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