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