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