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