ViewRootImpl.java revision e78ba24c176fd6a0c54eaf7e52be545952ba1ab7
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                        } else if ((mTempRect.top-scrollY) < vi.top) {
3082                            scrollY -= vi.top - (mTempRect.top-scrollY);
3083                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3084                                    "Top covered; scrollY=" + scrollY);
3085                        } else if ((mTempRect.bottom-scrollY)
3086                                > (mView.getHeight()-vi.bottom)) {
3087                            scrollY += (mTempRect.bottom-scrollY)
3088                                    - (mView.getHeight()-vi.bottom);
3089                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3090                                    "Bottom covered; scrollY=" + scrollY);
3091                        }
3092                        handled = true;
3093                    }
3094                }
3095            }
3096        }
3097
3098        if (scrollY != mScrollY) {
3099            if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Pan scroll changed: old="
3100                    + mScrollY + " , new=" + scrollY);
3101            if (!immediate) {
3102                if (mScroller == null) {
3103                    mScroller = new Scroller(mView.getContext());
3104                }
3105                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
3106            } else if (mScroller != null) {
3107                mScroller.abortAnimation();
3108            }
3109            mScrollY = scrollY;
3110        }
3111
3112        return handled;
3113    }
3114
3115    /**
3116     * @hide
3117     */
3118    public View getAccessibilityFocusedHost() {
3119        return mAccessibilityFocusedHost;
3120    }
3121
3122    /**
3123     * @hide
3124     */
3125    public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
3126        return mAccessibilityFocusedVirtualView;
3127    }
3128
3129    void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
3130        // If we have a virtual view with accessibility focus we need
3131        // to clear the focus and invalidate the virtual view bounds.
3132        if (mAccessibilityFocusedVirtualView != null) {
3133
3134            AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
3135            View focusHost = mAccessibilityFocusedHost;
3136
3137            // Wipe the state of the current accessibility focus since
3138            // the call into the provider to clear accessibility focus
3139            // will fire an accessibility event which will end up calling
3140            // this method and we want to have clean state when this
3141            // invocation happens.
3142            mAccessibilityFocusedHost = null;
3143            mAccessibilityFocusedVirtualView = null;
3144
3145            // Clear accessibility focus on the host after clearing state since
3146            // this method may be reentrant.
3147            focusHost.clearAccessibilityFocusNoCallbacks(
3148                    AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
3149
3150            AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
3151            if (provider != null) {
3152                // Invalidate the area of the cleared accessibility focus.
3153                focusNode.getBoundsInParent(mTempRect);
3154                focusHost.invalidate(mTempRect);
3155                // Clear accessibility focus in the virtual node.
3156                final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
3157                        focusNode.getSourceNodeId());
3158                provider.performAction(virtualNodeId,
3159                        AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
3160            }
3161            focusNode.recycle();
3162        }
3163        if (mAccessibilityFocusedHost != null) {
3164            // Clear accessibility focus in the view.
3165            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(
3166                    AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
3167        }
3168
3169        // Set the new focus host and node.
3170        mAccessibilityFocusedHost = view;
3171        mAccessibilityFocusedVirtualView = node;
3172
3173        if (mAttachInfo.mHardwareRenderer != null) {
3174            mAttachInfo.mHardwareRenderer.invalidateRoot();
3175        }
3176    }
3177
3178    @Override
3179    public void requestChildFocus(View child, View focused) {
3180        if (DEBUG_INPUT_RESIZE) {
3181            Log.v(mTag, "Request child focus: focus now " + focused);
3182        }
3183        checkThread();
3184        scheduleTraversals();
3185    }
3186
3187    @Override
3188    public void clearChildFocus(View child) {
3189        if (DEBUG_INPUT_RESIZE) {
3190            Log.v(mTag, "Clearing child focus");
3191        }
3192        checkThread();
3193        scheduleTraversals();
3194    }
3195
3196    @Override
3197    public ViewParent getParentForAccessibility() {
3198        return null;
3199    }
3200
3201    @Override
3202    public void focusableViewAvailable(View v) {
3203        checkThread();
3204        if (mView != null) {
3205            if (!mView.hasFocus()) {
3206                v.requestFocus();
3207            } else {
3208                // the one case where will transfer focus away from the current one
3209                // is if the current view is a view group that prefers to give focus
3210                // to its children first AND the view is a descendant of it.
3211                View focused = mView.findFocus();
3212                if (focused instanceof ViewGroup) {
3213                    ViewGroup group = (ViewGroup) focused;
3214                    if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3215                            && isViewDescendantOf(v, focused)) {
3216                        v.requestFocus();
3217                    }
3218                }
3219            }
3220        }
3221    }
3222
3223    @Override
3224    public void recomputeViewAttributes(View child) {
3225        checkThread();
3226        if (mView == child) {
3227            mAttachInfo.mRecomputeGlobalAttributes = true;
3228            if (!mWillDrawSoon) {
3229                scheduleTraversals();
3230            }
3231        }
3232    }
3233
3234    void dispatchDetachedFromWindow() {
3235        if (mView != null && mView.mAttachInfo != null) {
3236            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
3237            mView.dispatchDetachedFromWindow();
3238        }
3239
3240        mAccessibilityInteractionConnectionManager.ensureNoConnection();
3241        mAccessibilityManager.removeAccessibilityStateChangeListener(
3242                mAccessibilityInteractionConnectionManager);
3243        mAccessibilityManager.removeHighTextContrastStateChangeListener(
3244                mHighContrastTextManager);
3245        removeSendWindowContentChangedCallback();
3246
3247        destroyHardwareRenderer();
3248
3249        setAccessibilityFocus(null, null);
3250
3251        mView.assignParent(null);
3252        mView = null;
3253        mAttachInfo.mRootView = null;
3254
3255        mSurface.release();
3256
3257        if (mInputQueueCallback != null && mInputQueue != null) {
3258            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
3259            mInputQueue.dispose();
3260            mInputQueueCallback = null;
3261            mInputQueue = null;
3262        }
3263        if (mInputEventReceiver != null) {
3264            mInputEventReceiver.dispose();
3265            mInputEventReceiver = null;
3266        }
3267        try {
3268            mWindowSession.remove(mWindow);
3269        } catch (RemoteException e) {
3270        }
3271
3272        // Dispose the input channel after removing the window so the Window Manager
3273        // doesn't interpret the input channel being closed as an abnormal termination.
3274        if (mInputChannel != null) {
3275            mInputChannel.dispose();
3276            mInputChannel = null;
3277        }
3278
3279        mDisplayManager.unregisterDisplayListener(mDisplayListener);
3280
3281        unscheduleTraversals();
3282    }
3283
3284    void updateConfiguration(Configuration config, boolean force) {
3285        if (DEBUG_CONFIGURATION) Log.v(mTag,
3286                "Applying new config to window "
3287                + mWindowAttributes.getTitle()
3288                + ": " + config);
3289
3290        CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo();
3291        if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
3292            config = new Configuration(config);
3293            ci.applyToConfiguration(mNoncompatDensity, config);
3294        }
3295
3296        synchronized (sConfigCallbacks) {
3297            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
3298                sConfigCallbacks.get(i).onConfigurationChanged(config);
3299            }
3300        }
3301        if (mView != null) {
3302            // At this point the resources have been updated to
3303            // have the most recent config, whatever that is.  Use
3304            // the one in them which may be newer.
3305            config = mView.getResources().getConfiguration();
3306            if (force || mLastConfiguration.diff(config) != 0) {
3307                final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
3308                final int currentLayoutDirection = config.getLayoutDirection();
3309                mLastConfiguration.setTo(config);
3310                if (lastLayoutDirection != currentLayoutDirection &&
3311                        mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
3312                    mView.setLayoutDirection(currentLayoutDirection);
3313                }
3314                mView.dispatchConfigurationChanged(config);
3315            }
3316        }
3317    }
3318
3319    /**
3320     * Return true if child is an ancestor of parent, (or equal to the parent).
3321     */
3322    public static boolean isViewDescendantOf(View child, View parent) {
3323        if (child == parent) {
3324            return true;
3325        }
3326
3327        final ViewParent theParent = child.getParent();
3328        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
3329    }
3330
3331    private static void forceLayout(View view) {
3332        view.forceLayout();
3333        if (view instanceof ViewGroup) {
3334            ViewGroup group = (ViewGroup) view;
3335            final int count = group.getChildCount();
3336            for (int i = 0; i < count; i++) {
3337                forceLayout(group.getChildAt(i));
3338            }
3339        }
3340    }
3341
3342    private final static int MSG_INVALIDATE = 1;
3343    private final static int MSG_INVALIDATE_RECT = 2;
3344    private final static int MSG_DIE = 3;
3345    private final static int MSG_RESIZED = 4;
3346    private final static int MSG_RESIZED_REPORT = 5;
3347    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
3348    private final static int MSG_DISPATCH_INPUT_EVENT = 7;
3349    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
3350    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
3351    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
3352    private final static int MSG_CHECK_FOCUS = 13;
3353    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
3354    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
3355    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
3356    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
3357    private final static int MSG_UPDATE_CONFIGURATION = 18;
3358    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
3359    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
3360    private final static int MSG_INVALIDATE_WORLD = 22;
3361    private final static int MSG_WINDOW_MOVED = 23;
3362    private final static int MSG_SYNTHESIZE_INPUT_EVENT = 24;
3363    private final static int MSG_DISPATCH_WINDOW_SHOWN = 25;
3364    private final static int MSG_REQUEST_KEYBOARD_SHORTCUTS = 26;
3365    private final static int MSG_UPDATE_POINTER_ICON = 27;
3366
3367    final class ViewRootHandler extends Handler {
3368        @Override
3369        public String getMessageName(Message message) {
3370            switch (message.what) {
3371                case MSG_INVALIDATE:
3372                    return "MSG_INVALIDATE";
3373                case MSG_INVALIDATE_RECT:
3374                    return "MSG_INVALIDATE_RECT";
3375                case MSG_DIE:
3376                    return "MSG_DIE";
3377                case MSG_RESIZED:
3378                    return "MSG_RESIZED";
3379                case MSG_RESIZED_REPORT:
3380                    return "MSG_RESIZED_REPORT";
3381                case MSG_WINDOW_FOCUS_CHANGED:
3382                    return "MSG_WINDOW_FOCUS_CHANGED";
3383                case MSG_DISPATCH_INPUT_EVENT:
3384                    return "MSG_DISPATCH_INPUT_EVENT";
3385                case MSG_DISPATCH_APP_VISIBILITY:
3386                    return "MSG_DISPATCH_APP_VISIBILITY";
3387                case MSG_DISPATCH_GET_NEW_SURFACE:
3388                    return "MSG_DISPATCH_GET_NEW_SURFACE";
3389                case MSG_DISPATCH_KEY_FROM_IME:
3390                    return "MSG_DISPATCH_KEY_FROM_IME";
3391                case MSG_CHECK_FOCUS:
3392                    return "MSG_CHECK_FOCUS";
3393                case MSG_CLOSE_SYSTEM_DIALOGS:
3394                    return "MSG_CLOSE_SYSTEM_DIALOGS";
3395                case MSG_DISPATCH_DRAG_EVENT:
3396                    return "MSG_DISPATCH_DRAG_EVENT";
3397                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
3398                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
3399                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
3400                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
3401                case MSG_UPDATE_CONFIGURATION:
3402                    return "MSG_UPDATE_CONFIGURATION";
3403                case MSG_PROCESS_INPUT_EVENTS:
3404                    return "MSG_PROCESS_INPUT_EVENTS";
3405                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
3406                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
3407                case MSG_WINDOW_MOVED:
3408                    return "MSG_WINDOW_MOVED";
3409                case MSG_SYNTHESIZE_INPUT_EVENT:
3410                    return "MSG_SYNTHESIZE_INPUT_EVENT";
3411                case MSG_DISPATCH_WINDOW_SHOWN:
3412                    return "MSG_DISPATCH_WINDOW_SHOWN";
3413                case MSG_UPDATE_POINTER_ICON:
3414                    return "MSG_UPDATE_POINTER_ICON";
3415            }
3416            return super.getMessageName(message);
3417        }
3418
3419        @Override
3420        public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
3421            if (msg.what == MSG_REQUEST_KEYBOARD_SHORTCUTS && msg.obj == null) {
3422                // Debugging for b/27963013
3423                throw new NullPointerException(
3424                        "Attempted to call MSG_REQUEST_KEYBOARD_SHORTCUTS with null receiver:");
3425            }
3426            return super.sendMessageAtTime(msg, uptimeMillis);
3427        }
3428
3429        @Override
3430        public void handleMessage(Message msg) {
3431            switch (msg.what) {
3432            case MSG_INVALIDATE:
3433                ((View) msg.obj).invalidate();
3434                break;
3435            case MSG_INVALIDATE_RECT:
3436                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
3437                info.target.invalidate(info.left, info.top, info.right, info.bottom);
3438                info.recycle();
3439                break;
3440            case MSG_PROCESS_INPUT_EVENTS:
3441                mProcessInputEventsScheduled = false;
3442                doProcessInputEvents();
3443                break;
3444            case MSG_DISPATCH_APP_VISIBILITY:
3445                handleAppVisibility(msg.arg1 != 0);
3446                break;
3447            case MSG_DISPATCH_GET_NEW_SURFACE:
3448                handleGetNewSurface();
3449                break;
3450            case MSG_RESIZED: {
3451                // Recycled in the fall through...
3452                SomeArgs args = (SomeArgs) msg.obj;
3453                if (mWinFrame.equals(args.arg1)
3454                        && mPendingOverscanInsets.equals(args.arg5)
3455                        && mPendingContentInsets.equals(args.arg2)
3456                        && mPendingStableInsets.equals(args.arg6)
3457                        && mPendingVisibleInsets.equals(args.arg3)
3458                        && mPendingOutsets.equals(args.arg7)
3459                        && mPendingBackDropFrame.equals(args.arg8)
3460                        && args.arg4 == null
3461                        && args.argi1 == 0) {
3462                    break;
3463                }
3464                } // fall through...
3465            case MSG_RESIZED_REPORT:
3466                if (mAdded) {
3467                    SomeArgs args = (SomeArgs) msg.obj;
3468
3469                    Configuration config = (Configuration) args.arg4;
3470                    if (config != null) {
3471                        updateConfiguration(config, false);
3472                    }
3473
3474                    final boolean framesChanged = !mWinFrame.equals(args.arg1)
3475                            || !mPendingOverscanInsets.equals(args.arg5)
3476                            || !mPendingContentInsets.equals(args.arg2)
3477                            || !mPendingStableInsets.equals(args.arg6)
3478                            || !mPendingVisibleInsets.equals(args.arg3)
3479                            || !mPendingOutsets.equals(args.arg7);
3480
3481                    mWinFrame.set((Rect) args.arg1);
3482                    mPendingOverscanInsets.set((Rect) args.arg5);
3483                    mPendingContentInsets.set((Rect) args.arg2);
3484                    mPendingStableInsets.set((Rect) args.arg6);
3485                    mPendingVisibleInsets.set((Rect) args.arg3);
3486                    mPendingOutsets.set((Rect) args.arg7);
3487                    mPendingBackDropFrame.set((Rect) args.arg8);
3488                    mForceNextWindowRelayout = args.argi1 != 0;
3489                    mPendingAlwaysConsumeNavBar = args.argi2 != 0;
3490
3491                    args.recycle();
3492
3493                    if (msg.what == MSG_RESIZED_REPORT) {
3494                        mReportNextDraw = true;
3495                    }
3496
3497                    if (mView != null && framesChanged) {
3498                        forceLayout(mView);
3499                    }
3500
3501                    requestLayout();
3502                }
3503                break;
3504            case MSG_WINDOW_MOVED:
3505                if (mAdded) {
3506                    final int w = mWinFrame.width();
3507                    final int h = mWinFrame.height();
3508                    final int l = msg.arg1;
3509                    final int t = msg.arg2;
3510                    mWinFrame.left = l;
3511                    mWinFrame.right = l + w;
3512                    mWinFrame.top = t;
3513                    mWinFrame.bottom = t + h;
3514
3515                    mPendingBackDropFrame.set(mWinFrame);
3516
3517                    // Suppress layouts during resizing - a correct layout will happen when resizing
3518                    // is done, and this just increases system load.
3519                    boolean isDockedDivider = mWindowAttributes.type == TYPE_DOCK_DIVIDER;
3520                    boolean suppress = (mDragResizing && mResizeMode == RESIZE_MODE_DOCKED_DIVIDER)
3521                            || isDockedDivider;
3522                    if (!suppress) {
3523                        if (mView != null) {
3524                            forceLayout(mView);
3525                        }
3526                        requestLayout();
3527                    } else {
3528                        maybeHandleWindowMove(mWinFrame);
3529                    }
3530                }
3531                break;
3532            case MSG_WINDOW_FOCUS_CHANGED: {
3533                if (mAdded) {
3534                    boolean hasWindowFocus = msg.arg1 != 0;
3535                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
3536
3537                    profileRendering(hasWindowFocus);
3538
3539                    if (hasWindowFocus) {
3540                        boolean inTouchMode = msg.arg2 != 0;
3541                        ensureTouchModeLocally(inTouchMode);
3542
3543                        if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){
3544                            mFullRedrawNeeded = true;
3545                            try {
3546                                final WindowManager.LayoutParams lp = mWindowAttributes;
3547                                final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null;
3548                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3549                                        mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
3550                            } catch (OutOfResourcesException e) {
3551                                Log.e(mTag, "OutOfResourcesException locking surface", e);
3552                                try {
3553                                    if (!mWindowSession.outOfMemory(mWindow)) {
3554                                        Slog.w(mTag, "No processes killed for memory; killing self");
3555                                        Process.killProcess(Process.myPid());
3556                                    }
3557                                } catch (RemoteException ex) {
3558                                }
3559                                // Retry in a bit.
3560                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3561                                return;
3562                            }
3563                        }
3564                    }
3565
3566                    mLastWasImTarget = WindowManager.LayoutParams
3567                            .mayUseInputMethod(mWindowAttributes.flags);
3568
3569                    InputMethodManager imm = InputMethodManager.peekInstance();
3570                    if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3571                        imm.onPreWindowFocus(mView, hasWindowFocus);
3572                    }
3573                    if (mView != null) {
3574                        mAttachInfo.mKeyDispatchState.reset();
3575                        mView.dispatchWindowFocusChanged(hasWindowFocus);
3576                        mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
3577                    }
3578
3579                    // Note: must be done after the focus change callbacks,
3580                    // so all of the view state is set up correctly.
3581                    if (hasWindowFocus) {
3582                        if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3583                            imm.onPostWindowFocus(mView, mView.findFocus(),
3584                                    mWindowAttributes.softInputMode,
3585                                    !mHasHadWindowFocus, mWindowAttributes.flags);
3586                        }
3587                        // Clear the forward bit.  We can just do this directly, since
3588                        // the window manager doesn't care about it.
3589                        mWindowAttributes.softInputMode &=
3590                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3591                        ((WindowManager.LayoutParams)mView.getLayoutParams())
3592                                .softInputMode &=
3593                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3594                        mHasHadWindowFocus = true;
3595                    }
3596                }
3597            } break;
3598            case MSG_DIE:
3599                doDie();
3600                break;
3601            case MSG_DISPATCH_INPUT_EVENT: {
3602                SomeArgs args = (SomeArgs)msg.obj;
3603                InputEvent event = (InputEvent)args.arg1;
3604                InputEventReceiver receiver = (InputEventReceiver)args.arg2;
3605                enqueueInputEvent(event, receiver, 0, true);
3606                args.recycle();
3607            } break;
3608            case MSG_SYNTHESIZE_INPUT_EVENT: {
3609                InputEvent event = (InputEvent)msg.obj;
3610                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true);
3611            } break;
3612            case MSG_DISPATCH_KEY_FROM_IME: {
3613                if (LOCAL_LOGV) Log.v(
3614                    TAG, "Dispatching key "
3615                    + msg.obj + " from IME to " + mView);
3616                KeyEvent event = (KeyEvent)msg.obj;
3617                if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3618                    // The IME is trying to say this event is from the
3619                    // system!  Bad bad bad!
3620                    //noinspection UnusedAssignment
3621                    event = KeyEvent.changeFlags(event, event.getFlags() &
3622                            ~KeyEvent.FLAG_FROM_SYSTEM);
3623                }
3624                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3625            } break;
3626            case MSG_CHECK_FOCUS: {
3627                InputMethodManager imm = InputMethodManager.peekInstance();
3628                if (imm != null) {
3629                    imm.checkFocus();
3630                }
3631            } break;
3632            case MSG_CLOSE_SYSTEM_DIALOGS: {
3633                if (mView != null) {
3634                    mView.onCloseSystemDialogs((String)msg.obj);
3635                }
3636            } break;
3637            case MSG_DISPATCH_DRAG_EVENT:
3638            case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3639                DragEvent event = (DragEvent)msg.obj;
3640                event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
3641                handleDragEvent(event);
3642            } break;
3643            case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3644                handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3645            } break;
3646            case MSG_UPDATE_CONFIGURATION: {
3647                Configuration config = (Configuration)msg.obj;
3648                if (config.isOtherSeqNewer(mLastConfiguration)) {
3649                    config = mLastConfiguration;
3650                }
3651                updateConfiguration(config, false);
3652            } break;
3653            case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3654                setAccessibilityFocus(null, null);
3655            } break;
3656            case MSG_INVALIDATE_WORLD: {
3657                if (mView != null) {
3658                    invalidateWorld(mView);
3659                }
3660            } break;
3661            case MSG_DISPATCH_WINDOW_SHOWN: {
3662                handleDispatchWindowShown();
3663            } break;
3664            case MSG_REQUEST_KEYBOARD_SHORTCUTS: {
3665                final IResultReceiver receiver = (IResultReceiver) msg.obj;
3666                final int deviceId = msg.arg1;
3667                handleRequestKeyboardShortcuts(receiver, deviceId);
3668            } break;
3669            case MSG_UPDATE_POINTER_ICON: {
3670                MotionEvent event = (MotionEvent) msg.obj;
3671                resetPointerIcon(event);
3672            } break;
3673            }
3674        }
3675    }
3676
3677    final ViewRootHandler mHandler = new ViewRootHandler();
3678
3679    /**
3680     * Something in the current window tells us we need to change the touch mode.  For
3681     * example, we are not in touch mode, and the user touches the screen.
3682     *
3683     * If the touch mode has changed, tell the window manager, and handle it locally.
3684     *
3685     * @param inTouchMode Whether we want to be in touch mode.
3686     * @return True if the touch mode changed and focus changed was changed as a result
3687     */
3688    boolean ensureTouchMode(boolean inTouchMode) {
3689        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3690                + "touch mode is " + mAttachInfo.mInTouchMode);
3691        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3692
3693        // tell the window manager
3694        try {
3695            mWindowSession.setInTouchMode(inTouchMode);
3696        } catch (RemoteException e) {
3697            throw new RuntimeException(e);
3698        }
3699
3700        // handle the change
3701        return ensureTouchModeLocally(inTouchMode);
3702    }
3703
3704    /**
3705     * Ensure that the touch mode for this window is set, and if it is changing,
3706     * take the appropriate action.
3707     * @param inTouchMode Whether we want to be in touch mode.
3708     * @return True if the touch mode changed and focus changed was changed as a result
3709     */
3710    private boolean ensureTouchModeLocally(boolean inTouchMode) {
3711        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3712                + "touch mode is " + mAttachInfo.mInTouchMode);
3713
3714        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3715
3716        mAttachInfo.mInTouchMode = inTouchMode;
3717        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3718
3719        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3720    }
3721
3722    private boolean enterTouchMode() {
3723        if (mView != null && mView.hasFocus()) {
3724            // note: not relying on mFocusedView here because this could
3725            // be when the window is first being added, and mFocused isn't
3726            // set yet.
3727            final View focused = mView.findFocus();
3728            if (focused != null && !focused.isFocusableInTouchMode()) {
3729                final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused);
3730                if (ancestorToTakeFocus != null) {
3731                    // there is an ancestor that wants focus after its
3732                    // descendants that is focusable in touch mode.. give it
3733                    // focus
3734                    return ancestorToTakeFocus.requestFocus();
3735                } else {
3736                    // There's nothing to focus. Clear and propagate through the
3737                    // hierarchy, but don't attempt to place new focus.
3738                    focused.clearFocusInternal(null, true, false);
3739                    return true;
3740                }
3741            }
3742        }
3743        return false;
3744    }
3745
3746    /**
3747     * Find an ancestor of focused that wants focus after its descendants and is
3748     * focusable in touch mode.
3749     * @param focused The currently focused view.
3750     * @return An appropriate view, or null if no such view exists.
3751     */
3752    private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3753        ViewParent parent = focused.getParent();
3754        while (parent instanceof ViewGroup) {
3755            final ViewGroup vgParent = (ViewGroup) parent;
3756            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3757                    && vgParent.isFocusableInTouchMode()) {
3758                return vgParent;
3759            }
3760            if (vgParent.isRootNamespace()) {
3761                return null;
3762            } else {
3763                parent = vgParent.getParent();
3764            }
3765        }
3766        return null;
3767    }
3768
3769    private boolean leaveTouchMode() {
3770        if (mView != null) {
3771            if (mView.hasFocus()) {
3772                View focusedView = mView.findFocus();
3773                if (!(focusedView instanceof ViewGroup)) {
3774                    // some view has focus, let it keep it
3775                    return false;
3776                } else if (((ViewGroup) focusedView).getDescendantFocusability() !=
3777                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3778                    // some view group has focus, and doesn't prefer its children
3779                    // over itself for focus, so let them keep it.
3780                    return false;
3781                }
3782            }
3783
3784            // find the best view to give focus to in this brave new non-touch-mode
3785            // world
3786            final View focused = focusSearch(null, View.FOCUS_DOWN);
3787            if (focused != null) {
3788                return focused.requestFocus(View.FOCUS_DOWN);
3789            }
3790        }
3791        return false;
3792    }
3793
3794    /**
3795     * Base class for implementing a stage in the chain of responsibility
3796     * for processing input events.
3797     * <p>
3798     * Events are delivered to the stage by the {@link #deliver} method.  The stage
3799     * then has the choice of finishing the event or forwarding it to the next stage.
3800     * </p>
3801     */
3802    abstract class InputStage {
3803        private final InputStage mNext;
3804
3805        protected static final int FORWARD = 0;
3806        protected static final int FINISH_HANDLED = 1;
3807        protected static final int FINISH_NOT_HANDLED = 2;
3808
3809        /**
3810         * Creates an input stage.
3811         * @param next The next stage to which events should be forwarded.
3812         */
3813        public InputStage(InputStage next) {
3814            mNext = next;
3815        }
3816
3817        /**
3818         * Delivers an event to be processed.
3819         */
3820        public final void deliver(QueuedInputEvent q) {
3821            if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
3822                forward(q);
3823            } else if (shouldDropInputEvent(q)) {
3824                finish(q, false);
3825            } else {
3826                apply(q, onProcess(q));
3827            }
3828        }
3829
3830        /**
3831         * Marks the the input event as finished then forwards it to the next stage.
3832         */
3833        protected void finish(QueuedInputEvent q, boolean handled) {
3834            q.mFlags |= QueuedInputEvent.FLAG_FINISHED;
3835            if (handled) {
3836                q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;
3837            }
3838            forward(q);
3839        }
3840
3841        /**
3842         * Forwards the event to the next stage.
3843         */
3844        protected void forward(QueuedInputEvent q) {
3845            onDeliverToNext(q);
3846        }
3847
3848        /**
3849         * Applies a result code from {@link #onProcess} to the specified event.
3850         */
3851        protected void apply(QueuedInputEvent q, int result) {
3852            if (result == FORWARD) {
3853                forward(q);
3854            } else if (result == FINISH_HANDLED) {
3855                finish(q, true);
3856            } else if (result == FINISH_NOT_HANDLED) {
3857                finish(q, false);
3858            } else {
3859                throw new IllegalArgumentException("Invalid result: " + result);
3860            }
3861        }
3862
3863        /**
3864         * Called when an event is ready to be processed.
3865         * @return A result code indicating how the event was handled.
3866         */
3867        protected int onProcess(QueuedInputEvent q) {
3868            return FORWARD;
3869        }
3870
3871        /**
3872         * Called when an event is being delivered to the next stage.
3873         */
3874        protected void onDeliverToNext(QueuedInputEvent q) {
3875            if (DEBUG_INPUT_STAGES) {
3876                Log.v(mTag, "Done with " + getClass().getSimpleName() + ". " + q);
3877            }
3878            if (mNext != null) {
3879                mNext.deliver(q);
3880            } else {
3881                finishInputEvent(q);
3882            }
3883        }
3884
3885        protected boolean shouldDropInputEvent(QueuedInputEvent q) {
3886            if (mView == null || !mAdded) {
3887                Slog.w(mTag, "Dropping event due to root view being removed: " + q.mEvent);
3888                return true;
3889            } else if ((!mAttachInfo.mHasWindowFocus
3890                    && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) || mStopped
3891                    || (mIsAmbientMode && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_BUTTON))
3892                    || (mPausedForTransition && !isBack(q.mEvent))) {
3893                // This is a focus event and the window doesn't currently have input focus or
3894                // has stopped. This could be an event that came back from the previous stage
3895                // but the window has lost focus or stopped in the meantime.
3896                if (isTerminalInputEvent(q.mEvent)) {
3897                    // Don't drop terminal input events, however mark them as canceled.
3898                    q.mEvent.cancel();
3899                    Slog.w(mTag, "Cancelling event due to no window focus: " + q.mEvent);
3900                    return false;
3901                }
3902
3903                // Drop non-terminal input events.
3904                Slog.w(mTag, "Dropping event due to no window focus: " + q.mEvent);
3905                return true;
3906            }
3907            return false;
3908        }
3909
3910        void dump(String prefix, PrintWriter writer) {
3911            if (mNext != null) {
3912                mNext.dump(prefix, writer);
3913            }
3914        }
3915
3916        private boolean isBack(InputEvent event) {
3917            if (event instanceof KeyEvent) {
3918                return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK;
3919            } else {
3920                return false;
3921            }
3922        }
3923    }
3924
3925    /**
3926     * Base class for implementing an input pipeline stage that supports
3927     * asynchronous and out-of-order processing of input events.
3928     * <p>
3929     * In addition to what a normal input stage can do, an asynchronous
3930     * input stage may also defer an input event that has been delivered to it
3931     * and finish or forward it later.
3932     * </p>
3933     */
3934    abstract class AsyncInputStage extends InputStage {
3935        private final String mTraceCounter;
3936
3937        private QueuedInputEvent mQueueHead;
3938        private QueuedInputEvent mQueueTail;
3939        private int mQueueLength;
3940
3941        protected static final int DEFER = 3;
3942
3943        /**
3944         * Creates an asynchronous input stage.
3945         * @param next The next stage to which events should be forwarded.
3946         * @param traceCounter The name of a counter to record the size of
3947         * the queue of pending events.
3948         */
3949        public AsyncInputStage(InputStage next, String traceCounter) {
3950            super(next);
3951            mTraceCounter = traceCounter;
3952        }
3953
3954        /**
3955         * Marks the event as deferred, which is to say that it will be handled
3956         * asynchronously.  The caller is responsible for calling {@link #forward}
3957         * or {@link #finish} later when it is done handling the event.
3958         */
3959        protected void defer(QueuedInputEvent q) {
3960            q.mFlags |= QueuedInputEvent.FLAG_DEFERRED;
3961            enqueue(q);
3962        }
3963
3964        @Override
3965        protected void forward(QueuedInputEvent q) {
3966            // Clear the deferred flag.
3967            q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
3968
3969            // Fast path if the queue is empty.
3970            QueuedInputEvent curr = mQueueHead;
3971            if (curr == null) {
3972                super.forward(q);
3973                return;
3974            }
3975
3976            // Determine whether the event must be serialized behind any others
3977            // before it can be delivered to the next stage.  This is done because
3978            // deferred events might be handled out of order by the stage.
3979            final int deviceId = q.mEvent.getDeviceId();
3980            QueuedInputEvent prev = null;
3981            boolean blocked = false;
3982            while (curr != null && curr != q) {
3983                if (!blocked && deviceId == curr.mEvent.getDeviceId()) {
3984                    blocked = true;
3985                }
3986                prev = curr;
3987                curr = curr.mNext;
3988            }
3989
3990            // If the event is blocked, then leave it in the queue to be delivered later.
3991            // Note that the event might not yet be in the queue if it was not previously
3992            // deferred so we will enqueue it if needed.
3993            if (blocked) {
3994                if (curr == null) {
3995                    enqueue(q);
3996                }
3997                return;
3998            }
3999
4000            // The event is not blocked.  Deliver it immediately.
4001            if (curr != null) {
4002                curr = curr.mNext;
4003                dequeue(q, prev);
4004            }
4005            super.forward(q);
4006
4007            // Dequeuing this event may have unblocked successors.  Deliver them.
4008            while (curr != null) {
4009                if (deviceId == curr.mEvent.getDeviceId()) {
4010                    if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) {
4011                        break;
4012                    }
4013                    QueuedInputEvent next = curr.mNext;
4014                    dequeue(curr, prev);
4015                    super.forward(curr);
4016                    curr = next;
4017                } else {
4018                    prev = curr;
4019                    curr = curr.mNext;
4020                }
4021            }
4022        }
4023
4024        @Override
4025        protected void apply(QueuedInputEvent q, int result) {
4026            if (result == DEFER) {
4027                defer(q);
4028            } else {
4029                super.apply(q, result);
4030            }
4031        }
4032
4033        private void enqueue(QueuedInputEvent q) {
4034            if (mQueueTail == null) {
4035                mQueueHead = q;
4036                mQueueTail = q;
4037            } else {
4038                mQueueTail.mNext = q;
4039                mQueueTail = q;
4040            }
4041
4042            mQueueLength += 1;
4043            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
4044        }
4045
4046        private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) {
4047            if (prev == null) {
4048                mQueueHead = q.mNext;
4049            } else {
4050                prev.mNext = q.mNext;
4051            }
4052            if (mQueueTail == q) {
4053                mQueueTail = prev;
4054            }
4055            q.mNext = null;
4056
4057            mQueueLength -= 1;
4058            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
4059        }
4060
4061        @Override
4062        void dump(String prefix, PrintWriter writer) {
4063            writer.print(prefix);
4064            writer.print(getClass().getName());
4065            writer.print(": mQueueLength=");
4066            writer.println(mQueueLength);
4067
4068            super.dump(prefix, writer);
4069        }
4070    }
4071
4072    /**
4073     * Delivers pre-ime input events to a native activity.
4074     * Does not support pointer events.
4075     */
4076    final class NativePreImeInputStage extends AsyncInputStage
4077            implements InputQueue.FinishedInputEventCallback {
4078        public NativePreImeInputStage(InputStage next, String traceCounter) {
4079            super(next, traceCounter);
4080        }
4081
4082        @Override
4083        protected int onProcess(QueuedInputEvent q) {
4084            if (mInputQueue != null && q.mEvent instanceof KeyEvent) {
4085                mInputQueue.sendInputEvent(q.mEvent, q, true, this);
4086                return DEFER;
4087            }
4088            return FORWARD;
4089        }
4090
4091        @Override
4092        public void onFinishedInputEvent(Object token, boolean handled) {
4093            QueuedInputEvent q = (QueuedInputEvent)token;
4094            if (handled) {
4095                finish(q, true);
4096                return;
4097            }
4098            forward(q);
4099        }
4100    }
4101
4102    /**
4103     * Delivers pre-ime input events to the view hierarchy.
4104     * Does not support pointer events.
4105     */
4106    final class ViewPreImeInputStage extends InputStage {
4107        public ViewPreImeInputStage(InputStage next) {
4108            super(next);
4109        }
4110
4111        @Override
4112        protected int onProcess(QueuedInputEvent q) {
4113            if (q.mEvent instanceof KeyEvent) {
4114                return processKeyEvent(q);
4115            }
4116            return FORWARD;
4117        }
4118
4119        private int processKeyEvent(QueuedInputEvent q) {
4120            final KeyEvent event = (KeyEvent)q.mEvent;
4121            if (mView.dispatchKeyEventPreIme(event)) {
4122                return FINISH_HANDLED;
4123            }
4124            return FORWARD;
4125        }
4126    }
4127
4128    /**
4129     * Delivers input events to the ime.
4130     * Does not support pointer events.
4131     */
4132    final class ImeInputStage extends AsyncInputStage
4133            implements InputMethodManager.FinishedInputEventCallback {
4134        public ImeInputStage(InputStage next, String traceCounter) {
4135            super(next, traceCounter);
4136        }
4137
4138        @Override
4139        protected int onProcess(QueuedInputEvent q) {
4140            if (mLastWasImTarget && !isInLocalFocusMode()) {
4141                InputMethodManager imm = InputMethodManager.peekInstance();
4142                if (imm != null) {
4143                    final InputEvent event = q.mEvent;
4144                    if (DEBUG_IMF) Log.v(mTag, "Sending input event to IME: " + event);
4145                    int result = imm.dispatchInputEvent(event, q, this, mHandler);
4146                    if (result == InputMethodManager.DISPATCH_HANDLED) {
4147                        return FINISH_HANDLED;
4148                    } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) {
4149                        // The IME could not handle it, so skip along to the next InputStage
4150                        return FORWARD;
4151                    } else {
4152                        return DEFER; // callback will be invoked later
4153                    }
4154                }
4155            }
4156            return FORWARD;
4157        }
4158
4159        @Override
4160        public void onFinishedInputEvent(Object token, boolean handled) {
4161            QueuedInputEvent q = (QueuedInputEvent)token;
4162            if (handled) {
4163                finish(q, true);
4164                return;
4165            }
4166            forward(q);
4167        }
4168    }
4169
4170    /**
4171     * Performs early processing of post-ime input events.
4172     */
4173    final class EarlyPostImeInputStage extends InputStage {
4174        public EarlyPostImeInputStage(InputStage next) {
4175            super(next);
4176        }
4177
4178        @Override
4179        protected int onProcess(QueuedInputEvent q) {
4180            if (q.mEvent instanceof KeyEvent) {
4181                return processKeyEvent(q);
4182            } else {
4183                final int source = q.mEvent.getSource();
4184                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
4185                    return processPointerEvent(q);
4186                }
4187            }
4188            return FORWARD;
4189        }
4190
4191        private int processKeyEvent(QueuedInputEvent q) {
4192            final KeyEvent event = (KeyEvent)q.mEvent;
4193
4194            // If the key's purpose is to exit touch mode then we consume it
4195            // and consider it handled.
4196            if (checkForLeavingTouchModeAndConsume(event)) {
4197                return FINISH_HANDLED;
4198            }
4199
4200            // Make sure the fallback event policy sees all keys that will be
4201            // delivered to the view hierarchy.
4202            mFallbackEventHandler.preDispatchKeyEvent(event);
4203            return FORWARD;
4204        }
4205
4206        private int processPointerEvent(QueuedInputEvent q) {
4207            final MotionEvent event = (MotionEvent)q.mEvent;
4208
4209            // Translate the pointer event for compatibility, if needed.
4210            if (mTranslator != null) {
4211                mTranslator.translateEventInScreenToAppWindow(event);
4212            }
4213
4214            // Enter touch mode on down or scroll.
4215            final int action = event.getAction();
4216            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
4217                ensureTouchMode(true);
4218            }
4219
4220            // Offset the scroll position.
4221            if (mCurScrollY != 0) {
4222                event.offsetLocation(0, mCurScrollY);
4223            }
4224
4225            // Remember the touch position for possible drag-initiation.
4226            if (event.isTouchEvent()) {
4227                mLastTouchPoint.x = event.getRawX();
4228                mLastTouchPoint.y = event.getRawY();
4229                mLastTouchSource = event.getSource();
4230            }
4231            return FORWARD;
4232        }
4233    }
4234
4235    /**
4236     * Delivers post-ime input events to a native activity.
4237     */
4238    final class NativePostImeInputStage extends AsyncInputStage
4239            implements InputQueue.FinishedInputEventCallback {
4240        public NativePostImeInputStage(InputStage next, String traceCounter) {
4241            super(next, traceCounter);
4242        }
4243
4244        @Override
4245        protected int onProcess(QueuedInputEvent q) {
4246            if (mInputQueue != null) {
4247                mInputQueue.sendInputEvent(q.mEvent, q, false, this);
4248                return DEFER;
4249            }
4250            return FORWARD;
4251        }
4252
4253        @Override
4254        public void onFinishedInputEvent(Object token, boolean handled) {
4255            QueuedInputEvent q = (QueuedInputEvent)token;
4256            if (handled) {
4257                finish(q, true);
4258                return;
4259            }
4260            forward(q);
4261        }
4262    }
4263
4264    /**
4265     * Delivers post-ime input events to the view hierarchy.
4266     */
4267    final class ViewPostImeInputStage extends InputStage {
4268        public ViewPostImeInputStage(InputStage next) {
4269            super(next);
4270        }
4271
4272        @Override
4273        protected int onProcess(QueuedInputEvent q) {
4274            if (q.mEvent instanceof KeyEvent) {
4275                return processKeyEvent(q);
4276            } else {
4277                final int source = q.mEvent.getSource();
4278                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
4279                    return processPointerEvent(q);
4280                } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4281                    return processTrackballEvent(q);
4282                } else {
4283                    return processGenericMotionEvent(q);
4284                }
4285            }
4286        }
4287
4288        @Override
4289        protected void onDeliverToNext(QueuedInputEvent q) {
4290            if (mUnbufferedInputDispatch
4291                    && q.mEvent instanceof MotionEvent
4292                    && ((MotionEvent)q.mEvent).isTouchEvent()
4293                    && isTerminalInputEvent(q.mEvent)) {
4294                mUnbufferedInputDispatch = false;
4295                scheduleConsumeBatchedInput();
4296            }
4297            super.onDeliverToNext(q);
4298        }
4299
4300        private int processKeyEvent(QueuedInputEvent q) {
4301            final KeyEvent event = (KeyEvent)q.mEvent;
4302
4303            // Deliver the key to the view hierarchy.
4304            if (mView.dispatchKeyEvent(event)) {
4305                return FINISH_HANDLED;
4306            }
4307
4308            if (shouldDropInputEvent(q)) {
4309                return FINISH_NOT_HANDLED;
4310            }
4311
4312            // If the Control modifier is held, try to interpret the key as a shortcut.
4313            if (event.getAction() == KeyEvent.ACTION_DOWN
4314                    && event.isCtrlPressed()
4315                    && event.getRepeatCount() == 0
4316                    && !KeyEvent.isModifierKey(event.getKeyCode())) {
4317                if (mView.dispatchKeyShortcutEvent(event)) {
4318                    return FINISH_HANDLED;
4319                }
4320                if (shouldDropInputEvent(q)) {
4321                    return FINISH_NOT_HANDLED;
4322                }
4323            }
4324
4325            // Apply the fallback event policy.
4326            if (mFallbackEventHandler.dispatchKeyEvent(event)) {
4327                return FINISH_HANDLED;
4328            }
4329            if (shouldDropInputEvent(q)) {
4330                return FINISH_NOT_HANDLED;
4331            }
4332
4333            // Handle automatic focus changes.
4334            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4335                int direction = 0;
4336                switch (event.getKeyCode()) {
4337                    case KeyEvent.KEYCODE_DPAD_LEFT:
4338                        if (event.hasNoModifiers()) {
4339                            direction = View.FOCUS_LEFT;
4340                        }
4341                        break;
4342                    case KeyEvent.KEYCODE_DPAD_RIGHT:
4343                        if (event.hasNoModifiers()) {
4344                            direction = View.FOCUS_RIGHT;
4345                        }
4346                        break;
4347                    case KeyEvent.KEYCODE_DPAD_UP:
4348                        if (event.hasNoModifiers()) {
4349                            direction = View.FOCUS_UP;
4350                        }
4351                        break;
4352                    case KeyEvent.KEYCODE_DPAD_DOWN:
4353                        if (event.hasNoModifiers()) {
4354                            direction = View.FOCUS_DOWN;
4355                        }
4356                        break;
4357                    case KeyEvent.KEYCODE_TAB:
4358                        if (event.hasNoModifiers()) {
4359                            direction = View.FOCUS_FORWARD;
4360                        } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
4361                            direction = View.FOCUS_BACKWARD;
4362                        }
4363                        break;
4364                }
4365                if (direction != 0) {
4366                    View focused = mView.findFocus();
4367                    if (focused != null) {
4368                        View v = focused.focusSearch(direction);
4369                        if (v != null && v != focused) {
4370                            // do the math the get the interesting rect
4371                            // of previous focused into the coord system of
4372                            // newly focused view
4373                            focused.getFocusedRect(mTempRect);
4374                            if (mView instanceof ViewGroup) {
4375                                ((ViewGroup) mView).offsetDescendantRectToMyCoords(
4376                                        focused, mTempRect);
4377                                ((ViewGroup) mView).offsetRectIntoDescendantCoords(
4378                                        v, mTempRect);
4379                            }
4380                            if (v.requestFocus(direction, mTempRect)) {
4381                                playSoundEffect(SoundEffectConstants
4382                                        .getContantForFocusDirection(direction));
4383                                return FINISH_HANDLED;
4384                            }
4385                        }
4386
4387                        // Give the focused view a last chance to handle the dpad key.
4388                        if (mView.dispatchUnhandledMove(focused, direction)) {
4389                            return FINISH_HANDLED;
4390                        }
4391                    } else {
4392                        // find the best view to give focus to in this non-touch-mode with no-focus
4393                        View v = focusSearch(null, direction);
4394                        if (v != null && v.requestFocus(direction)) {
4395                            return FINISH_HANDLED;
4396                        }
4397                    }
4398                }
4399            }
4400            return FORWARD;
4401        }
4402
4403        private int processPointerEvent(QueuedInputEvent q) {
4404            final MotionEvent event = (MotionEvent)q.mEvent;
4405
4406            mAttachInfo.mUnbufferedDispatchRequested = false;
4407            final View eventTarget =
4408                    (event.isFromSource(InputDevice.SOURCE_MOUSE) && mCapturingView != null) ?
4409                            mCapturingView : mView;
4410            mAttachInfo.mHandlingPointerEvent = true;
4411            boolean handled = eventTarget.dispatchPointerEvent(event);
4412            maybeUpdatePointerIcon(event);
4413            mAttachInfo.mHandlingPointerEvent = false;
4414            if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4415                mUnbufferedInputDispatch = true;
4416                if (mConsumeBatchedInputScheduled) {
4417                    scheduleConsumeBatchedInputImmediately();
4418                }
4419            }
4420            return handled ? FINISH_HANDLED : FORWARD;
4421        }
4422
4423        private void maybeUpdatePointerIcon(MotionEvent event) {
4424            if (event.getPointerCount() == 1 && event.isFromSource(InputDevice.SOURCE_MOUSE)) {
4425                if (event.getActionMasked() == MotionEvent.ACTION_HOVER_ENTER
4426                        || event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
4427                    // Other apps or the window manager may change the icon type outside of
4428                    // this app, therefore the icon type has to be reset on enter/exit event.
4429                    mPointerIconType = PointerIcon.TYPE_NOT_SPECIFIED;
4430                }
4431
4432                if (event.getActionMasked() != MotionEvent.ACTION_HOVER_EXIT) {
4433                    if (!updatePointerIcon(event) &&
4434                            event.getActionMasked() == MotionEvent.ACTION_HOVER_MOVE) {
4435                        mPointerIconType = PointerIcon.TYPE_NOT_SPECIFIED;
4436                    }
4437                }
4438            }
4439        }
4440
4441        private int processTrackballEvent(QueuedInputEvent q) {
4442            final MotionEvent event = (MotionEvent)q.mEvent;
4443
4444            if (mView.dispatchTrackballEvent(event)) {
4445                return FINISH_HANDLED;
4446            }
4447            return FORWARD;
4448        }
4449
4450        private int processGenericMotionEvent(QueuedInputEvent q) {
4451            final MotionEvent event = (MotionEvent)q.mEvent;
4452
4453            // Deliver the event to the view.
4454            if (mView.dispatchGenericMotionEvent(event)) {
4455                return FINISH_HANDLED;
4456            }
4457            return FORWARD;
4458        }
4459    }
4460
4461    private void resetPointerIcon(MotionEvent event) {
4462        mPointerIconType = PointerIcon.TYPE_NOT_SPECIFIED;
4463        updatePointerIcon(event);
4464    }
4465
4466    private boolean updatePointerIcon(MotionEvent event) {
4467        final int pointerIndex = 0;
4468        final float x = event.getX(pointerIndex);
4469        final float y = event.getY(pointerIndex);
4470        if (mView == null) {
4471            // E.g. click outside a popup to dismiss it
4472            Slog.d(mTag, "updatePointerIcon called after view was removed");
4473            return false;
4474        }
4475        if (x < 0 || x >= mView.getWidth() || y < 0 || y >= mView.getHeight()) {
4476            // E.g. when moving window divider with mouse
4477            Slog.d(mTag, "updatePointerIcon called with position out of bounds");
4478            return false;
4479        }
4480        final PointerIcon pointerIcon = mView.onResolvePointerIcon(event, pointerIndex);
4481        final int pointerType = (pointerIcon != null) ?
4482                pointerIcon.getType() : PointerIcon.TYPE_DEFAULT;
4483
4484        if (mPointerIconType != pointerType) {
4485            mPointerIconType = pointerType;
4486            if (mPointerIconType != PointerIcon.TYPE_CUSTOM) {
4487                mCustomPointerIcon = null;
4488                InputManager.getInstance().setPointerIconType(pointerType);
4489                return true;
4490            }
4491        }
4492        if (mPointerIconType == PointerIcon.TYPE_CUSTOM &&
4493                !pointerIcon.equals(mCustomPointerIcon)) {
4494            mCustomPointerIcon = pointerIcon;
4495            InputManager.getInstance().setCustomPointerIcon(mCustomPointerIcon);
4496        }
4497        return true;
4498    }
4499
4500    /**
4501     * Performs synthesis of new input events from unhandled input events.
4502     */
4503    final class SyntheticInputStage extends InputStage {
4504        private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
4505        private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
4506        private final SyntheticTouchNavigationHandler mTouchNavigation =
4507                new SyntheticTouchNavigationHandler();
4508        private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
4509
4510        public SyntheticInputStage() {
4511            super(null);
4512        }
4513
4514        @Override
4515        protected int onProcess(QueuedInputEvent q) {
4516            q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
4517            if (q.mEvent instanceof MotionEvent) {
4518                final MotionEvent event = (MotionEvent)q.mEvent;
4519                final int source = event.getSource();
4520                if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4521                    mTrackball.process(event);
4522                    return FINISH_HANDLED;
4523                } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4524                    mJoystick.process(event);
4525                    return FINISH_HANDLED;
4526                } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4527                        == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4528                    mTouchNavigation.process(event);
4529                    return FINISH_HANDLED;
4530                }
4531            } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4532                mKeyboard.process((KeyEvent)q.mEvent);
4533                return FINISH_HANDLED;
4534            }
4535
4536            return FORWARD;
4537        }
4538
4539        @Override
4540        protected void onDeliverToNext(QueuedInputEvent q) {
4541            if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
4542                // Cancel related synthetic events if any prior stage has handled the event.
4543                if (q.mEvent instanceof MotionEvent) {
4544                    final MotionEvent event = (MotionEvent)q.mEvent;
4545                    final int source = event.getSource();
4546                    if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4547                        mTrackball.cancel(event);
4548                    } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4549                        mJoystick.cancel(event);
4550                    } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4551                            == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4552                        mTouchNavigation.cancel(event);
4553                    }
4554                }
4555            }
4556            super.onDeliverToNext(q);
4557        }
4558    }
4559
4560    /**
4561     * Creates dpad events from unhandled trackball movements.
4562     */
4563    final class SyntheticTrackballHandler {
4564        private final TrackballAxis mX = new TrackballAxis();
4565        private final TrackballAxis mY = new TrackballAxis();
4566        private long mLastTime;
4567
4568        public void process(MotionEvent event) {
4569            // Translate the trackball event into DPAD keys and try to deliver those.
4570            long curTime = SystemClock.uptimeMillis();
4571            if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
4572                // It has been too long since the last movement,
4573                // so restart at the beginning.
4574                mX.reset(0);
4575                mY.reset(0);
4576                mLastTime = curTime;
4577            }
4578
4579            final int action = event.getAction();
4580            final int metaState = event.getMetaState();
4581            switch (action) {
4582                case MotionEvent.ACTION_DOWN:
4583                    mX.reset(2);
4584                    mY.reset(2);
4585                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4586                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4587                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4588                            InputDevice.SOURCE_KEYBOARD));
4589                    break;
4590                case MotionEvent.ACTION_UP:
4591                    mX.reset(2);
4592                    mY.reset(2);
4593                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4594                            KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4595                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4596                            InputDevice.SOURCE_KEYBOARD));
4597                    break;
4598            }
4599
4600            if (DEBUG_TRACKBALL) Log.v(mTag, "TB X=" + mX.position + " step="
4601                    + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
4602                    + " move=" + event.getX()
4603                    + " / Y=" + mY.position + " step="
4604                    + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
4605                    + " move=" + event.getY());
4606            final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
4607            final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
4608
4609            // Generate DPAD events based on the trackball movement.
4610            // We pick the axis that has moved the most as the direction of
4611            // the DPAD.  When we generate DPAD events for one axis, then the
4612            // other axis is reset -- we don't want to perform DPAD jumps due
4613            // to slight movements in the trackball when making major movements
4614            // along the other axis.
4615            int keycode = 0;
4616            int movement = 0;
4617            float accel = 1;
4618            if (xOff > yOff) {
4619                movement = mX.generate();
4620                if (movement != 0) {
4621                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
4622                            : KeyEvent.KEYCODE_DPAD_LEFT;
4623                    accel = mX.acceleration;
4624                    mY.reset(2);
4625                }
4626            } else if (yOff > 0) {
4627                movement = mY.generate();
4628                if (movement != 0) {
4629                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
4630                            : KeyEvent.KEYCODE_DPAD_UP;
4631                    accel = mY.acceleration;
4632                    mX.reset(2);
4633                }
4634            }
4635
4636            if (keycode != 0) {
4637                if (movement < 0) movement = -movement;
4638                int accelMovement = (int)(movement * accel);
4639                if (DEBUG_TRACKBALL) Log.v(mTag, "Move: movement=" + movement
4640                        + " accelMovement=" + accelMovement
4641                        + " accel=" + accel);
4642                if (accelMovement > movement) {
4643                    if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
4644                            + keycode);
4645                    movement--;
4646                    int repeatCount = accelMovement - movement;
4647                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4648                            KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
4649                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4650                            InputDevice.SOURCE_KEYBOARD));
4651                }
4652                while (movement > 0) {
4653                    if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
4654                            + keycode);
4655                    movement--;
4656                    curTime = SystemClock.uptimeMillis();
4657                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4658                            KeyEvent.ACTION_DOWN, keycode, 0, metaState,
4659                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4660                            InputDevice.SOURCE_KEYBOARD));
4661                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4662                            KeyEvent.ACTION_UP, keycode, 0, metaState,
4663                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4664                            InputDevice.SOURCE_KEYBOARD));
4665                }
4666                mLastTime = curTime;
4667            }
4668        }
4669
4670        public void cancel(MotionEvent event) {
4671            mLastTime = Integer.MIN_VALUE;
4672
4673            // If we reach this, we consumed a trackball event.
4674            // Because we will not translate the trackball event into a key event,
4675            // touch mode will not exit, so we exit touch mode here.
4676            if (mView != null && mAdded) {
4677                ensureTouchMode(false);
4678            }
4679        }
4680    }
4681
4682    /**
4683     * Maintains state information for a single trackball axis, generating
4684     * discrete (DPAD) movements based on raw trackball motion.
4685     */
4686    static final class TrackballAxis {
4687        /**
4688         * The maximum amount of acceleration we will apply.
4689         */
4690        static final float MAX_ACCELERATION = 20;
4691
4692        /**
4693         * The maximum amount of time (in milliseconds) between events in order
4694         * for us to consider the user to be doing fast trackball movements,
4695         * and thus apply an acceleration.
4696         */
4697        static final long FAST_MOVE_TIME = 150;
4698
4699        /**
4700         * Scaling factor to the time (in milliseconds) between events to how
4701         * much to multiple/divide the current acceleration.  When movement
4702         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4703         * FAST_MOVE_TIME it divides it.
4704         */
4705        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4706
4707        static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
4708        static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
4709        static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
4710
4711        float position;
4712        float acceleration = 1;
4713        long lastMoveTime = 0;
4714        int step;
4715        int dir;
4716        int nonAccelMovement;
4717
4718        void reset(int _step) {
4719            position = 0;
4720            acceleration = 1;
4721            lastMoveTime = 0;
4722            step = _step;
4723            dir = 0;
4724        }
4725
4726        /**
4727         * Add trackball movement into the state.  If the direction of movement
4728         * has been reversed, the state is reset before adding the
4729         * movement (so that you don't have to compensate for any previously
4730         * collected movement before see the result of the movement in the
4731         * new direction).
4732         *
4733         * @return Returns the absolute value of the amount of movement
4734         * collected so far.
4735         */
4736        float collect(float off, long time, String axis) {
4737            long normTime;
4738            if (off > 0) {
4739                normTime = (long)(off * FAST_MOVE_TIME);
4740                if (dir < 0) {
4741                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4742                    position = 0;
4743                    step = 0;
4744                    acceleration = 1;
4745                    lastMoveTime = 0;
4746                }
4747                dir = 1;
4748            } else if (off < 0) {
4749                normTime = (long)((-off) * FAST_MOVE_TIME);
4750                if (dir > 0) {
4751                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4752                    position = 0;
4753                    step = 0;
4754                    acceleration = 1;
4755                    lastMoveTime = 0;
4756                }
4757                dir = -1;
4758            } else {
4759                normTime = 0;
4760            }
4761
4762            // The number of milliseconds between each movement that is
4763            // considered "normal" and will not result in any acceleration
4764            // or deceleration, scaled by the offset we have here.
4765            if (normTime > 0) {
4766                long delta = time - lastMoveTime;
4767                lastMoveTime = time;
4768                float acc = acceleration;
4769                if (delta < normTime) {
4770                    // The user is scrolling rapidly, so increase acceleration.
4771                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4772                    if (scale > 1) acc *= scale;
4773                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4774                            + off + " normTime=" + normTime + " delta=" + delta
4775                            + " scale=" + scale + " acc=" + acc);
4776                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4777                } else {
4778                    // The user is scrolling slowly, so decrease acceleration.
4779                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4780                    if (scale > 1) acc /= scale;
4781                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4782                            + off + " normTime=" + normTime + " delta=" + delta
4783                            + " scale=" + scale + " acc=" + acc);
4784                    acceleration = acc > 1 ? acc : 1;
4785                }
4786            }
4787            position += off;
4788            return Math.abs(position);
4789        }
4790
4791        /**
4792         * Generate the number of discrete movement events appropriate for
4793         * the currently collected trackball movement.
4794         *
4795         * @return Returns the number of discrete movements, either positive
4796         * or negative, or 0 if there is not enough trackball movement yet
4797         * for a discrete movement.
4798         */
4799        int generate() {
4800            int movement = 0;
4801            nonAccelMovement = 0;
4802            do {
4803                final int dir = position >= 0 ? 1 : -1;
4804                switch (step) {
4805                    // If we are going to execute the first step, then we want
4806                    // to do this as soon as possible instead of waiting for
4807                    // a full movement, in order to make things look responsive.
4808                    case 0:
4809                        if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4810                            return movement;
4811                        }
4812                        movement += dir;
4813                        nonAccelMovement += dir;
4814                        step = 1;
4815                        break;
4816                    // If we have generated the first movement, then we need
4817                    // to wait for the second complete trackball motion before
4818                    // generating the second discrete movement.
4819                    case 1:
4820                        if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4821                            return movement;
4822                        }
4823                        movement += dir;
4824                        nonAccelMovement += dir;
4825                        position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
4826                        step = 2;
4827                        break;
4828                    // After the first two, we generate discrete movements
4829                    // consistently with the trackball, applying an acceleration
4830                    // if the trackball is moving quickly.  This is a simple
4831                    // acceleration on top of what we already compute based
4832                    // on how quickly the wheel is being turned, to apply
4833                    // a longer increasing acceleration to continuous movement
4834                    // in one direction.
4835                    default:
4836                        if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4837                            return movement;
4838                        }
4839                        movement += dir;
4840                        position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4841                        float acc = acceleration;
4842                        acc *= 1.1f;
4843                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4844                        break;
4845                }
4846            } while (true);
4847        }
4848    }
4849
4850    /**
4851     * Creates dpad events from unhandled joystick movements.
4852     */
4853    final class SyntheticJoystickHandler extends Handler {
4854        private final static String TAG = "SyntheticJoystickHandler";
4855        private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
4856        private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
4857
4858        private int mLastXDirection;
4859        private int mLastYDirection;
4860        private int mLastXKeyCode;
4861        private int mLastYKeyCode;
4862
4863        public SyntheticJoystickHandler() {
4864            super(true);
4865        }
4866
4867        @Override
4868        public void handleMessage(Message msg) {
4869            switch (msg.what) {
4870                case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
4871                case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
4872                    KeyEvent oldEvent = (KeyEvent)msg.obj;
4873                    KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
4874                            SystemClock.uptimeMillis(),
4875                            oldEvent.getRepeatCount() + 1);
4876                    if (mAttachInfo.mHasWindowFocus) {
4877                        enqueueInputEvent(e);
4878                        Message m = obtainMessage(msg.what, e);
4879                        m.setAsynchronous(true);
4880                        sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
4881                    }
4882                } break;
4883            }
4884        }
4885
4886        public void process(MotionEvent event) {
4887            switch(event.getActionMasked()) {
4888            case MotionEvent.ACTION_CANCEL:
4889                cancel(event);
4890                break;
4891            case MotionEvent.ACTION_MOVE:
4892                update(event, true);
4893                break;
4894            default:
4895                Log.w(mTag, "Unexpected action: " + event.getActionMasked());
4896            }
4897        }
4898
4899        private void cancel(MotionEvent event) {
4900            removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4901            removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4902            update(event, false);
4903        }
4904
4905        private void update(MotionEvent event, boolean synthesizeNewKeys) {
4906            final long time = event.getEventTime();
4907            final int metaState = event.getMetaState();
4908            final int deviceId = event.getDeviceId();
4909            final int source = event.getSource();
4910
4911            int xDirection = joystickAxisValueToDirection(
4912                    event.getAxisValue(MotionEvent.AXIS_HAT_X));
4913            if (xDirection == 0) {
4914                xDirection = joystickAxisValueToDirection(event.getX());
4915            }
4916
4917            int yDirection = joystickAxisValueToDirection(
4918                    event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4919            if (yDirection == 0) {
4920                yDirection = joystickAxisValueToDirection(event.getY());
4921            }
4922
4923            if (xDirection != mLastXDirection) {
4924                if (mLastXKeyCode != 0) {
4925                    removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4926                    enqueueInputEvent(new KeyEvent(time, time,
4927                            KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState,
4928                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4929                    mLastXKeyCode = 0;
4930                }
4931
4932                mLastXDirection = xDirection;
4933
4934                if (xDirection != 0 && synthesizeNewKeys) {
4935                    mLastXKeyCode = xDirection > 0
4936                            ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
4937                    final KeyEvent e = new KeyEvent(time, time,
4938                            KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState,
4939                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4940                    enqueueInputEvent(e);
4941                    Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
4942                    m.setAsynchronous(true);
4943                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4944                }
4945            }
4946
4947            if (yDirection != mLastYDirection) {
4948                if (mLastYKeyCode != 0) {
4949                    removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4950                    enqueueInputEvent(new KeyEvent(time, time,
4951                            KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState,
4952                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4953                    mLastYKeyCode = 0;
4954                }
4955
4956                mLastYDirection = yDirection;
4957
4958                if (yDirection != 0 && synthesizeNewKeys) {
4959                    mLastYKeyCode = yDirection > 0
4960                            ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
4961                    final KeyEvent e = new KeyEvent(time, time,
4962                            KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState,
4963                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4964                    enqueueInputEvent(e);
4965                    Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e);
4966                    m.setAsynchronous(true);
4967                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4968                }
4969            }
4970        }
4971
4972        private int joystickAxisValueToDirection(float value) {
4973            if (value >= 0.5f) {
4974                return 1;
4975            } else if (value <= -0.5f) {
4976                return -1;
4977            } else {
4978                return 0;
4979            }
4980        }
4981    }
4982
4983    /**
4984     * Creates dpad events from unhandled touch navigation movements.
4985     */
4986    final class SyntheticTouchNavigationHandler extends Handler {
4987        private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4988        private static final boolean LOCAL_DEBUG = false;
4989
4990        // Assumed nominal width and height in millimeters of a touch navigation pad,
4991        // if no resolution information is available from the input system.
4992        private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
4993        private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
4994
4995        /* TODO: These constants should eventually be moved to ViewConfiguration. */
4996
4997        // The nominal distance traveled to move by one unit.
4998        private static final int TICK_DISTANCE_MILLIMETERS = 12;
4999
5000        // Minimum and maximum fling velocity in ticks per second.
5001        // The minimum velocity should be set such that we perform enough ticks per
5002        // second that the fling appears to be fluid.  For example, if we set the minimum
5003        // to 2 ticks per second, then there may be up to half a second delay between the next
5004        // to last and last ticks which is noticeably discrete and jerky.  This value should
5005        // probably not be set to anything less than about 4.
5006        // If fling accuracy is a problem then consider tuning the tick distance instead.
5007        private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
5008        private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
5009
5010        // Fling velocity decay factor applied after each new key is emitted.
5011        // This parameter controls the deceleration and overall duration of the fling.
5012        // The fling stops automatically when its velocity drops below the minimum
5013        // fling velocity defined above.
5014        private static final float FLING_TICK_DECAY = 0.8f;
5015
5016        /* The input device that we are tracking. */
5017
5018        private int mCurrentDeviceId = -1;
5019        private int mCurrentSource;
5020        private boolean mCurrentDeviceSupported;
5021
5022        /* Configuration for the current input device. */
5023
5024        // The scaled tick distance.  A movement of this amount should generally translate
5025        // into a single dpad event in a given direction.
5026        private float mConfigTickDistance;
5027
5028        // The minimum and maximum scaled fling velocity.
5029        private float mConfigMinFlingVelocity;
5030        private float mConfigMaxFlingVelocity;
5031
5032        /* Tracking state. */
5033
5034        // The velocity tracker for detecting flings.
5035        private VelocityTracker mVelocityTracker;
5036
5037        // The active pointer id, or -1 if none.
5038        private int mActivePointerId = -1;
5039
5040        // Location where tracking started.
5041        private float mStartX;
5042        private float mStartY;
5043
5044        // Most recently observed position.
5045        private float mLastX;
5046        private float mLastY;
5047
5048        // Accumulated movement delta since the last direction key was sent.
5049        private float mAccumulatedX;
5050        private float mAccumulatedY;
5051
5052        // Set to true if any movement was delivered to the app.
5053        // Implies that tap slop was exceeded.
5054        private boolean mConsumedMovement;
5055
5056        // The most recently sent key down event.
5057        // The keycode remains set until the direction changes or a fling ends
5058        // so that repeated key events may be generated as required.
5059        private long mPendingKeyDownTime;
5060        private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
5061        private int mPendingKeyRepeatCount;
5062        private int mPendingKeyMetaState;
5063
5064        // The current fling velocity while a fling is in progress.
5065        private boolean mFlinging;
5066        private float mFlingVelocity;
5067
5068        public SyntheticTouchNavigationHandler() {
5069            super(true);
5070        }
5071
5072        public void process(MotionEvent event) {
5073            // Update the current device information.
5074            final long time = event.getEventTime();
5075            final int deviceId = event.getDeviceId();
5076            final int source = event.getSource();
5077            if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
5078                finishKeys(time);
5079                finishTracking(time);
5080                mCurrentDeviceId = deviceId;
5081                mCurrentSource = source;
5082                mCurrentDeviceSupported = false;
5083                InputDevice device = event.getDevice();
5084                if (device != null) {
5085                    // In order to support an input device, we must know certain
5086                    // characteristics about it, such as its size and resolution.
5087                    InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
5088                    InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
5089                    if (xRange != null && yRange != null) {
5090                        mCurrentDeviceSupported = true;
5091
5092                        // Infer the resolution if it not actually known.
5093                        float xRes = xRange.getResolution();
5094                        if (xRes <= 0) {
5095                            xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
5096                        }
5097                        float yRes = yRange.getResolution();
5098                        if (yRes <= 0) {
5099                            yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
5100                        }
5101                        float nominalRes = (xRes + yRes) * 0.5f;
5102
5103                        // Precompute all of the configuration thresholds we will need.
5104                        mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
5105                        mConfigMinFlingVelocity =
5106                                MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
5107                        mConfigMaxFlingVelocity =
5108                                MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
5109
5110                        if (LOCAL_DEBUG) {
5111                            Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
5112                                    + " (" + Integer.toHexString(mCurrentSource) + "): "
5113                                    + ", mConfigTickDistance=" + mConfigTickDistance
5114                                    + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
5115                                    + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
5116                        }
5117                    }
5118                }
5119            }
5120            if (!mCurrentDeviceSupported) {
5121                return;
5122            }
5123
5124            // Handle the event.
5125            final int action = event.getActionMasked();
5126            switch (action) {
5127                case MotionEvent.ACTION_DOWN: {
5128                    boolean caughtFling = mFlinging;
5129                    finishKeys(time);
5130                    finishTracking(time);
5131                    mActivePointerId = event.getPointerId(0);
5132                    mVelocityTracker = VelocityTracker.obtain();
5133                    mVelocityTracker.addMovement(event);
5134                    mStartX = event.getX();
5135                    mStartY = event.getY();
5136                    mLastX = mStartX;
5137                    mLastY = mStartY;
5138                    mAccumulatedX = 0;
5139                    mAccumulatedY = 0;
5140
5141                    // If we caught a fling, then pretend that the tap slop has already
5142                    // been exceeded to suppress taps whose only purpose is to stop the fling.
5143                    mConsumedMovement = caughtFling;
5144                    break;
5145                }
5146
5147                case MotionEvent.ACTION_MOVE:
5148                case MotionEvent.ACTION_UP: {
5149                    if (mActivePointerId < 0) {
5150                        break;
5151                    }
5152                    final int index = event.findPointerIndex(mActivePointerId);
5153                    if (index < 0) {
5154                        finishKeys(time);
5155                        finishTracking(time);
5156                        break;
5157                    }
5158
5159                    mVelocityTracker.addMovement(event);
5160                    final float x = event.getX(index);
5161                    final float y = event.getY(index);
5162                    mAccumulatedX += x - mLastX;
5163                    mAccumulatedY += y - mLastY;
5164                    mLastX = x;
5165                    mLastY = y;
5166
5167                    // Consume any accumulated movement so far.
5168                    final int metaState = event.getMetaState();
5169                    consumeAccumulatedMovement(time, metaState);
5170
5171                    // Detect taps and flings.
5172                    if (action == MotionEvent.ACTION_UP) {
5173                        if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
5174                            // It might be a fling.
5175                            mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
5176                            final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
5177                            final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
5178                            if (!startFling(time, vx, vy)) {
5179                                finishKeys(time);
5180                            }
5181                        }
5182                        finishTracking(time);
5183                    }
5184                    break;
5185                }
5186
5187                case MotionEvent.ACTION_CANCEL: {
5188                    finishKeys(time);
5189                    finishTracking(time);
5190                    break;
5191                }
5192            }
5193        }
5194
5195        public void cancel(MotionEvent event) {
5196            if (mCurrentDeviceId == event.getDeviceId()
5197                    && mCurrentSource == event.getSource()) {
5198                final long time = event.getEventTime();
5199                finishKeys(time);
5200                finishTracking(time);
5201            }
5202        }
5203
5204        private void finishKeys(long time) {
5205            cancelFling();
5206            sendKeyUp(time);
5207        }
5208
5209        private void finishTracking(long time) {
5210            if (mActivePointerId >= 0) {
5211                mActivePointerId = -1;
5212                mVelocityTracker.recycle();
5213                mVelocityTracker = null;
5214            }
5215        }
5216
5217        private void consumeAccumulatedMovement(long time, int metaState) {
5218            final float absX = Math.abs(mAccumulatedX);
5219            final float absY = Math.abs(mAccumulatedY);
5220            if (absX >= absY) {
5221                if (absX >= mConfigTickDistance) {
5222                    mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
5223                            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
5224                    mAccumulatedY = 0;
5225                    mConsumedMovement = true;
5226                }
5227            } else {
5228                if (absY >= mConfigTickDistance) {
5229                    mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
5230                            KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
5231                    mAccumulatedX = 0;
5232                    mConsumedMovement = true;
5233                }
5234            }
5235        }
5236
5237        private float consumeAccumulatedMovement(long time, int metaState,
5238                float accumulator, int negativeKeyCode, int positiveKeyCode) {
5239            while (accumulator <= -mConfigTickDistance) {
5240                sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
5241                accumulator += mConfigTickDistance;
5242            }
5243            while (accumulator >= mConfigTickDistance) {
5244                sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
5245                accumulator -= mConfigTickDistance;
5246            }
5247            return accumulator;
5248        }
5249
5250        private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
5251            if (mPendingKeyCode != keyCode) {
5252                sendKeyUp(time);
5253                mPendingKeyDownTime = time;
5254                mPendingKeyCode = keyCode;
5255                mPendingKeyRepeatCount = 0;
5256            } else {
5257                mPendingKeyRepeatCount += 1;
5258            }
5259            mPendingKeyMetaState = metaState;
5260
5261            // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
5262            // but it doesn't quite make sense when simulating the events in this way.
5263            if (LOCAL_DEBUG) {
5264                Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
5265                        + ", repeatCount=" + mPendingKeyRepeatCount
5266                        + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
5267            }
5268            enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
5269                    KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
5270                    mPendingKeyMetaState, mCurrentDeviceId,
5271                    KeyEvent.FLAG_FALLBACK, mCurrentSource));
5272        }
5273
5274        private void sendKeyUp(long time) {
5275            if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
5276                if (LOCAL_DEBUG) {
5277                    Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
5278                            + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
5279                }
5280                enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
5281                        KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
5282                        mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
5283                        mCurrentSource));
5284                mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
5285            }
5286        }
5287
5288        private boolean startFling(long time, float vx, float vy) {
5289            if (LOCAL_DEBUG) {
5290                Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
5291                        + ", min=" + mConfigMinFlingVelocity);
5292            }
5293
5294            // Flings must be oriented in the same direction as the preceding movements.
5295            switch (mPendingKeyCode) {
5296                case KeyEvent.KEYCODE_DPAD_LEFT:
5297                    if (-vx >= mConfigMinFlingVelocity
5298                            && Math.abs(vy) < mConfigMinFlingVelocity) {
5299                        mFlingVelocity = -vx;
5300                        break;
5301                    }
5302                    return false;
5303
5304                case KeyEvent.KEYCODE_DPAD_RIGHT:
5305                    if (vx >= mConfigMinFlingVelocity
5306                            && Math.abs(vy) < mConfigMinFlingVelocity) {
5307                        mFlingVelocity = vx;
5308                        break;
5309                    }
5310                    return false;
5311
5312                case KeyEvent.KEYCODE_DPAD_UP:
5313                    if (-vy >= mConfigMinFlingVelocity
5314                            && Math.abs(vx) < mConfigMinFlingVelocity) {
5315                        mFlingVelocity = -vy;
5316                        break;
5317                    }
5318                    return false;
5319
5320                case KeyEvent.KEYCODE_DPAD_DOWN:
5321                    if (vy >= mConfigMinFlingVelocity
5322                            && Math.abs(vx) < mConfigMinFlingVelocity) {
5323                        mFlingVelocity = vy;
5324                        break;
5325                    }
5326                    return false;
5327            }
5328
5329            // Post the first fling event.
5330            mFlinging = postFling(time);
5331            return mFlinging;
5332        }
5333
5334        private boolean postFling(long time) {
5335            // The idea here is to estimate the time when the pointer would have
5336            // traveled one tick distance unit given the current fling velocity.
5337            // This effect creates continuity of motion.
5338            if (mFlingVelocity >= mConfigMinFlingVelocity) {
5339                long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
5340                postAtTime(mFlingRunnable, time + delay);
5341                if (LOCAL_DEBUG) {
5342                    Log.d(LOCAL_TAG, "Posted fling: velocity="
5343                            + mFlingVelocity + ", delay=" + delay
5344                            + ", keyCode=" + mPendingKeyCode);
5345                }
5346                return true;
5347            }
5348            return false;
5349        }
5350
5351        private void cancelFling() {
5352            if (mFlinging) {
5353                removeCallbacks(mFlingRunnable);
5354                mFlinging = false;
5355            }
5356        }
5357
5358        private final Runnable mFlingRunnable = new Runnable() {
5359            @Override
5360            public void run() {
5361                final long time = SystemClock.uptimeMillis();
5362                sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5363                mFlingVelocity *= FLING_TICK_DECAY;
5364                if (!postFling(time)) {
5365                    mFlinging = false;
5366                    finishKeys(time);
5367                }
5368            }
5369        };
5370    }
5371
5372    final class SyntheticKeyboardHandler {
5373        public void process(KeyEvent event) {
5374            if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5375                return;
5376            }
5377
5378            final KeyCharacterMap kcm = event.getKeyCharacterMap();
5379            final int keyCode = event.getKeyCode();
5380            final int metaState = event.getMetaState();
5381
5382            // Check for fallback actions specified by the key character map.
5383            KeyCharacterMap.FallbackAction fallbackAction =
5384                    kcm.getFallbackAction(keyCode, metaState);
5385            if (fallbackAction != null) {
5386                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5387                KeyEvent fallbackEvent = KeyEvent.obtain(
5388                        event.getDownTime(), event.getEventTime(),
5389                        event.getAction(), fallbackAction.keyCode,
5390                        event.getRepeatCount(), fallbackAction.metaState,
5391                        event.getDeviceId(), event.getScanCode(),
5392                        flags, event.getSource(), null);
5393                fallbackAction.recycle();
5394                enqueueInputEvent(fallbackEvent);
5395            }
5396        }
5397    }
5398
5399    /**
5400     * Returns true if the key is used for keyboard navigation.
5401     * @param keyEvent The key event.
5402     * @return True if the key is used for keyboard navigation.
5403     */
5404    private static boolean isNavigationKey(KeyEvent keyEvent) {
5405        switch (keyEvent.getKeyCode()) {
5406        case KeyEvent.KEYCODE_DPAD_LEFT:
5407        case KeyEvent.KEYCODE_DPAD_RIGHT:
5408        case KeyEvent.KEYCODE_DPAD_UP:
5409        case KeyEvent.KEYCODE_DPAD_DOWN:
5410        case KeyEvent.KEYCODE_DPAD_CENTER:
5411        case KeyEvent.KEYCODE_PAGE_UP:
5412        case KeyEvent.KEYCODE_PAGE_DOWN:
5413        case KeyEvent.KEYCODE_MOVE_HOME:
5414        case KeyEvent.KEYCODE_MOVE_END:
5415        case KeyEvent.KEYCODE_TAB:
5416        case KeyEvent.KEYCODE_SPACE:
5417        case KeyEvent.KEYCODE_ENTER:
5418            return true;
5419        }
5420        return false;
5421    }
5422
5423    /**
5424     * Returns true if the key is used for typing.
5425     * @param keyEvent The key event.
5426     * @return True if the key is used for typing.
5427     */
5428    private static boolean isTypingKey(KeyEvent keyEvent) {
5429        return keyEvent.getUnicodeChar() > 0;
5430    }
5431
5432    /**
5433     * See if the key event means we should leave touch mode (and leave touch mode if so).
5434     * @param event The key event.
5435     * @return Whether this key event should be consumed (meaning the act of
5436     *   leaving touch mode alone is considered the event).
5437     */
5438    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
5439        // Only relevant in touch mode.
5440        if (!mAttachInfo.mInTouchMode) {
5441            return false;
5442        }
5443
5444        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
5445        final int action = event.getAction();
5446        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
5447            return false;
5448        }
5449
5450        // Don't leave touch mode if the IME told us not to.
5451        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
5452            return false;
5453        }
5454
5455        // If the key can be used for keyboard navigation then leave touch mode
5456        // and select a focused view if needed (in ensureTouchMode).
5457        // When a new focused view is selected, we consume the navigation key because
5458        // navigation doesn't make much sense unless a view already has focus so
5459        // the key's purpose is to set focus.
5460        if (isNavigationKey(event)) {
5461            return ensureTouchMode(false);
5462        }
5463
5464        // If the key can be used for typing then leave touch mode
5465        // and select a focused view if needed (in ensureTouchMode).
5466        // Always allow the view to process the typing key.
5467        if (isTypingKey(event)) {
5468            ensureTouchMode(false);
5469            return false;
5470        }
5471
5472        return false;
5473    }
5474
5475    /* drag/drop */
5476    void setLocalDragState(Object obj) {
5477        mLocalDragState = obj;
5478    }
5479
5480    private void handleDragEvent(DragEvent event) {
5481        // From the root, only drag start/end/location are dispatched.  entered/exited
5482        // are determined and dispatched by the viewgroup hierarchy, who then report
5483        // that back here for ultimate reporting back to the framework.
5484        if (mView != null && mAdded) {
5485            final int what = event.mAction;
5486
5487            if (what == DragEvent.ACTION_DRAG_EXITED) {
5488                // A direct EXITED event means that the window manager knows we've just crossed
5489                // a window boundary, so the current drag target within this one must have
5490                // just been exited.  Send it the usual notifications and then we're done
5491                // for now.
5492                mView.dispatchDragEvent(event);
5493            } else {
5494                // Cache the drag description when the operation starts, then fill it in
5495                // on subsequent calls as a convenience
5496                if (what == DragEvent.ACTION_DRAG_STARTED) {
5497                    mCurrentDragView = null;    // Start the current-recipient tracking
5498                    mDragDescription = event.mClipDescription;
5499                } else {
5500                    event.mClipDescription = mDragDescription;
5501                }
5502
5503                // For events with a [screen] location, translate into window coordinates
5504                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
5505                    mDragPoint.set(event.mX, event.mY);
5506                    if (mTranslator != null) {
5507                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
5508                    }
5509
5510                    if (mCurScrollY != 0) {
5511                        mDragPoint.offset(0, mCurScrollY);
5512                    }
5513
5514                    event.mX = mDragPoint.x;
5515                    event.mY = mDragPoint.y;
5516                }
5517
5518                // Remember who the current drag target is pre-dispatch
5519                final View prevDragView = mCurrentDragView;
5520
5521                // Now dispatch the drag/drop event
5522                boolean result = mView.dispatchDragEvent(event);
5523
5524                // If we changed apparent drag target, tell the OS about it
5525                if (prevDragView != mCurrentDragView) {
5526                    try {
5527                        if (prevDragView != null) {
5528                            mWindowSession.dragRecipientExited(mWindow);
5529                        }
5530                        if (mCurrentDragView != null) {
5531                            mWindowSession.dragRecipientEntered(mWindow);
5532                        }
5533                    } catch (RemoteException e) {
5534                        Slog.e(mTag, "Unable to note drag target change");
5535                    }
5536                }
5537
5538                // Report the drop result when we're done
5539                if (what == DragEvent.ACTION_DROP) {
5540                    mDragDescription = null;
5541                    try {
5542                        Log.i(mTag, "Reporting drop result: " + result);
5543                        mWindowSession.reportDropResult(mWindow, result);
5544                    } catch (RemoteException e) {
5545                        Log.e(mTag, "Unable to report drop result");
5546                    }
5547                }
5548
5549                // When the drag operation ends, reset drag-related state
5550                if (what == DragEvent.ACTION_DRAG_ENDED) {
5551                    setLocalDragState(null);
5552                    mAttachInfo.mDragToken = null;
5553                    if (mAttachInfo.mDragSurface != null) {
5554                        mAttachInfo.mDragSurface.release();
5555                        mAttachInfo.mDragSurface = null;
5556                    }
5557                }
5558            }
5559        }
5560        event.recycle();
5561    }
5562
5563    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
5564        if (mSeq != args.seq) {
5565            // The sequence has changed, so we need to update our value and make
5566            // sure to do a traversal afterward so the window manager is given our
5567            // most recent data.
5568            mSeq = args.seq;
5569            mAttachInfo.mForceReportNewAttributes = true;
5570            scheduleTraversals();
5571        }
5572        if (mView == null) return;
5573        if (args.localChanges != 0) {
5574            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
5575        }
5576
5577        int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5578        if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5579            mAttachInfo.mGlobalSystemUiVisibility = visibility;
5580            mView.dispatchSystemUiVisibilityChanged(visibility);
5581        }
5582    }
5583
5584    public void handleDispatchWindowShown() {
5585        mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5586    }
5587
5588    public void handleRequestKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
5589        Bundle data = new Bundle();
5590        ArrayList<KeyboardShortcutGroup> list = new ArrayList<>();
5591        if (mView != null) {
5592            mView.requestKeyboardShortcuts(list, deviceId);
5593        }
5594        data.putParcelableArrayList(WindowManager.PARCEL_KEY_SHORTCUTS_ARRAY, list);
5595        try {
5596            receiver.send(0, data);
5597        } catch (RemoteException e) {
5598        }
5599    }
5600
5601    public void getLastTouchPoint(Point outLocation) {
5602        outLocation.x = (int) mLastTouchPoint.x;
5603        outLocation.y = (int) mLastTouchPoint.y;
5604    }
5605
5606    public int getLastTouchSource() {
5607        return mLastTouchSource;
5608    }
5609
5610    public void setDragFocus(View newDragTarget) {
5611        if (mCurrentDragView != newDragTarget) {
5612            mCurrentDragView = newDragTarget;
5613        }
5614    }
5615
5616    private AudioManager getAudioManager() {
5617        if (mView == null) {
5618            throw new IllegalStateException("getAudioManager called when there is no mView");
5619        }
5620        if (mAudioManager == null) {
5621            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5622        }
5623        return mAudioManager;
5624    }
5625
5626    public AccessibilityInteractionController getAccessibilityInteractionController() {
5627        if (mView == null) {
5628            throw new IllegalStateException("getAccessibilityInteractionController"
5629                    + " called when there is no mView");
5630        }
5631        if (mAccessibilityInteractionController == null) {
5632            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
5633        }
5634        return mAccessibilityInteractionController;
5635    }
5636
5637    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5638            boolean insetsPending) throws RemoteException {
5639
5640        float appScale = mAttachInfo.mApplicationScale;
5641        boolean restore = false;
5642        if (params != null && mTranslator != null) {
5643            restore = true;
5644            params.backup();
5645            mTranslator.translateWindowLayout(params);
5646        }
5647        if (params != null) {
5648            if (DBG) Log.d(mTag, "WindowLayout in layoutWindow:" + params);
5649        }
5650        mPendingConfiguration.seq = 0;
5651        //Log.d(mTag, ">>>>>> CALLING relayout");
5652        if (params != null && mOrigWindowType != params.type) {
5653            // For compatibility with old apps, don't crash here.
5654            if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5655                Slog.w(mTag, "Window type can not be changed after "
5656                        + "the window is added; ignoring change of " + mView);
5657                params.type = mOrigWindowType;
5658            }
5659        }
5660        int relayoutResult = mWindowSession.relayout(
5661                mWindow, mSeq, params,
5662                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
5663                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
5664                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
5665                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
5666                mPendingStableInsets, mPendingOutsets, mPendingBackDropFrame, mPendingConfiguration,
5667                mSurface);
5668
5669        mPendingAlwaysConsumeNavBar =
5670                (relayoutResult & WindowManagerGlobal.RELAYOUT_RES_CONSUME_ALWAYS_NAV_BAR) != 0;
5671
5672        //Log.d(mTag, "<<<<<< BACK FROM relayout");
5673        if (restore) {
5674            params.restore();
5675        }
5676
5677        if (mTranslator != null) {
5678            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
5679            mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
5680            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5681            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
5682            mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
5683        }
5684        return relayoutResult;
5685    }
5686
5687    /**
5688     * {@inheritDoc}
5689     */
5690    @Override
5691    public void playSoundEffect(int effectId) {
5692        checkThread();
5693
5694        try {
5695            final AudioManager audioManager = getAudioManager();
5696
5697            switch (effectId) {
5698                case SoundEffectConstants.CLICK:
5699                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5700                    return;
5701                case SoundEffectConstants.NAVIGATION_DOWN:
5702                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5703                    return;
5704                case SoundEffectConstants.NAVIGATION_LEFT:
5705                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5706                    return;
5707                case SoundEffectConstants.NAVIGATION_RIGHT:
5708                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5709                    return;
5710                case SoundEffectConstants.NAVIGATION_UP:
5711                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5712                    return;
5713                default:
5714                    throw new IllegalArgumentException("unknown effect id " + effectId +
5715                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
5716            }
5717        } catch (IllegalStateException e) {
5718            // Exception thrown by getAudioManager() when mView is null
5719            Log.e(mTag, "FATAL EXCEPTION when attempting to play sound effect: " + e);
5720            e.printStackTrace();
5721        }
5722    }
5723
5724    /**
5725     * {@inheritDoc}
5726     */
5727    @Override
5728    public boolean performHapticFeedback(int effectId, boolean always) {
5729        try {
5730            return mWindowSession.performHapticFeedback(mWindow, effectId, always);
5731        } catch (RemoteException e) {
5732            return false;
5733        }
5734    }
5735
5736    /**
5737     * {@inheritDoc}
5738     */
5739    @Override
5740    public View focusSearch(View focused, int direction) {
5741        checkThread();
5742        if (!(mView instanceof ViewGroup)) {
5743            return null;
5744        }
5745        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5746    }
5747
5748    public void debug() {
5749        mView.debug();
5750    }
5751
5752    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5753        String innerPrefix = prefix + "  ";
5754        writer.print(prefix); writer.println("ViewRoot:");
5755        writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded);
5756                writer.print(" mRemoved="); writer.println(mRemoved);
5757        writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled=");
5758                writer.println(mConsumeBatchedInputScheduled);
5759        writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled=");
5760                writer.println(mConsumeBatchedInputImmediatelyScheduled);
5761        writer.print(innerPrefix); writer.print("mPendingInputEventCount=");
5762                writer.println(mPendingInputEventCount);
5763        writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled=");
5764                writer.println(mProcessInputEventsScheduled);
5765        writer.print(innerPrefix); writer.print("mTraversalScheduled=");
5766                writer.print(mTraversalScheduled);
5767        writer.print(innerPrefix); writer.print("mIsAmbientMode=");
5768                writer.print(mIsAmbientMode);
5769        if (mTraversalScheduled) {
5770            writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")");
5771        } else {
5772            writer.println();
5773        }
5774        mFirstInputStage.dump(innerPrefix, writer);
5775
5776        mChoreographer.dump(prefix, writer);
5777
5778        writer.print(prefix); writer.println("View Hierarchy:");
5779        dumpViewHierarchy(innerPrefix, writer, mView);
5780    }
5781
5782    private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5783        writer.print(prefix);
5784        if (view == null) {
5785            writer.println("null");
5786            return;
5787        }
5788        writer.println(view.toString());
5789        if (!(view instanceof ViewGroup)) {
5790            return;
5791        }
5792        ViewGroup grp = (ViewGroup)view;
5793        final int N = grp.getChildCount();
5794        if (N <= 0) {
5795            return;
5796        }
5797        prefix = prefix + "  ";
5798        for (int i=0; i<N; i++) {
5799            dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5800        }
5801    }
5802
5803    public void dumpGfxInfo(int[] info) {
5804        info[0] = info[1] = 0;
5805        if (mView != null) {
5806            getGfxInfo(mView, info);
5807        }
5808    }
5809
5810    private static void getGfxInfo(View view, int[] info) {
5811        RenderNode renderNode = view.mRenderNode;
5812        info[0]++;
5813        if (renderNode != null) {
5814            info[1] += renderNode.getDebugSize();
5815        }
5816
5817        if (view instanceof ViewGroup) {
5818            ViewGroup group = (ViewGroup) view;
5819
5820            int count = group.getChildCount();
5821            for (int i = 0; i < count; i++) {
5822                getGfxInfo(group.getChildAt(i), info);
5823            }
5824        }
5825    }
5826
5827    /**
5828     * @param immediate True, do now if not in traversal. False, put on queue and do later.
5829     * @return True, request has been queued. False, request has been completed.
5830     */
5831    boolean die(boolean immediate) {
5832        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
5833        // done by dispatchDetachedFromWindow will cause havoc on return.
5834        if (immediate && !mIsInTraversal) {
5835            doDie();
5836            return false;
5837        }
5838
5839        if (!mIsDrawing) {
5840            destroyHardwareRenderer();
5841        } else {
5842            Log.e(mTag, "Attempting to destroy the window while drawing!\n" +
5843                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
5844        }
5845        mHandler.sendEmptyMessage(MSG_DIE);
5846        return true;
5847    }
5848
5849    void doDie() {
5850        checkThread();
5851        if (LOCAL_LOGV) Log.v(mTag, "DIE in " + this + " of " + mSurface);
5852        synchronized (this) {
5853            if (mRemoved) {
5854                return;
5855            }
5856            mRemoved = true;
5857            if (mAdded) {
5858                dispatchDetachedFromWindow();
5859            }
5860
5861            if (mAdded && !mFirst) {
5862                destroyHardwareRenderer();
5863
5864                if (mView != null) {
5865                    int viewVisibility = mView.getVisibility();
5866                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
5867                    if (mWindowAttributesChanged || viewVisibilityChanged) {
5868                        // If layout params have been changed, first give them
5869                        // to the window manager to make sure it has the correct
5870                        // animation info.
5871                        try {
5872                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5873                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5874                                mWindowSession.finishDrawing(mWindow);
5875                            }
5876                        } catch (RemoteException e) {
5877                        }
5878                    }
5879
5880                    mSurface.release();
5881                }
5882            }
5883
5884            mAdded = false;
5885        }
5886        WindowManagerGlobal.getInstance().doRemoveView(this);
5887    }
5888
5889    public void requestUpdateConfiguration(Configuration config) {
5890        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5891        mHandler.sendMessage(msg);
5892    }
5893
5894    public void loadSystemProperties() {
5895        mHandler.post(new Runnable() {
5896            @Override
5897            public void run() {
5898                // Profiling
5899                mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5900                profileRendering(mAttachInfo.mHasWindowFocus);
5901
5902                // Hardware rendering
5903                if (mAttachInfo.mHardwareRenderer != null) {
5904                    if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
5905                        invalidate();
5906                    }
5907                }
5908
5909                // Layout debugging
5910                boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5911                if (layout != mAttachInfo.mDebugLayout) {
5912                    mAttachInfo.mDebugLayout = layout;
5913                    if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5914                        mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5915                    }
5916                }
5917            }
5918        });
5919    }
5920
5921    private void destroyHardwareRenderer() {
5922        ThreadedRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
5923
5924        if (hardwareRenderer != null) {
5925            if (mView != null) {
5926                hardwareRenderer.destroyHardwareResources(mView);
5927            }
5928            hardwareRenderer.destroy();
5929            hardwareRenderer.setRequested(false);
5930
5931            mAttachInfo.mHardwareRenderer = null;
5932            mAttachInfo.mHardwareAccelerated = false;
5933        }
5934    }
5935
5936    public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
5937            Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
5938            Configuration newConfig, Rect backDropFrame, boolean forceLayout,
5939            boolean alwaysConsumeNavBar) {
5940        if (DEBUG_LAYOUT) Log.v(mTag, "Resizing " + this + ": frame=" + frame.toShortString()
5941                + " contentInsets=" + contentInsets.toShortString()
5942                + " visibleInsets=" + visibleInsets.toShortString()
5943                + " reportDraw=" + reportDraw
5944                + " backDropFrame=" + backDropFrame);
5945
5946        // Tell all listeners that we are resizing the window so that the chrome can get
5947        // updated as fast as possible on a separate thread,
5948        if (mDragResizing) {
5949            boolean fullscreen = frame.equals(backDropFrame);
5950            synchronized (mWindowCallbacks) {
5951                for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
5952                    mWindowCallbacks.get(i).onWindowSizeIsChanging(backDropFrame, fullscreen,
5953                            visibleInsets, stableInsets);
5954                }
5955            }
5956        }
5957
5958        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
5959        if (mTranslator != null) {
5960            mTranslator.translateRectInScreenToAppWindow(frame);
5961            mTranslator.translateRectInScreenToAppWindow(overscanInsets);
5962            mTranslator.translateRectInScreenToAppWindow(contentInsets);
5963            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
5964        }
5965        SomeArgs args = SomeArgs.obtain();
5966        final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5967        args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5968        args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5969        args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5970        args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
5971        args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
5972        args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets;
5973        args.arg7 = sameProcessCall ? new Rect(outsets) : outsets;
5974        args.arg8 = sameProcessCall ? new Rect(backDropFrame) : backDropFrame;
5975        args.argi1 = forceLayout ? 1 : 0;
5976        args.argi2 = alwaysConsumeNavBar ? 1 : 0;
5977        msg.obj = args;
5978        mHandler.sendMessage(msg);
5979    }
5980
5981    public void dispatchMoved(int newX, int newY) {
5982        if (DEBUG_LAYOUT) Log.v(mTag, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
5983        if (mTranslator != null) {
5984            PointF point = new PointF(newX, newY);
5985            mTranslator.translatePointInScreenToAppWindow(point);
5986            newX = (int) (point.x + 0.5);
5987            newY = (int) (point.y + 0.5);
5988        }
5989        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5990        mHandler.sendMessage(msg);
5991    }
5992
5993    /**
5994     * Represents a pending input event that is waiting in a queue.
5995     *
5996     * Input events are processed in serial order by the timestamp specified by
5997     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
5998     * one input event to the application at a time and waits for the application
5999     * to finish handling it before delivering the next one.
6000     *
6001     * However, because the application or IME can synthesize and inject multiple
6002     * key events at a time without going through the input dispatcher, we end up
6003     * needing a queue on the application's side.
6004     */
6005    private static final class QueuedInputEvent {
6006        public static final int FLAG_DELIVER_POST_IME = 1 << 0;
6007        public static final int FLAG_DEFERRED = 1 << 1;
6008        public static final int FLAG_FINISHED = 1 << 2;
6009        public static final int FLAG_FINISHED_HANDLED = 1 << 3;
6010        public static final int FLAG_RESYNTHESIZED = 1 << 4;
6011        public static final int FLAG_UNHANDLED = 1 << 5;
6012
6013        public QueuedInputEvent mNext;
6014
6015        public InputEvent mEvent;
6016        public InputEventReceiver mReceiver;
6017        public int mFlags;
6018
6019        public boolean shouldSkipIme() {
6020            if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
6021                return true;
6022            }
6023            return mEvent instanceof MotionEvent
6024                    && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
6025        }
6026
6027        public boolean shouldSendToSynthesizer() {
6028            if ((mFlags & FLAG_UNHANDLED) != 0) {
6029                return true;
6030            }
6031
6032            return false;
6033        }
6034
6035        @Override
6036        public String toString() {
6037            StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
6038            boolean hasPrevious = false;
6039            hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
6040            hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
6041            hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
6042            hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
6043            hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
6044            hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
6045            if (!hasPrevious) {
6046                sb.append("0");
6047            }
6048            sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
6049            sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
6050            sb.append(", mEvent=" + mEvent + "}");
6051            return sb.toString();
6052        }
6053
6054        private boolean flagToString(String name, int flag,
6055                boolean hasPrevious, StringBuilder sb) {
6056            if ((mFlags & flag) != 0) {
6057                if (hasPrevious) {
6058                    sb.append("|");
6059                }
6060                sb.append(name);
6061                return true;
6062            }
6063            return hasPrevious;
6064        }
6065    }
6066
6067    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
6068            InputEventReceiver receiver, int flags) {
6069        QueuedInputEvent q = mQueuedInputEventPool;
6070        if (q != null) {
6071            mQueuedInputEventPoolSize -= 1;
6072            mQueuedInputEventPool = q.mNext;
6073            q.mNext = null;
6074        } else {
6075            q = new QueuedInputEvent();
6076        }
6077
6078        q.mEvent = event;
6079        q.mReceiver = receiver;
6080        q.mFlags = flags;
6081        return q;
6082    }
6083
6084    private void recycleQueuedInputEvent(QueuedInputEvent q) {
6085        q.mEvent = null;
6086        q.mReceiver = null;
6087
6088        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
6089            mQueuedInputEventPoolSize += 1;
6090            q.mNext = mQueuedInputEventPool;
6091            mQueuedInputEventPool = q;
6092        }
6093    }
6094
6095    void enqueueInputEvent(InputEvent event) {
6096        enqueueInputEvent(event, null, 0, false);
6097    }
6098
6099    void enqueueInputEvent(InputEvent event,
6100            InputEventReceiver receiver, int flags, boolean processImmediately) {
6101        adjustInputEventForCompatibility(event);
6102        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
6103
6104        // Always enqueue the input event in order, regardless of its time stamp.
6105        // We do this because the application or the IME may inject key events
6106        // in response to touch events and we want to ensure that the injected keys
6107        // are processed in the order they were received and we cannot trust that
6108        // the time stamp of injected events are monotonic.
6109        QueuedInputEvent last = mPendingInputEventTail;
6110        if (last == null) {
6111            mPendingInputEventHead = q;
6112            mPendingInputEventTail = q;
6113        } else {
6114            last.mNext = q;
6115            mPendingInputEventTail = q;
6116        }
6117        mPendingInputEventCount += 1;
6118        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
6119                mPendingInputEventCount);
6120
6121        if (processImmediately) {
6122            doProcessInputEvents();
6123        } else {
6124            scheduleProcessInputEvents();
6125        }
6126    }
6127
6128    private void scheduleProcessInputEvents() {
6129        if (!mProcessInputEventsScheduled) {
6130            mProcessInputEventsScheduled = true;
6131            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
6132            msg.setAsynchronous(true);
6133            mHandler.sendMessage(msg);
6134        }
6135    }
6136
6137    void doProcessInputEvents() {
6138        // Deliver all pending input events in the queue.
6139        while (mPendingInputEventHead != null) {
6140            QueuedInputEvent q = mPendingInputEventHead;
6141            mPendingInputEventHead = q.mNext;
6142            if (mPendingInputEventHead == null) {
6143                mPendingInputEventTail = null;
6144            }
6145            q.mNext = null;
6146
6147            mPendingInputEventCount -= 1;
6148            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
6149                    mPendingInputEventCount);
6150
6151            long eventTime = q.mEvent.getEventTimeNano();
6152            long oldestEventTime = eventTime;
6153            if (q.mEvent instanceof MotionEvent) {
6154                MotionEvent me = (MotionEvent)q.mEvent;
6155                if (me.getHistorySize() > 0) {
6156                    oldestEventTime = me.getHistoricalEventTimeNano(0);
6157                }
6158            }
6159            mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);
6160
6161            deliverInputEvent(q);
6162        }
6163
6164        // We are done processing all input events that we can process right now
6165        // so we can clear the pending flag immediately.
6166        if (mProcessInputEventsScheduled) {
6167            mProcessInputEventsScheduled = false;
6168            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
6169        }
6170    }
6171
6172    private void deliverInputEvent(QueuedInputEvent q) {
6173        Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
6174                q.mEvent.getSequenceNumber());
6175        if (mInputEventConsistencyVerifier != null) {
6176            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
6177        }
6178
6179        InputStage stage;
6180        if (q.shouldSendToSynthesizer()) {
6181            stage = mSyntheticInputStage;
6182        } else {
6183            stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
6184        }
6185
6186        if (stage != null) {
6187            stage.deliver(q);
6188        } else {
6189            finishInputEvent(q);
6190        }
6191    }
6192
6193    private void finishInputEvent(QueuedInputEvent q) {
6194        Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
6195                q.mEvent.getSequenceNumber());
6196
6197        if (q.mReceiver != null) {
6198            boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
6199            q.mReceiver.finishInputEvent(q.mEvent, handled);
6200        } else {
6201            q.mEvent.recycleIfNeededAfterDispatch();
6202        }
6203
6204        recycleQueuedInputEvent(q);
6205    }
6206
6207    private void adjustInputEventForCompatibility(InputEvent e) {
6208        if (mTargetSdkVersion < Build.VERSION_CODES.M && e instanceof MotionEvent) {
6209            MotionEvent motion = (MotionEvent) e;
6210            final int mask =
6211                MotionEvent.BUTTON_STYLUS_PRIMARY | MotionEvent.BUTTON_STYLUS_SECONDARY;
6212            final int buttonState = motion.getButtonState();
6213            final int compatButtonState = (buttonState & mask) >> 4;
6214            if (compatButtonState != 0) {
6215                motion.setButtonState(buttonState | compatButtonState);
6216            }
6217        }
6218    }
6219
6220    static boolean isTerminalInputEvent(InputEvent event) {
6221        if (event instanceof KeyEvent) {
6222            final KeyEvent keyEvent = (KeyEvent)event;
6223            return keyEvent.getAction() == KeyEvent.ACTION_UP;
6224        } else {
6225            final MotionEvent motionEvent = (MotionEvent)event;
6226            final int action = motionEvent.getAction();
6227            return action == MotionEvent.ACTION_UP
6228                    || action == MotionEvent.ACTION_CANCEL
6229                    || action == MotionEvent.ACTION_HOVER_EXIT;
6230        }
6231    }
6232
6233    void scheduleConsumeBatchedInput() {
6234        if (!mConsumeBatchedInputScheduled) {
6235            mConsumeBatchedInputScheduled = true;
6236            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
6237                    mConsumedBatchedInputRunnable, null);
6238        }
6239    }
6240
6241    void unscheduleConsumeBatchedInput() {
6242        if (mConsumeBatchedInputScheduled) {
6243            mConsumeBatchedInputScheduled = false;
6244            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
6245                    mConsumedBatchedInputRunnable, null);
6246        }
6247    }
6248
6249    void scheduleConsumeBatchedInputImmediately() {
6250        if (!mConsumeBatchedInputImmediatelyScheduled) {
6251            unscheduleConsumeBatchedInput();
6252            mConsumeBatchedInputImmediatelyScheduled = true;
6253            mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
6254        }
6255    }
6256
6257    void doConsumeBatchedInput(long frameTimeNanos) {
6258        if (mConsumeBatchedInputScheduled) {
6259            mConsumeBatchedInputScheduled = false;
6260            if (mInputEventReceiver != null) {
6261                if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
6262                        && frameTimeNanos != -1) {
6263                    // If we consumed a batch here, we want to go ahead and schedule the
6264                    // consumption of batched input events on the next frame. Otherwise, we would
6265                    // wait until we have more input events pending and might get starved by other
6266                    // things occurring in the process. If the frame time is -1, however, then
6267                    // we're in a non-batching mode, so there's no need to schedule this.
6268                    scheduleConsumeBatchedInput();
6269                }
6270            }
6271            doProcessInputEvents();
6272        }
6273    }
6274
6275    final class TraversalRunnable implements Runnable {
6276        @Override
6277        public void run() {
6278            doTraversal();
6279        }
6280    }
6281    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
6282
6283    final class WindowInputEventReceiver extends InputEventReceiver {
6284        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
6285            super(inputChannel, looper);
6286        }
6287
6288        @Override
6289        public void onInputEvent(InputEvent event) {
6290            enqueueInputEvent(event, this, 0, true);
6291        }
6292
6293        @Override
6294        public void onBatchedInputEventPending() {
6295            if (mUnbufferedInputDispatch) {
6296                super.onBatchedInputEventPending();
6297            } else {
6298                scheduleConsumeBatchedInput();
6299            }
6300        }
6301
6302        @Override
6303        public void dispose() {
6304            unscheduleConsumeBatchedInput();
6305            super.dispose();
6306        }
6307    }
6308    WindowInputEventReceiver mInputEventReceiver;
6309
6310    final class ConsumeBatchedInputRunnable implements Runnable {
6311        @Override
6312        public void run() {
6313            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
6314        }
6315    }
6316    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
6317            new ConsumeBatchedInputRunnable();
6318    boolean mConsumeBatchedInputScheduled;
6319
6320    final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
6321        @Override
6322        public void run() {
6323            doConsumeBatchedInput(-1);
6324        }
6325    }
6326    final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
6327            new ConsumeBatchedInputImmediatelyRunnable();
6328    boolean mConsumeBatchedInputImmediatelyScheduled;
6329
6330    final class InvalidateOnAnimationRunnable implements Runnable {
6331        private boolean mPosted;
6332        private final ArrayList<View> mViews = new ArrayList<View>();
6333        private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
6334                new ArrayList<AttachInfo.InvalidateInfo>();
6335        private View[] mTempViews;
6336        private AttachInfo.InvalidateInfo[] mTempViewRects;
6337
6338        public void addView(View view) {
6339            synchronized (this) {
6340                mViews.add(view);
6341                postIfNeededLocked();
6342            }
6343        }
6344
6345        public void addViewRect(AttachInfo.InvalidateInfo info) {
6346            synchronized (this) {
6347                mViewRects.add(info);
6348                postIfNeededLocked();
6349            }
6350        }
6351
6352        public void removeView(View view) {
6353            synchronized (this) {
6354                mViews.remove(view);
6355
6356                for (int i = mViewRects.size(); i-- > 0; ) {
6357                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
6358                    if (info.target == view) {
6359                        mViewRects.remove(i);
6360                        info.recycle();
6361                    }
6362                }
6363
6364                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
6365                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
6366                    mPosted = false;
6367                }
6368            }
6369        }
6370
6371        @Override
6372        public void run() {
6373            final int viewCount;
6374            final int viewRectCount;
6375            synchronized (this) {
6376                mPosted = false;
6377
6378                viewCount = mViews.size();
6379                if (viewCount != 0) {
6380                    mTempViews = mViews.toArray(mTempViews != null
6381                            ? mTempViews : new View[viewCount]);
6382                    mViews.clear();
6383                }
6384
6385                viewRectCount = mViewRects.size();
6386                if (viewRectCount != 0) {
6387                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
6388                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6389                    mViewRects.clear();
6390                }
6391            }
6392
6393            for (int i = 0; i < viewCount; i++) {
6394                mTempViews[i].invalidate();
6395                mTempViews[i] = null;
6396            }
6397
6398            for (int i = 0; i < viewRectCount; i++) {
6399                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
6400                info.target.invalidate(info.left, info.top, info.right, info.bottom);
6401                info.recycle();
6402            }
6403        }
6404
6405        private void postIfNeededLocked() {
6406            if (!mPosted) {
6407                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
6408                mPosted = true;
6409            }
6410        }
6411    }
6412    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6413            new InvalidateOnAnimationRunnable();
6414
6415    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6416        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6417        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6418    }
6419
6420    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
6421            long delayMilliseconds) {
6422        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
6423        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6424    }
6425
6426    public void dispatchInvalidateOnAnimation(View view) {
6427        mInvalidateOnAnimationRunnable.addView(view);
6428    }
6429
6430    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6431        mInvalidateOnAnimationRunnable.addViewRect(info);
6432    }
6433
6434    public void cancelInvalidate(View view) {
6435        mHandler.removeMessages(MSG_INVALIDATE, view);
6436        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6437        // them to the pool
6438        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6439        mInvalidateOnAnimationRunnable.removeView(view);
6440    }
6441
6442    public void dispatchInputEvent(InputEvent event) {
6443        dispatchInputEvent(event, null);
6444    }
6445
6446    public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6447        SomeArgs args = SomeArgs.obtain();
6448        args.arg1 = event;
6449        args.arg2 = receiver;
6450        Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
6451        msg.setAsynchronous(true);
6452        mHandler.sendMessage(msg);
6453    }
6454
6455    public void synthesizeInputEvent(InputEvent event) {
6456        Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6457        msg.setAsynchronous(true);
6458        mHandler.sendMessage(msg);
6459    }
6460
6461    public void dispatchKeyFromIme(KeyEvent event) {
6462        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
6463        msg.setAsynchronous(true);
6464        mHandler.sendMessage(msg);
6465    }
6466
6467    /**
6468     * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6469     *
6470     * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6471     * passes in.
6472     */
6473    public void dispatchUnhandledInputEvent(InputEvent event) {
6474        if (event instanceof MotionEvent) {
6475            event = MotionEvent.obtain((MotionEvent) event);
6476        }
6477        synthesizeInputEvent(event);
6478    }
6479
6480    public void dispatchAppVisibility(boolean visible) {
6481        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
6482        msg.arg1 = visible ? 1 : 0;
6483        mHandler.sendMessage(msg);
6484    }
6485
6486    public void dispatchGetNewSurface() {
6487        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6488        mHandler.sendMessage(msg);
6489    }
6490
6491    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6492        Message msg = Message.obtain();
6493        msg.what = MSG_WINDOW_FOCUS_CHANGED;
6494        msg.arg1 = hasFocus ? 1 : 0;
6495        msg.arg2 = inTouchMode ? 1 : 0;
6496        mHandler.sendMessage(msg);
6497    }
6498
6499    public void dispatchWindowShown() {
6500        mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6501    }
6502
6503    public void dispatchCloseSystemDialogs(String reason) {
6504        Message msg = Message.obtain();
6505        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
6506        msg.obj = reason;
6507        mHandler.sendMessage(msg);
6508    }
6509
6510    public void dispatchDragEvent(DragEvent event) {
6511        final int what;
6512        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
6513            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6514            mHandler.removeMessages(what);
6515        } else {
6516            what = MSG_DISPATCH_DRAG_EVENT;
6517        }
6518        Message msg = mHandler.obtainMessage(what, event);
6519        mHandler.sendMessage(msg);
6520    }
6521
6522    public void updatePointerIcon(float x, float y) {
6523        final int what = MSG_UPDATE_POINTER_ICON;
6524        mHandler.removeMessages(what);
6525        final long now = SystemClock.uptimeMillis();
6526        final MotionEvent event = MotionEvent.obtain(
6527                0, now, MotionEvent.ACTION_HOVER_MOVE, x, y, 0);
6528        Message msg = mHandler.obtainMessage(what, event);
6529        mHandler.sendMessage(msg);
6530    }
6531
6532    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6533            int localValue, int localChanges) {
6534        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6535        args.seq = seq;
6536        args.globalVisibility = globalVisibility;
6537        args.localValue = localValue;
6538        args.localChanges = localChanges;
6539        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6540    }
6541
6542    public void dispatchCheckFocus() {
6543        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
6544            // This will result in a call to checkFocus() below.
6545            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
6546        }
6547    }
6548
6549    public void dispatchRequestKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
6550        mHandler.obtainMessage(
6551                MSG_REQUEST_KEYBOARD_SHORTCUTS, deviceId, 0, receiver).sendToTarget();
6552    }
6553
6554    /**
6555     * Post a callback to send a
6556     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6557     * This event is send at most once every
6558     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
6559     */
6560    private void postSendWindowContentChangedCallback(View source, int changeType) {
6561        if (mSendWindowContentChangedAccessibilityEvent == null) {
6562            mSendWindowContentChangedAccessibilityEvent =
6563                new SendWindowContentChangedAccessibilityEvent();
6564        }
6565        mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
6566    }
6567
6568    /**
6569     * Remove a posted callback to send a
6570     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6571     */
6572    private void removeSendWindowContentChangedCallback() {
6573        if (mSendWindowContentChangedAccessibilityEvent != null) {
6574            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
6575        }
6576    }
6577
6578    @Override
6579    public boolean showContextMenuForChild(View originalView) {
6580        return false;
6581    }
6582
6583    @Override
6584    public boolean showContextMenuForChild(View originalView, float x, float y) {
6585        return false;
6586    }
6587
6588    @Override
6589    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6590        return null;
6591    }
6592
6593    @Override
6594    public ActionMode startActionModeForChild(
6595            View originalView, ActionMode.Callback callback, int type) {
6596        return null;
6597    }
6598
6599    @Override
6600    public void createContextMenu(ContextMenu menu) {
6601    }
6602
6603    @Override
6604    public void childDrawableStateChanged(View child) {
6605    }
6606
6607    @Override
6608    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
6609        if (mView == null || mStopped || mPausedForTransition) {
6610            return false;
6611        }
6612        // Intercept accessibility focus events fired by virtual nodes to keep
6613        // track of accessibility focus position in such nodes.
6614        final int eventType = event.getEventType();
6615        switch (eventType) {
6616            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
6617                final long sourceNodeId = event.getSourceNodeId();
6618                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6619                        sourceNodeId);
6620                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6621                if (source != null) {
6622                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6623                    if (provider != null) {
6624                        final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
6625                                sourceNodeId);
6626                        final AccessibilityNodeInfo node;
6627                        if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6628                            node = provider.createAccessibilityNodeInfo(
6629                                    AccessibilityNodeProvider.HOST_VIEW_ID);
6630                        } else {
6631                            node = provider.createAccessibilityNodeInfo(virtualNodeId);
6632                        }
6633                        setAccessibilityFocus(source, node);
6634                    }
6635                }
6636            } break;
6637            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
6638                final long sourceNodeId = event.getSourceNodeId();
6639                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6640                        sourceNodeId);
6641                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6642                if (source != null) {
6643                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6644                    if (provider != null) {
6645                        setAccessibilityFocus(null, null);
6646                    }
6647                }
6648            } break;
6649
6650
6651            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
6652                handleWindowContentChangedEvent(event);
6653            } break;
6654        }
6655        mAccessibilityManager.sendAccessibilityEvent(event);
6656        return true;
6657    }
6658
6659    /**
6660     * Updates the focused virtual view, when necessary, in response to a
6661     * content changed event.
6662     * <p>
6663     * This is necessary to get updated bounds after a position change.
6664     *
6665     * @param event an accessibility event of type
6666     *              {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
6667     */
6668    private void handleWindowContentChangedEvent(AccessibilityEvent event) {
6669        final View focusedHost = mAccessibilityFocusedHost;
6670        if (focusedHost == null || mAccessibilityFocusedVirtualView == null) {
6671            // No virtual view focused, nothing to do here.
6672            return;
6673        }
6674
6675        final AccessibilityNodeProvider provider = focusedHost.getAccessibilityNodeProvider();
6676        if (provider == null) {
6677            // Error state: virtual view with no provider. Clear focus.
6678            mAccessibilityFocusedHost = null;
6679            mAccessibilityFocusedVirtualView = null;
6680            focusedHost.clearAccessibilityFocusNoCallbacks(0);
6681            return;
6682        }
6683
6684        // We only care about change types that may affect the bounds of the
6685        // focused virtual view.
6686        final int changes = event.getContentChangeTypes();
6687        if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) == 0
6688                && changes != AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
6689            return;
6690        }
6691
6692        final long eventSourceNodeId = event.getSourceNodeId();
6693        final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId);
6694
6695        // Search up the tree for subtree containment.
6696        boolean hostInSubtree = false;
6697        View root = mAccessibilityFocusedHost;
6698        while (root != null && !hostInSubtree) {
6699            if (changedViewId == root.getAccessibilityViewId()) {
6700                hostInSubtree = true;
6701            } else {
6702                final ViewParent parent = root.getParent();
6703                if (parent instanceof View) {
6704                    root = (View) parent;
6705                } else {
6706                    root = null;
6707                }
6708            }
6709        }
6710
6711        // We care only about changes in subtrees containing the host view.
6712        if (!hostInSubtree) {
6713            return;
6714        }
6715
6716        final long focusedSourceNodeId = mAccessibilityFocusedVirtualView.getSourceNodeId();
6717        int focusedChildId = AccessibilityNodeInfo.getVirtualDescendantId(focusedSourceNodeId);
6718        if (focusedChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6719            // TODO: Should we clear the focused virtual view?
6720            focusedChildId = AccessibilityNodeProvider.HOST_VIEW_ID;
6721        }
6722
6723        // Refresh the node for the focused virtual view.
6724        final Rect oldBounds = mTempRect;
6725        mAccessibilityFocusedVirtualView.getBoundsInScreen(oldBounds);
6726        mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId);
6727        if (mAccessibilityFocusedVirtualView == null) {
6728            // Error state: The node no longer exists. Clear focus.
6729            mAccessibilityFocusedHost = null;
6730            focusedHost.clearAccessibilityFocusNoCallbacks(0);
6731
6732            // This will probably fail, but try to keep the provider's internal
6733            // state consistent by clearing focus.
6734            provider.performAction(focusedChildId,
6735                    AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS.getId(), null);
6736            invalidateRectOnScreen(oldBounds);
6737        } else {
6738            // The node was refreshed, invalidate bounds if necessary.
6739            final Rect newBounds = mAccessibilityFocusedVirtualView.getBoundsInScreen();
6740            if (!oldBounds.equals(newBounds)) {
6741                oldBounds.union(newBounds);
6742                invalidateRectOnScreen(oldBounds);
6743            }
6744        }
6745    }
6746
6747    @Override
6748    public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6749        postSendWindowContentChangedCallback(source, changeType);
6750    }
6751
6752    @Override
6753    public boolean canResolveLayoutDirection() {
6754        return true;
6755    }
6756
6757    @Override
6758    public boolean isLayoutDirectionResolved() {
6759        return true;
6760    }
6761
6762    @Override
6763    public int getLayoutDirection() {
6764        return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6765    }
6766
6767    @Override
6768    public boolean canResolveTextDirection() {
6769        return true;
6770    }
6771
6772    @Override
6773    public boolean isTextDirectionResolved() {
6774        return true;
6775    }
6776
6777    @Override
6778    public int getTextDirection() {
6779        return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6780    }
6781
6782    @Override
6783    public boolean canResolveTextAlignment() {
6784        return true;
6785    }
6786
6787    @Override
6788    public boolean isTextAlignmentResolved() {
6789        return true;
6790    }
6791
6792    @Override
6793    public int getTextAlignment() {
6794        return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6795    }
6796
6797    private View getCommonPredecessor(View first, View second) {
6798        if (mTempHashSet == null) {
6799            mTempHashSet = new HashSet<View>();
6800        }
6801        HashSet<View> seen = mTempHashSet;
6802        seen.clear();
6803        View firstCurrent = first;
6804        while (firstCurrent != null) {
6805            seen.add(firstCurrent);
6806            ViewParent firstCurrentParent = firstCurrent.mParent;
6807            if (firstCurrentParent instanceof View) {
6808                firstCurrent = (View) firstCurrentParent;
6809            } else {
6810                firstCurrent = null;
6811            }
6812        }
6813        View secondCurrent = second;
6814        while (secondCurrent != null) {
6815            if (seen.contains(secondCurrent)) {
6816                seen.clear();
6817                return secondCurrent;
6818            }
6819            ViewParent secondCurrentParent = secondCurrent.mParent;
6820            if (secondCurrentParent instanceof View) {
6821                secondCurrent = (View) secondCurrentParent;
6822            } else {
6823                secondCurrent = null;
6824            }
6825        }
6826        seen.clear();
6827        return null;
6828    }
6829
6830    void checkThread() {
6831        if (mThread != Thread.currentThread()) {
6832            throw new CalledFromWrongThreadException(
6833                    "Only the original thread that created a view hierarchy can touch its views.");
6834        }
6835    }
6836
6837    @Override
6838    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
6839        // ViewAncestor never intercepts touch event, so this can be a no-op
6840    }
6841
6842    @Override
6843    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
6844        if (rectangle == null) {
6845            return scrollToRectOrFocus(null, immediate);
6846        }
6847        rectangle.offset(child.getLeft() - child.getScrollX(),
6848                child.getTop() - child.getScrollY());
6849        final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
6850        mTempRect.set(rectangle);
6851        mTempRect.offset(0, -mCurScrollY);
6852        mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6853        try {
6854            mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6855        } catch (RemoteException re) {
6856            /* ignore */
6857        }
6858        return scrolled;
6859    }
6860
6861    @Override
6862    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6863        // Do nothing.
6864    }
6865
6866    @Override
6867    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6868        return false;
6869    }
6870
6871    @Override
6872    public void onStopNestedScroll(View target) {
6873    }
6874
6875    @Override
6876    public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6877    }
6878
6879    @Override
6880    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6881            int dxUnconsumed, int dyUnconsumed) {
6882    }
6883
6884    @Override
6885    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6886    }
6887
6888    @Override
6889    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6890        return false;
6891    }
6892
6893    @Override
6894    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6895        return false;
6896    }
6897
6898    @Override
6899    public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6900        return false;
6901    }
6902
6903    /**
6904     * Force the window to report its next draw.
6905     * <p>
6906     * This method is only supposed to be used to speed up the interaction from SystemUI and window
6907     * manager when waiting for the first frame to be drawn when turning on the screen. DO NOT USE
6908     * unless you fully understand this interaction.
6909     * @hide
6910     */
6911    public void setReportNextDraw() {
6912        mReportNextDraw = true;
6913        invalidate();
6914    }
6915
6916    void changeCanvasOpacity(boolean opaque) {
6917        Log.d(mTag, "changeCanvasOpacity: opaque=" + opaque);
6918        if (mAttachInfo.mHardwareRenderer != null) {
6919            mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6920        }
6921    }
6922
6923    class TakenSurfaceHolder extends BaseSurfaceHolder {
6924        @Override
6925        public boolean onAllowLockCanvas() {
6926            return mDrawingAllowed;
6927        }
6928
6929        @Override
6930        public void onRelayoutContainer() {
6931            // Not currently interesting -- from changing between fixed and layout size.
6932        }
6933
6934        @Override
6935        public void setFormat(int format) {
6936            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6937        }
6938
6939        @Override
6940        public void setType(int type) {
6941            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6942        }
6943
6944        @Override
6945        public void onUpdateSurface() {
6946            // We take care of format and type changes on our own.
6947            throw new IllegalStateException("Shouldn't be here");
6948        }
6949
6950        @Override
6951        public boolean isCreating() {
6952            return mIsCreating;
6953        }
6954
6955        @Override
6956        public void setFixedSize(int width, int height) {
6957            throw new UnsupportedOperationException(
6958                    "Currently only support sizing from layout");
6959        }
6960
6961        @Override
6962        public void setKeepScreenOn(boolean screenOn) {
6963            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6964        }
6965    }
6966
6967    static class W extends IWindow.Stub {
6968        private final WeakReference<ViewRootImpl> mViewAncestor;
6969        private final IWindowSession mWindowSession;
6970
6971        W(ViewRootImpl viewAncestor) {
6972            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
6973            mWindowSession = viewAncestor.mWindowSession;
6974        }
6975
6976        @Override
6977        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
6978                Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
6979                Configuration newConfig, Rect backDropFrame, boolean forceLayout,
6980                boolean alwaysConsumeNavBar) {
6981            final ViewRootImpl viewAncestor = mViewAncestor.get();
6982            if (viewAncestor != null) {
6983                viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
6984                        visibleInsets, stableInsets, outsets, reportDraw, newConfig, backDropFrame,
6985                        forceLayout, alwaysConsumeNavBar);
6986            }
6987        }
6988
6989        @Override
6990        public void moved(int newX, int newY) {
6991            final ViewRootImpl viewAncestor = mViewAncestor.get();
6992            if (viewAncestor != null) {
6993                viewAncestor.dispatchMoved(newX, newY);
6994            }
6995        }
6996
6997        @Override
6998        public void dispatchAppVisibility(boolean visible) {
6999            final ViewRootImpl viewAncestor = mViewAncestor.get();
7000            if (viewAncestor != null) {
7001                viewAncestor.dispatchAppVisibility(visible);
7002            }
7003        }
7004
7005        @Override
7006        public void dispatchGetNewSurface() {
7007            final ViewRootImpl viewAncestor = mViewAncestor.get();
7008            if (viewAncestor != null) {
7009                viewAncestor.dispatchGetNewSurface();
7010            }
7011        }
7012
7013        @Override
7014        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
7015            final ViewRootImpl viewAncestor = mViewAncestor.get();
7016            if (viewAncestor != null) {
7017                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
7018            }
7019        }
7020
7021        private static int checkCallingPermission(String permission) {
7022            try {
7023                return ActivityManagerNative.getDefault().checkPermission(
7024                        permission, Binder.getCallingPid(), Binder.getCallingUid());
7025            } catch (RemoteException e) {
7026                return PackageManager.PERMISSION_DENIED;
7027            }
7028        }
7029
7030        @Override
7031        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
7032            final ViewRootImpl viewAncestor = mViewAncestor.get();
7033            if (viewAncestor != null) {
7034                final View view = viewAncestor.mView;
7035                if (view != null) {
7036                    if (checkCallingPermission(Manifest.permission.DUMP) !=
7037                            PackageManager.PERMISSION_GRANTED) {
7038                        throw new SecurityException("Insufficient permissions to invoke"
7039                                + " executeCommand() from pid=" + Binder.getCallingPid()
7040                                + ", uid=" + Binder.getCallingUid());
7041                    }
7042
7043                    OutputStream clientStream = null;
7044                    try {
7045                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
7046                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
7047                    } catch (IOException e) {
7048                        e.printStackTrace();
7049                    } finally {
7050                        if (clientStream != null) {
7051                            try {
7052                                clientStream.close();
7053                            } catch (IOException e) {
7054                                e.printStackTrace();
7055                            }
7056                        }
7057                    }
7058                }
7059            }
7060        }
7061
7062        @Override
7063        public void closeSystemDialogs(String reason) {
7064            final ViewRootImpl viewAncestor = mViewAncestor.get();
7065            if (viewAncestor != null) {
7066                viewAncestor.dispatchCloseSystemDialogs(reason);
7067            }
7068        }
7069
7070        @Override
7071        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
7072                boolean sync) {
7073            if (sync) {
7074                try {
7075                    mWindowSession.wallpaperOffsetsComplete(asBinder());
7076                } catch (RemoteException e) {
7077                }
7078            }
7079        }
7080
7081        @Override
7082        public void dispatchWallpaperCommand(String action, int x, int y,
7083                int z, Bundle extras, boolean sync) {
7084            if (sync) {
7085                try {
7086                    mWindowSession.wallpaperCommandComplete(asBinder(), null);
7087                } catch (RemoteException e) {
7088                }
7089            }
7090        }
7091
7092        /* Drag/drop */
7093        @Override
7094        public void dispatchDragEvent(DragEvent event) {
7095            final ViewRootImpl viewAncestor = mViewAncestor.get();
7096            if (viewAncestor != null) {
7097                viewAncestor.dispatchDragEvent(event);
7098            }
7099        }
7100
7101        @Override
7102        public void updatePointerIcon(float x, float y) {
7103            final ViewRootImpl viewAncestor = mViewAncestor.get();
7104            if (viewAncestor != null) {
7105                viewAncestor.updatePointerIcon(x, y);
7106            }
7107        }
7108
7109        @Override
7110        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
7111                int localValue, int localChanges) {
7112            final ViewRootImpl viewAncestor = mViewAncestor.get();
7113            if (viewAncestor != null) {
7114                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
7115                        localValue, localChanges);
7116            }
7117        }
7118
7119        @Override
7120        public void dispatchWindowShown() {
7121            final ViewRootImpl viewAncestor = mViewAncestor.get();
7122            if (viewAncestor != null) {
7123                viewAncestor.dispatchWindowShown();
7124            }
7125        }
7126
7127        @Override
7128        public void requestAppKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
7129            ViewRootImpl viewAncestor = mViewAncestor.get();
7130            if (viewAncestor != null) {
7131                viewAncestor.dispatchRequestKeyboardShortcuts(receiver, deviceId);
7132            }
7133        }
7134    }
7135
7136    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
7137        public CalledFromWrongThreadException(String msg) {
7138            super(msg);
7139        }
7140    }
7141
7142    static HandlerActionQueue getRunQueue() {
7143        HandlerActionQueue rq = sRunQueues.get();
7144        if (rq != null) {
7145            return rq;
7146        }
7147        rq = new HandlerActionQueue();
7148        sRunQueues.set(rq);
7149        return rq;
7150    }
7151
7152    /**
7153     * Start a drag resizing which will inform all listeners that a window resize is taking place.
7154     */
7155    private void startDragResizing(Rect initialBounds, boolean fullscreen, Rect systemInsets,
7156            Rect stableInsets, int resizeMode) {
7157        if (!mDragResizing) {
7158            mDragResizing = true;
7159            for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7160                mWindowCallbacks.get(i).onWindowDragResizeStart(initialBounds, fullscreen,
7161                        systemInsets, stableInsets, resizeMode);
7162            }
7163            mFullRedrawNeeded = true;
7164        }
7165    }
7166
7167    /**
7168     * End a drag resize which will inform all listeners that a window resize has ended.
7169     */
7170    private void endDragResizing() {
7171        if (mDragResizing) {
7172            mDragResizing = false;
7173            for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7174                mWindowCallbacks.get(i).onWindowDragResizeEnd();
7175            }
7176            mFullRedrawNeeded = true;
7177        }
7178    }
7179
7180    private boolean updateContentDrawBounds() {
7181        boolean updated = false;
7182        for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7183            updated |= mWindowCallbacks.get(i).onContentDrawn(
7184                    mWindowAttributes.surfaceInsets.left,
7185                    mWindowAttributes.surfaceInsets.top,
7186                    mWidth, mHeight);
7187        }
7188        return updated | (mDragResizing && mReportNextDraw);
7189    }
7190
7191    private void requestDrawWindow() {
7192        if (mReportNextDraw) {
7193            mWindowDrawCountDown = new CountDownLatch(mWindowCallbacks.size());
7194        }
7195        for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7196            mWindowCallbacks.get(i).onRequestDraw(mReportNextDraw);
7197        }
7198    }
7199
7200    /**
7201     * Tells this instance that its corresponding activity has just relaunched. In this case, we
7202     * need to force a relayout of the window to make sure we get the correct bounds from window
7203     * manager.
7204     */
7205    public void reportActivityRelaunched() {
7206        mActivityRelaunched = true;
7207    }
7208
7209    /**
7210     * Class for managing the accessibility interaction connection
7211     * based on the global accessibility state.
7212     */
7213    final class AccessibilityInteractionConnectionManager
7214            implements AccessibilityStateChangeListener {
7215        @Override
7216        public void onAccessibilityStateChanged(boolean enabled) {
7217            if (enabled) {
7218                ensureConnection();
7219                if (mAttachInfo.mHasWindowFocus) {
7220                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
7221                    View focusedView = mView.findFocus();
7222                    if (focusedView != null && focusedView != mView) {
7223                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
7224                    }
7225                }
7226            } else {
7227                ensureNoConnection();
7228                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
7229            }
7230        }
7231
7232        public void ensureConnection() {
7233            final boolean registered =
7234                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7235            if (!registered) {
7236                mAttachInfo.mAccessibilityWindowId =
7237                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
7238                                new AccessibilityInteractionConnection(ViewRootImpl.this));
7239            }
7240        }
7241
7242        public void ensureNoConnection() {
7243            final boolean registered =
7244                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7245            if (registered) {
7246                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7247                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
7248            }
7249        }
7250    }
7251
7252    final class HighContrastTextManager implements HighTextContrastChangeListener {
7253        HighContrastTextManager() {
7254            mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
7255        }
7256        @Override
7257        public void onHighTextContrastStateChanged(boolean enabled) {
7258            mAttachInfo.mHighContrastText = enabled;
7259
7260            // Destroy Displaylists so they can be recreated with high contrast recordings
7261            destroyHardwareResources();
7262
7263            // Schedule redraw, which will rerecord + redraw all text
7264            invalidate();
7265        }
7266    }
7267
7268    /**
7269     * This class is an interface this ViewAncestor provides to the
7270     * AccessibilityManagerService to the latter can interact with
7271     * the view hierarchy in this ViewAncestor.
7272     */
7273    static final class AccessibilityInteractionConnection
7274            extends IAccessibilityInteractionConnection.Stub {
7275        private final WeakReference<ViewRootImpl> mViewRootImpl;
7276
7277        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
7278            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
7279        }
7280
7281        @Override
7282        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
7283                Region interactiveRegion, int interactionId,
7284                IAccessibilityInteractionConnectionCallback callback, int flags,
7285                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7286            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7287            if (viewRootImpl != null && viewRootImpl.mView != null) {
7288                viewRootImpl.getAccessibilityInteractionController()
7289                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
7290                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
7291                            interrogatingTid, spec);
7292            } else {
7293                // We cannot make the call and notify the caller so it does not wait.
7294                try {
7295                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
7296                } catch (RemoteException re) {
7297                    /* best effort - ignore */
7298                }
7299            }
7300        }
7301
7302        @Override
7303        public void performAccessibilityAction(long accessibilityNodeId, int action,
7304                Bundle arguments, int interactionId,
7305                IAccessibilityInteractionConnectionCallback callback, int flags,
7306                int interrogatingPid, long interrogatingTid) {
7307            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7308            if (viewRootImpl != null && viewRootImpl.mView != null) {
7309                viewRootImpl.getAccessibilityInteractionController()
7310                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
7311                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
7312            } else {
7313                // We cannot make the call and notify the caller so it does not wait.
7314                try {
7315                    callback.setPerformAccessibilityActionResult(false, interactionId);
7316                } catch (RemoteException re) {
7317                    /* best effort - ignore */
7318                }
7319            }
7320        }
7321
7322        @Override
7323        public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
7324                String viewId, Region interactiveRegion, int interactionId,
7325                IAccessibilityInteractionConnectionCallback callback, int flags,
7326                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7327            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7328            if (viewRootImpl != null && viewRootImpl.mView != null) {
7329                viewRootImpl.getAccessibilityInteractionController()
7330                    .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
7331                            viewId, interactiveRegion, interactionId, callback, flags,
7332                            interrogatingPid, interrogatingTid, spec);
7333            } else {
7334                // We cannot make the call and notify the caller so it does not wait.
7335                try {
7336                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7337                } catch (RemoteException re) {
7338                    /* best effort - ignore */
7339                }
7340            }
7341        }
7342
7343        @Override
7344        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
7345                Region interactiveRegion, int interactionId,
7346                IAccessibilityInteractionConnectionCallback callback, int flags,
7347                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7348            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7349            if (viewRootImpl != null && viewRootImpl.mView != null) {
7350                viewRootImpl.getAccessibilityInteractionController()
7351                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
7352                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
7353                            interrogatingTid, spec);
7354            } else {
7355                // We cannot make the call and notify the caller so it does not wait.
7356                try {
7357                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
7358                } catch (RemoteException re) {
7359                    /* best effort - ignore */
7360                }
7361            }
7362        }
7363
7364        @Override
7365        public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
7366                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
7367                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7368            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7369            if (viewRootImpl != null && viewRootImpl.mView != null) {
7370                viewRootImpl.getAccessibilityInteractionController()
7371                    .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
7372                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
7373                            spec);
7374            } else {
7375                // We cannot make the call and notify the caller so it does not wait.
7376                try {
7377                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7378                } catch (RemoteException re) {
7379                    /* best effort - ignore */
7380                }
7381            }
7382        }
7383
7384        @Override
7385        public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
7386                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
7387                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7388            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7389            if (viewRootImpl != null && viewRootImpl.mView != null) {
7390                viewRootImpl.getAccessibilityInteractionController()
7391                    .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
7392                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
7393                            spec);
7394            } else {
7395                // We cannot make the call and notify the caller so it does not wait.
7396                try {
7397                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7398                } catch (RemoteException re) {
7399                    /* best effort - ignore */
7400                }
7401            }
7402        }
7403    }
7404
7405    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
7406        private int mChangeTypes = 0;
7407
7408        public View mSource;
7409        public long mLastEventTimeMillis;
7410
7411        @Override
7412        public void run() {
7413            // The accessibility may be turned off while we were waiting so check again.
7414            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7415                mLastEventTimeMillis = SystemClock.uptimeMillis();
7416                AccessibilityEvent event = AccessibilityEvent.obtain();
7417                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
7418                event.setContentChangeTypes(mChangeTypes);
7419                mSource.sendAccessibilityEventUnchecked(event);
7420            } else {
7421                mLastEventTimeMillis = 0;
7422            }
7423            // In any case reset to initial state.
7424            mSource.resetSubtreeAccessibilityStateChanged();
7425            mSource = null;
7426            mChangeTypes = 0;
7427        }
7428
7429        public void runOrPost(View source, int changeType) {
7430            if (mSource != null) {
7431                // If there is no common predecessor, then mSource points to
7432                // a removed view, hence in this case always prefer the source.
7433                View predecessor = getCommonPredecessor(mSource, source);
7434                mSource = (predecessor != null) ? predecessor : source;
7435                mChangeTypes |= changeType;
7436                return;
7437            }
7438            mSource = source;
7439            mChangeTypes = changeType;
7440            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
7441            final long minEventIntevalMillis =
7442                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
7443            if (timeSinceLastMillis >= minEventIntevalMillis) {
7444                mSource.removeCallbacks(this);
7445                run();
7446            } else {
7447                mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
7448            }
7449        }
7450    }
7451}
7452