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