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