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