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