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