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