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