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