ViewRootImpl.java revision 5f05965f546fa42750f1a8314f8a2da01fd6bfb4
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            if (mAttachInfo.mHardwareRenderer != null &&
1817                    mAttachInfo.mHardwareRenderer.isEnabled()) {
1818                if (hwInitialized ||
1819                        mWidth != mAttachInfo.mHardwareRenderer.getWidth() ||
1820                        mHeight != mAttachInfo.mHardwareRenderer.getHeight()) {
1821                    mAttachInfo.mHardwareRenderer.setup(
1822                            mWidth, mHeight, mWindowAttributes.surfaceInsets);
1823                    if (!hwInitialized) {
1824                        mAttachInfo.mHardwareRenderer.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        }
1902
1903        final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
1904        boolean triggerGlobalLayoutListener = didLayout
1905                || mAttachInfo.mRecomputeGlobalAttributes;
1906        if (didLayout) {
1907            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
1908
1909            // By this point all views have been sized and positioned
1910            // We can compute the transparent area
1911
1912            if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1913                // start out transparent
1914                // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1915                host.getLocationInWindow(mTmpLocation);
1916                mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1917                        mTmpLocation[0] + host.mRight - host.mLeft,
1918                        mTmpLocation[1] + host.mBottom - host.mTop);
1919
1920                host.gatherTransparentRegion(mTransparentRegion);
1921                if (mTranslator != null) {
1922                    mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1923                }
1924
1925                if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1926                    mPreviousTransparentRegion.set(mTransparentRegion);
1927                    mFullRedrawNeeded = true;
1928                    // reconfigure window manager
1929                    try {
1930                        mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1931                    } catch (RemoteException e) {
1932                    }
1933                }
1934            }
1935
1936            if (DBG) {
1937                System.out.println("======================================");
1938                System.out.println("performTraversals -- after setFrame");
1939                host.debug();
1940            }
1941        }
1942
1943        if (triggerGlobalLayoutListener) {
1944            mAttachInfo.mRecomputeGlobalAttributes = false;
1945            mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
1946        }
1947
1948        if (computesInternalInsets) {
1949            // Clear the original insets.
1950            final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
1951            insets.reset();
1952
1953            // Compute new insets in place.
1954            mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
1955            mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
1956
1957            // Tell the window manager.
1958            if (insetsPending || !mLastGivenInsets.equals(insets)) {
1959                mLastGivenInsets.set(insets);
1960
1961                // Translate insets to screen coordinates if needed.
1962                final Rect contentInsets;
1963                final Rect visibleInsets;
1964                final Region touchableRegion;
1965                if (mTranslator != null) {
1966                    contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1967                    visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1968                    touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1969                } else {
1970                    contentInsets = insets.contentInsets;
1971                    visibleInsets = insets.visibleInsets;
1972                    touchableRegion = insets.touchableRegion;
1973                }
1974
1975                try {
1976                    mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
1977                            contentInsets, visibleInsets, touchableRegion);
1978                } catch (RemoteException e) {
1979                }
1980            }
1981        }
1982
1983        boolean skipDraw = false;
1984
1985        if (mFirst) {
1986            // handle first focus request
1987            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1988                    + mView.hasFocus());
1989            if (mView != null) {
1990                if (!mView.hasFocus()) {
1991                    mView.requestFocus(View.FOCUS_FORWARD);
1992                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1993                            + mView.findFocus());
1994                } else {
1995                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1996                            + mView.findFocus());
1997                }
1998            }
1999        } else if (mWindowsAnimating) {
2000            if (mRemainingFrameCount <= 0) {
2001                skipDraw = true;
2002            }
2003            mRemainingFrameCount--;
2004        }
2005
2006        mFirst = false;
2007        mWillDrawSoon = false;
2008        mNewSurfaceNeeded = false;
2009        mViewVisibility = viewVisibility;
2010
2011        if (mAttachInfo.mHasWindowFocus && !isInLocalFocusMode()) {
2012            final boolean imTarget = WindowManager.LayoutParams
2013                    .mayUseInputMethod(mWindowAttributes.flags);
2014            if (imTarget != mLastWasImTarget) {
2015                mLastWasImTarget = imTarget;
2016                InputMethodManager imm = InputMethodManager.peekInstance();
2017                if (imm != null && imTarget) {
2018                    imm.onPreWindowFocus(mView, true /* hasWindowFocus */);
2019                    imm.onPostWindowFocus(mView, mView.findFocus(),
2020                            mWindowAttributes.softInputMode,
2021                            !mHasHadWindowFocus, mWindowAttributes.flags);
2022                }
2023            }
2024        }
2025
2026        // Remember if we must report the next draw.
2027        if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
2028            mReportNextDraw = true;
2029        }
2030
2031        boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() ||
2032                viewVisibility != View.VISIBLE;
2033
2034        if (!cancelDraw && !newSurface) {
2035            if (!skipDraw || mReportNextDraw) {
2036                if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2037                    for (int i = 0; i < mPendingTransitions.size(); ++i) {
2038                        mPendingTransitions.get(i).startChangingAnimations();
2039                    }
2040                    mPendingTransitions.clear();
2041                }
2042
2043                performDraw();
2044            }
2045        } else {
2046            if (viewVisibility == View.VISIBLE) {
2047                // Try again
2048                scheduleTraversals();
2049            } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2050                for (int i = 0; i < mPendingTransitions.size(); ++i) {
2051                    mPendingTransitions.get(i).endChangingAnimations();
2052                }
2053                mPendingTransitions.clear();
2054            }
2055        }
2056
2057        mIsInTraversal = false;
2058    }
2059
2060    private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
2061        Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
2062        try {
2063            if (!mWindowSession.outOfMemory(mWindow) &&
2064                    Process.myUid() != Process.SYSTEM_UID) {
2065                Slog.w(TAG, "No processes killed for memory; killing self");
2066                Process.killProcess(Process.myPid());
2067            }
2068        } catch (RemoteException ex) {
2069        }
2070        mLayoutRequested = true;    // ask wm for a new surface next time.
2071    }
2072
2073    private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
2074        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2075        try {
2076            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2077        } finally {
2078            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2079        }
2080    }
2081
2082    /**
2083     * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
2084     * is currently undergoing a layout pass.
2085     *
2086     * @return whether the view hierarchy is currently undergoing a layout pass
2087     */
2088    boolean isInLayout() {
2089        return mInLayout;
2090    }
2091
2092    /**
2093     * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
2094     * undergoing a layout pass. requestLayout() should not generally be called during layout,
2095     * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
2096     * all children in that container hierarchy are measured and laid out at the end of the layout
2097     * pass for that container). If requestLayout() is called anyway, we handle it correctly
2098     * by registering all requesters during a frame as it proceeds. At the end of the frame,
2099     * we check all of those views to see if any still have pending layout requests, which
2100     * indicates that they were not correctly handled by their container hierarchy. If that is
2101     * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
2102     * to blank containers, and force a second request/measure/layout pass in this frame. If
2103     * more requestLayout() calls are received during that second layout pass, we post those
2104     * requests to the next frame to avoid possible infinite loops.
2105     *
2106     * <p>The return value from this method indicates whether the request should proceed
2107     * (if it is a request during the first layout pass) or should be skipped and posted to the
2108     * next frame (if it is a request during the second layout pass).</p>
2109     *
2110     * @param view the view that requested the layout.
2111     *
2112     * @return true if request should proceed, false otherwise.
2113     */
2114    boolean requestLayoutDuringLayout(final View view) {
2115        if (view.mParent == null || view.mAttachInfo == null) {
2116            // Would not normally trigger another layout, so just let it pass through as usual
2117            return true;
2118        }
2119        if (!mLayoutRequesters.contains(view)) {
2120            mLayoutRequesters.add(view);
2121        }
2122        if (!mHandlingLayoutInLayoutRequest) {
2123            // Let the request proceed normally; it will be processed in a second layout pass
2124            // if necessary
2125            return true;
2126        } else {
2127            // Don't let the request proceed during the second layout pass.
2128            // It will post to the next frame instead.
2129            return false;
2130        }
2131    }
2132
2133    private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
2134            int desiredWindowHeight) {
2135        mLayoutRequested = false;
2136        mScrollMayChange = true;
2137        mInLayout = true;
2138
2139        final View host = mView;
2140        if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
2141            Log.v(TAG, "Laying out " + host + " to (" +
2142                    host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
2143        }
2144
2145        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
2146        try {
2147            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2148
2149            mInLayout = false;
2150            int numViewsRequestingLayout = mLayoutRequesters.size();
2151            if (numViewsRequestingLayout > 0) {
2152                // requestLayout() was called during layout.
2153                // If no layout-request flags are set on the requesting views, there is no problem.
2154                // If some requests are still pending, then we need to clear those flags and do
2155                // a full request/measure/layout pass to handle this situation.
2156                ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
2157                        false);
2158                if (validLayoutRequesters != null) {
2159                    // Set this flag to indicate that any further requests are happening during
2160                    // the second pass, which may result in posting those requests to the next
2161                    // frame instead
2162                    mHandlingLayoutInLayoutRequest = true;
2163
2164                    // Process fresh layout requests, then measure and layout
2165                    int numValidRequests = validLayoutRequesters.size();
2166                    for (int i = 0; i < numValidRequests; ++i) {
2167                        final View view = validLayoutRequesters.get(i);
2168                        Log.w("View", "requestLayout() improperly called by " + view +
2169                                " during layout: running second layout pass");
2170                        view.requestLayout();
2171                    }
2172                    measureHierarchy(host, lp, mView.getContext().getResources(),
2173                            desiredWindowWidth, desiredWindowHeight);
2174                    mInLayout = true;
2175                    host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2176
2177                    mHandlingLayoutInLayoutRequest = false;
2178
2179                    // Check the valid requests again, this time without checking/clearing the
2180                    // layout flags, since requests happening during the second pass get noop'd
2181                    validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
2182                    if (validLayoutRequesters != null) {
2183                        final ArrayList<View> finalRequesters = validLayoutRequesters;
2184                        // Post second-pass requests to the next frame
2185                        getRunQueue().post(new Runnable() {
2186                            @Override
2187                            public void run() {
2188                                int numValidRequests = finalRequesters.size();
2189                                for (int i = 0; i < numValidRequests; ++i) {
2190                                    final View view = finalRequesters.get(i);
2191                                    Log.w("View", "requestLayout() improperly called by " + view +
2192                                            " during second layout pass: posting in next frame");
2193                                    view.requestLayout();
2194                                }
2195                            }
2196                        });
2197                    }
2198                }
2199
2200            }
2201        } finally {
2202            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2203        }
2204        mInLayout = false;
2205    }
2206
2207    /**
2208     * This method is called during layout when there have been calls to requestLayout() during
2209     * layout. It walks through the list of views that requested layout to determine which ones
2210     * still need it, based on visibility in the hierarchy and whether they have already been
2211     * handled (as is usually the case with ListView children).
2212     *
2213     * @param layoutRequesters The list of views that requested layout during layout
2214     * @param secondLayoutRequests Whether the requests were issued during the second layout pass.
2215     * If so, the FORCE_LAYOUT flag was not set on requesters.
2216     * @return A list of the actual views that still need to be laid out.
2217     */
2218    private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters,
2219            boolean secondLayoutRequests) {
2220
2221        int numViewsRequestingLayout = layoutRequesters.size();
2222        ArrayList<View> validLayoutRequesters = null;
2223        for (int i = 0; i < numViewsRequestingLayout; ++i) {
2224            View view = layoutRequesters.get(i);
2225            if (view != null && view.mAttachInfo != null && view.mParent != null &&
2226                    (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) ==
2227                            View.PFLAG_FORCE_LAYOUT)) {
2228                boolean gone = false;
2229                View parent = view;
2230                // Only trigger new requests for views in a non-GONE hierarchy
2231                while (parent != null) {
2232                    if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) {
2233                        gone = true;
2234                        break;
2235                    }
2236                    if (parent.mParent instanceof View) {
2237                        parent = (View) parent.mParent;
2238                    } else {
2239                        parent = null;
2240                    }
2241                }
2242                if (!gone) {
2243                    if (validLayoutRequesters == null) {
2244                        validLayoutRequesters = new ArrayList<View>();
2245                    }
2246                    validLayoutRequesters.add(view);
2247                }
2248            }
2249        }
2250        if (!secondLayoutRequests) {
2251            // If we're checking the layout flags, then we need to clean them up also
2252            for (int i = 0; i < numViewsRequestingLayout; ++i) {
2253                View view = layoutRequesters.get(i);
2254                while (view != null &&
2255                        (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
2256                    view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
2257                    if (view.mParent instanceof View) {
2258                        view = (View) view.mParent;
2259                    } else {
2260                        view = null;
2261                    }
2262                }
2263            }
2264        }
2265        layoutRequesters.clear();
2266        return validLayoutRequesters;
2267    }
2268
2269    @Override
2270    public void requestTransparentRegion(View child) {
2271        // the test below should not fail unless someone is messing with us
2272        checkThread();
2273        if (mView == child) {
2274            mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
2275            // Need to make sure we re-evaluate the window attributes next
2276            // time around, to ensure the window has the correct format.
2277            mWindowAttributesChanged = true;
2278            mWindowAttributesChangesFlag = 0;
2279            requestLayout();
2280        }
2281    }
2282
2283    /**
2284     * Figures out the measure spec for the root view in a window based on it's
2285     * layout params.
2286     *
2287     * @param windowSize
2288     *            The available width or height of the window
2289     *
2290     * @param rootDimension
2291     *            The layout params for one dimension (width or height) of the
2292     *            window.
2293     *
2294     * @return The measure spec to use to measure the root view.
2295     */
2296    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
2297        int measureSpec;
2298        switch (rootDimension) {
2299
2300        case ViewGroup.LayoutParams.MATCH_PARENT:
2301            // Window can't resize. Force root view to be windowSize.
2302            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2303            break;
2304        case ViewGroup.LayoutParams.WRAP_CONTENT:
2305            // Window can resize. Set max size for root view.
2306            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2307            break;
2308        default:
2309            // Window wants to be an exact size. Force root view to be that size.
2310            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2311            break;
2312        }
2313        return measureSpec;
2314    }
2315
2316    int mHardwareXOffset;
2317    int mHardwareYOffset;
2318    int mResizeAlpha;
2319    final Paint mResizePaint = new Paint();
2320
2321    @Override
2322    public void onHardwarePreDraw(DisplayListCanvas canvas) {
2323        canvas.translate(-mHardwareXOffset, -mHardwareYOffset);
2324    }
2325
2326    @Override
2327    public void onHardwarePostDraw(DisplayListCanvas canvas) {
2328        if (mResizeBuffer != null) {
2329            mResizePaint.setAlpha(mResizeAlpha);
2330            canvas.drawHardwareLayer(mResizeBuffer, mHardwareXOffset, mHardwareYOffset,
2331                    mResizePaint);
2332        }
2333        drawAccessibilityFocusedDrawableIfNeeded(canvas);
2334    }
2335
2336    /**
2337     * @hide
2338     */
2339    void outputDisplayList(View view) {
2340        RenderNode renderNode = view.updateDisplayListIfDirty();
2341        renderNode.output();
2342    }
2343
2344    /**
2345     * @see #PROPERTY_PROFILE_RENDERING
2346     */
2347    private void profileRendering(boolean enabled) {
2348        if (mProfileRendering) {
2349            mRenderProfilingEnabled = enabled;
2350
2351            if (mRenderProfiler != null) {
2352                mChoreographer.removeFrameCallback(mRenderProfiler);
2353            }
2354            if (mRenderProfilingEnabled) {
2355                if (mRenderProfiler == null) {
2356                    mRenderProfiler = new Choreographer.FrameCallback() {
2357                        @Override
2358                        public void doFrame(long frameTimeNanos) {
2359                            mDirty.set(0, 0, mWidth, mHeight);
2360                            scheduleTraversals();
2361                            if (mRenderProfilingEnabled) {
2362                                mChoreographer.postFrameCallback(mRenderProfiler);
2363                            }
2364                        }
2365                    };
2366                }
2367                mChoreographer.postFrameCallback(mRenderProfiler);
2368            } else {
2369                mRenderProfiler = null;
2370            }
2371        }
2372    }
2373
2374    /**
2375     * Called from draw() when DEBUG_FPS is enabled
2376     */
2377    private void trackFPS() {
2378        // Tracks frames per second drawn. First value in a series of draws may be bogus
2379        // because it down not account for the intervening idle time
2380        long nowTime = System.currentTimeMillis();
2381        if (mFpsStartTime < 0) {
2382            mFpsStartTime = mFpsPrevTime = nowTime;
2383            mFpsNumFrames = 0;
2384        } else {
2385            ++mFpsNumFrames;
2386            String thisHash = Integer.toHexString(System.identityHashCode(this));
2387            long frameTime = nowTime - mFpsPrevTime;
2388            long totalTime = nowTime - mFpsStartTime;
2389            Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime);
2390            mFpsPrevTime = nowTime;
2391            if (totalTime > 1000) {
2392                float fps = (float) mFpsNumFrames * 1000 / totalTime;
2393                Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps);
2394                mFpsStartTime = nowTime;
2395                mFpsNumFrames = 0;
2396            }
2397        }
2398    }
2399
2400    private void performDraw() {
2401        if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
2402            return;
2403        }
2404
2405        final boolean fullRedrawNeeded = mFullRedrawNeeded;
2406        mFullRedrawNeeded = false;
2407
2408        mIsDrawing = true;
2409        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2410        try {
2411            draw(fullRedrawNeeded);
2412        } finally {
2413            mIsDrawing = false;
2414            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2415        }
2416
2417        // For whatever reason we didn't create a HardwareRenderer, end any
2418        // hardware animations that are now dangling
2419        if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
2420            final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
2421            for (int i = 0; i < count; i++) {
2422                mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
2423            }
2424            mAttachInfo.mPendingAnimatingRenderNodes.clear();
2425        }
2426
2427        if (mReportNextDraw) {
2428            mReportNextDraw = false;
2429            if (mAttachInfo.mHardwareRenderer != null) {
2430                mAttachInfo.mHardwareRenderer.fence();
2431            }
2432
2433            if (LOCAL_LOGV) {
2434                Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2435            }
2436            if (mSurfaceHolder != null && mSurface.isValid()) {
2437                mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2438                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2439                if (callbacks != null) {
2440                    for (SurfaceHolder.Callback c : callbacks) {
2441                        if (c instanceof SurfaceHolder.Callback2) {
2442                            ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
2443                                    mSurfaceHolder);
2444                        }
2445                    }
2446                }
2447            }
2448            try {
2449                mWindowSession.finishDrawing(mWindow);
2450            } catch (RemoteException e) {
2451            }
2452        }
2453    }
2454
2455    private void draw(boolean fullRedrawNeeded) {
2456        Surface surface = mSurface;
2457        if (!surface.isValid()) {
2458            return;
2459        }
2460
2461        if (DEBUG_FPS) {
2462            trackFPS();
2463        }
2464
2465        if (!sFirstDrawComplete) {
2466            synchronized (sFirstDrawHandlers) {
2467                sFirstDrawComplete = true;
2468                final int count = sFirstDrawHandlers.size();
2469                for (int i = 0; i< count; i++) {
2470                    mHandler.post(sFirstDrawHandlers.get(i));
2471                }
2472            }
2473        }
2474
2475        scrollToRectOrFocus(null, false);
2476
2477        if (mAttachInfo.mViewScrollChanged) {
2478            mAttachInfo.mViewScrollChanged = false;
2479            mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
2480        }
2481
2482        boolean animating = mScroller != null && mScroller.computeScrollOffset();
2483        final int curScrollY;
2484        if (animating) {
2485            curScrollY = mScroller.getCurrY();
2486        } else {
2487            curScrollY = mScrollY;
2488        }
2489        if (mCurScrollY != curScrollY) {
2490            mCurScrollY = curScrollY;
2491            fullRedrawNeeded = true;
2492            if (mView instanceof RootViewSurfaceTaker) {
2493                ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
2494            }
2495        }
2496
2497        final float appScale = mAttachInfo.mApplicationScale;
2498        final boolean scalingRequired = mAttachInfo.mScalingRequired;
2499
2500        int resizeAlpha = 0;
2501        if (mResizeBuffer != null) {
2502            long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
2503            if (deltaTime < mResizeBufferDuration) {
2504                float amt = deltaTime/(float) mResizeBufferDuration;
2505                amt = mResizeInterpolator.getInterpolation(amt);
2506                animating = true;
2507                resizeAlpha = 255 - (int)(amt*255);
2508            } else {
2509                disposeResizeBuffer();
2510            }
2511        }
2512
2513        final Rect dirty = mDirty;
2514        if (mSurfaceHolder != null) {
2515            // The app owns the surface, we won't draw.
2516            dirty.setEmpty();
2517            if (animating) {
2518                if (mScroller != null) {
2519                    mScroller.abortAnimation();
2520                }
2521                disposeResizeBuffer();
2522            }
2523            return;
2524        }
2525
2526        if (fullRedrawNeeded) {
2527            mAttachInfo.mIgnoreDirtyState = true;
2528            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2529        }
2530
2531        if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2532            Log.v(TAG, "Draw " + mView + "/"
2533                    + mWindowAttributes.getTitle()
2534                    + ": dirty={" + dirty.left + "," + dirty.top
2535                    + "," + dirty.right + "," + dirty.bottom + "} surface="
2536                    + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2537                    appScale + ", width=" + mWidth + ", height=" + mHeight);
2538        }
2539
2540        mAttachInfo.mTreeObserver.dispatchOnDraw();
2541
2542        int xOffset = 0;
2543        int yOffset = curScrollY;
2544        final WindowManager.LayoutParams params = mWindowAttributes;
2545        final Rect surfaceInsets = params != null ? params.surfaceInsets : null;
2546        if (surfaceInsets != null) {
2547            xOffset -= surfaceInsets.left;
2548            yOffset -= surfaceInsets.top;
2549
2550            // Offset dirty rect for surface insets.
2551            dirty.offset(surfaceInsets.left, surfaceInsets.right);
2552        }
2553
2554        boolean accessibilityFocusDirty = false;
2555        final Drawable drawable = mAttachInfo.mAccessibilityFocusDrawable;
2556        if (drawable != null) {
2557            final Rect bounds = mAttachInfo.mTmpInvalRect;
2558            final boolean hasFocus = getAccessibilityFocusedRect(bounds);
2559            if (!hasFocus) {
2560                bounds.setEmpty();
2561            }
2562            if (!bounds.equals(drawable.getBounds())) {
2563                accessibilityFocusDirty = true;
2564            }
2565        }
2566
2567        mAttachInfo.mDrawingTime =
2568                mChoreographer.getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
2569
2570        if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
2571            if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
2572                // If accessibility focus moved, always invalidate the root.
2573                boolean invalidateRoot = accessibilityFocusDirty;
2574
2575                // Draw with hardware renderer.
2576                mIsAnimating = false;
2577
2578                if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
2579                    mHardwareYOffset = yOffset;
2580                    mHardwareXOffset = xOffset;
2581                    invalidateRoot = true;
2582                }
2583                mResizeAlpha = resizeAlpha;
2584
2585                if (invalidateRoot) {
2586                    mAttachInfo.mHardwareRenderer.invalidateRoot();
2587                }
2588
2589                dirty.setEmpty();
2590
2591                mBlockResizeBuffer = false;
2592                mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
2593            } else {
2594                // If we get here with a disabled & requested hardware renderer, something went
2595                // wrong (an invalidate posted right before we destroyed the hardware surface
2596                // for instance) so we should just bail out. Locking the surface with software
2597                // rendering at this point would lock it forever and prevent hardware renderer
2598                // from doing its job when it comes back.
2599                // Before we request a new frame we must however attempt to reinitiliaze the
2600                // hardware renderer if it's in requested state. This would happen after an
2601                // eglTerminate() for instance.
2602                if (mAttachInfo.mHardwareRenderer != null &&
2603                        !mAttachInfo.mHardwareRenderer.isEnabled() &&
2604                        mAttachInfo.mHardwareRenderer.isRequested()) {
2605
2606                    try {
2607                        mAttachInfo.mHardwareRenderer.initializeIfNeeded(
2608                                mWidth, mHeight, mSurface, surfaceInsets);
2609                    } catch (OutOfResourcesException e) {
2610                        handleOutOfResourcesException(e);
2611                        return;
2612                    }
2613
2614                    mFullRedrawNeeded = true;
2615                    scheduleTraversals();
2616                    return;
2617                }
2618
2619                if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
2620                    return;
2621                }
2622            }
2623        }
2624
2625        if (animating) {
2626            mFullRedrawNeeded = true;
2627            scheduleTraversals();
2628        }
2629    }
2630
2631    /**
2632     * @return true if drawing was successful, false if an error occurred
2633     */
2634    private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
2635            boolean scalingRequired, Rect dirty) {
2636
2637        // Draw with software renderer.
2638        final Canvas canvas;
2639        try {
2640            final int left = dirty.left;
2641            final int top = dirty.top;
2642            final int right = dirty.right;
2643            final int bottom = dirty.bottom;
2644
2645            canvas = mSurface.lockCanvas(dirty);
2646
2647            // The dirty rectangle can be modified by Surface.lockCanvas()
2648            //noinspection ConstantConditions
2649            if (left != dirty.left || top != dirty.top || right != dirty.right
2650                    || bottom != dirty.bottom) {
2651                attachInfo.mIgnoreDirtyState = true;
2652            }
2653
2654            // TODO: Do this in native
2655            canvas.setDensity(mDensity);
2656        } catch (Surface.OutOfResourcesException e) {
2657            handleOutOfResourcesException(e);
2658            return false;
2659        } catch (IllegalArgumentException e) {
2660            Log.e(TAG, "Could not lock surface", e);
2661            // Don't assume this is due to out of memory, it could be
2662            // something else, and if it is something else then we could
2663            // kill stuff (or ourself) for no reason.
2664            mLayoutRequested = true;    // ask wm for a new surface next time.
2665            return false;
2666        }
2667
2668        try {
2669            if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2670                Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
2671                        + canvas.getWidth() + ", h=" + canvas.getHeight());
2672                //canvas.drawARGB(255, 255, 0, 0);
2673            }
2674
2675            // If this bitmap's format includes an alpha channel, we
2676            // need to clear it before drawing so that the child will
2677            // properly re-composite its drawing on a transparent
2678            // background. This automatically respects the clip/dirty region
2679            // or
2680            // If we are applying an offset, we need to clear the area
2681            // where the offset doesn't appear to avoid having garbage
2682            // left in the blank areas.
2683            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
2684                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2685            }
2686
2687            dirty.setEmpty();
2688            mIsAnimating = false;
2689            mView.mPrivateFlags |= View.PFLAG_DRAWN;
2690
2691            if (DEBUG_DRAW) {
2692                Context cxt = mView.getContext();
2693                Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
2694                        ", metrics=" + cxt.getResources().getDisplayMetrics() +
2695                        ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2696            }
2697            try {
2698                canvas.translate(-xoff, -yoff);
2699                if (mTranslator != null) {
2700                    mTranslator.translateCanvas(canvas);
2701                }
2702                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2703                attachInfo.mSetIgnoreDirtyState = false;
2704
2705                mView.draw(canvas);
2706
2707                drawAccessibilityFocusedDrawableIfNeeded(canvas);
2708            } finally {
2709                if (!attachInfo.mSetIgnoreDirtyState) {
2710                    // Only clear the flag if it was not set during the mView.draw() call
2711                    attachInfo.mIgnoreDirtyState = false;
2712                }
2713            }
2714        } finally {
2715            try {
2716                surface.unlockCanvasAndPost(canvas);
2717            } catch (IllegalArgumentException e) {
2718                Log.e(TAG, "Could not unlock surface", e);
2719                mLayoutRequested = true;    // ask wm for a new surface next time.
2720                //noinspection ReturnInsideFinallyBlock
2721                return false;
2722            }
2723
2724            if (LOCAL_LOGV) {
2725                Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
2726            }
2727        }
2728        return true;
2729    }
2730
2731    /**
2732     * We want to draw a highlight around the current accessibility focused.
2733     * Since adding a style for all possible view is not a viable option we
2734     * have this specialized drawing method.
2735     *
2736     * Note: We are doing this here to be able to draw the highlight for
2737     *       virtual views in addition to real ones.
2738     *
2739     * @param canvas The canvas on which to draw.
2740     */
2741    private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2742        final Rect bounds = mAttachInfo.mTmpInvalRect;
2743        if (getAccessibilityFocusedRect(bounds)) {
2744            final Drawable drawable = getAccessibilityFocusedDrawable();
2745            if (drawable != null) {
2746                drawable.setBounds(bounds);
2747                drawable.draw(canvas);
2748            }
2749        } else if (mAttachInfo.mAccessibilityFocusDrawable != null) {
2750            mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0);
2751        }
2752    }
2753
2754    private boolean getAccessibilityFocusedRect(Rect bounds) {
2755        final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2756        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2757            return false;
2758        }
2759
2760        final View host = mAccessibilityFocusedHost;
2761        if (host == null || host.mAttachInfo == null) {
2762            return false;
2763        }
2764
2765        final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider();
2766        if (provider == null) {
2767            host.getBoundsOnScreen(bounds, true);
2768        } else if (mAccessibilityFocusedVirtualView != null) {
2769            mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2770        } else {
2771            return false;
2772        }
2773
2774        final AttachInfo attachInfo = mAttachInfo;
2775        bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop);
2776        bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth, attachInfo.mViewRootImpl.mHeight);
2777        return !bounds.isEmpty();
2778    }
2779
2780    private Drawable getAccessibilityFocusedDrawable() {
2781        // Lazily load the accessibility focus drawable.
2782        if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2783            final TypedValue value = new TypedValue();
2784            final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2785                    R.attr.accessibilityFocusedDrawable, value, true);
2786            if (resolved) {
2787                mAttachInfo.mAccessibilityFocusDrawable =
2788                        mView.mContext.getDrawable(value.resourceId);
2789            }
2790        }
2791        return mAttachInfo.mAccessibilityFocusDrawable;
2792    }
2793
2794    /**
2795     * @hide
2796     */
2797    public void setDrawDuringWindowsAnimating(boolean value) {
2798        mDrawDuringWindowsAnimating = value;
2799        if (value) {
2800            handleDispatchWindowAnimationStopped();
2801        }
2802    }
2803
2804    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2805        final Rect ci = mAttachInfo.mContentInsets;
2806        final Rect vi = mAttachInfo.mVisibleInsets;
2807        int scrollY = 0;
2808        boolean handled = false;
2809
2810        if (vi.left > ci.left || vi.top > ci.top
2811                || vi.right > ci.right || vi.bottom > ci.bottom) {
2812            // We'll assume that we aren't going to change the scroll
2813            // offset, since we want to avoid that unless it is actually
2814            // going to make the focus visible...  otherwise we scroll
2815            // all over the place.
2816            scrollY = mScrollY;
2817            // We can be called for two different situations: during a draw,
2818            // to update the scroll position if the focus has changed (in which
2819            // case 'rectangle' is null), or in response to a
2820            // requestChildRectangleOnScreen() call (in which case 'rectangle'
2821            // is non-null and we just want to scroll to whatever that
2822            // rectangle is).
2823            final View focus = mView.findFocus();
2824            if (focus == null) {
2825                return false;
2826            }
2827            View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
2828            if (focus != lastScrolledFocus) {
2829                // If the focus has changed, then ignore any requests to scroll
2830                // to a rectangle; first we want to make sure the entire focus
2831                // view is visible.
2832                rectangle = null;
2833            }
2834            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2835                    + " rectangle=" + rectangle + " ci=" + ci
2836                    + " vi=" + vi);
2837            if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) {
2838                // Optimization: if the focus hasn't changed since last
2839                // time, and no layout has happened, then just leave things
2840                // as they are.
2841                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2842                        + mScrollY + " vi=" + vi.toShortString());
2843            } else {
2844                // We need to determine if the currently focused view is
2845                // within the visible part of the window and, if not, apply
2846                // a pan so it can be seen.
2847                mLastScrolledFocus = new WeakReference<View>(focus);
2848                mScrollMayChange = false;
2849                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2850                // Try to find the rectangle from the focus view.
2851                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2852                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2853                            + mView.getWidth() + " h=" + mView.getHeight()
2854                            + " ci=" + ci.toShortString()
2855                            + " vi=" + vi.toShortString());
2856                    if (rectangle == null) {
2857                        focus.getFocusedRect(mTempRect);
2858                        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2859                                + ": focusRect=" + mTempRect.toShortString());
2860                        if (mView instanceof ViewGroup) {
2861                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2862                                    focus, mTempRect);
2863                        }
2864                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2865                                "Focus in window: focusRect="
2866                                + mTempRect.toShortString()
2867                                + " visRect=" + mVisRect.toShortString());
2868                    } else {
2869                        mTempRect.set(rectangle);
2870                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2871                                "Request scroll to rect: "
2872                                + mTempRect.toShortString()
2873                                + " visRect=" + mVisRect.toShortString());
2874                    }
2875                    if (mTempRect.intersect(mVisRect)) {
2876                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2877                                "Focus window visible rect: "
2878                                + mTempRect.toShortString());
2879                        if (mTempRect.height() >
2880                                (mView.getHeight()-vi.top-vi.bottom)) {
2881                            // If the focus simply is not going to fit, then
2882                            // best is probably just to leave things as-is.
2883                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2884                                    "Too tall; leaving scrollY=" + scrollY);
2885                        } else if ((mTempRect.top-scrollY) < vi.top) {
2886                            scrollY -= vi.top - (mTempRect.top-scrollY);
2887                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2888                                    "Top covered; scrollY=" + scrollY);
2889                        } else if ((mTempRect.bottom-scrollY)
2890                                > (mView.getHeight()-vi.bottom)) {
2891                            scrollY += (mTempRect.bottom-scrollY)
2892                                    - (mView.getHeight()-vi.bottom);
2893                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2894                                    "Bottom covered; scrollY=" + scrollY);
2895                        }
2896                        handled = true;
2897                    }
2898                }
2899            }
2900        }
2901
2902        if (scrollY != mScrollY) {
2903            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2904                    + mScrollY + " , new=" + scrollY);
2905            if (!immediate && mResizeBuffer == null) {
2906                if (mScroller == null) {
2907                    mScroller = new Scroller(mView.getContext());
2908                }
2909                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2910            } else if (mScroller != null) {
2911                mScroller.abortAnimation();
2912            }
2913            mScrollY = scrollY;
2914        }
2915
2916        return handled;
2917    }
2918
2919    /**
2920     * @hide
2921     */
2922    public View getAccessibilityFocusedHost() {
2923        return mAccessibilityFocusedHost;
2924    }
2925
2926    /**
2927     * @hide
2928     */
2929    public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
2930        return mAccessibilityFocusedVirtualView;
2931    }
2932
2933    void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
2934        // If we have a virtual view with accessibility focus we need
2935        // to clear the focus and invalidate the virtual view bounds.
2936        if (mAccessibilityFocusedVirtualView != null) {
2937
2938            AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
2939            View focusHost = mAccessibilityFocusedHost;
2940
2941            // Wipe the state of the current accessibility focus since
2942            // the call into the provider to clear accessibility focus
2943            // will fire an accessibility event which will end up calling
2944            // this method and we want to have clean state when this
2945            // invocation happens.
2946            mAccessibilityFocusedHost = null;
2947            mAccessibilityFocusedVirtualView = null;
2948
2949            // Clear accessibility focus on the host after clearing state since
2950            // this method may be reentrant.
2951            focusHost.clearAccessibilityFocusNoCallbacks();
2952
2953            AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
2954            if (provider != null) {
2955                // Invalidate the area of the cleared accessibility focus.
2956                focusNode.getBoundsInParent(mTempRect);
2957                focusHost.invalidate(mTempRect);
2958                // Clear accessibility focus in the virtual node.
2959                final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
2960                        focusNode.getSourceNodeId());
2961                provider.performAction(virtualNodeId,
2962                        AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
2963            }
2964            focusNode.recycle();
2965        }
2966        if (mAccessibilityFocusedHost != null) {
2967            // Clear accessibility focus in the view.
2968            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2969        }
2970
2971        // Set the new focus host and node.
2972        mAccessibilityFocusedHost = view;
2973        mAccessibilityFocusedVirtualView = node;
2974
2975        if (mAttachInfo.mHardwareRenderer != null) {
2976            mAttachInfo.mHardwareRenderer.invalidateRoot();
2977        }
2978    }
2979
2980    @Override
2981    public void requestChildFocus(View child, View focused) {
2982        if (DEBUG_INPUT_RESIZE) {
2983            Log.v(TAG, "Request child focus: focus now " + focused);
2984        }
2985        checkThread();
2986        scheduleTraversals();
2987    }
2988
2989    @Override
2990    public void clearChildFocus(View child) {
2991        if (DEBUG_INPUT_RESIZE) {
2992            Log.v(TAG, "Clearing child focus");
2993        }
2994        checkThread();
2995        scheduleTraversals();
2996    }
2997
2998    @Override
2999    public ViewParent getParentForAccessibility() {
3000        return null;
3001    }
3002
3003    @Override
3004    public void focusableViewAvailable(View v) {
3005        checkThread();
3006        if (mView != null) {
3007            if (!mView.hasFocus()) {
3008                v.requestFocus();
3009            } else {
3010                // the one case where will transfer focus away from the current one
3011                // is if the current view is a view group that prefers to give focus
3012                // to its children first AND the view is a descendant of it.
3013                View focused = mView.findFocus();
3014                if (focused instanceof ViewGroup) {
3015                    ViewGroup group = (ViewGroup) focused;
3016                    if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3017                            && isViewDescendantOf(v, focused)) {
3018                        v.requestFocus();
3019                    }
3020                }
3021            }
3022        }
3023    }
3024
3025    @Override
3026    public void recomputeViewAttributes(View child) {
3027        checkThread();
3028        if (mView == child) {
3029            mAttachInfo.mRecomputeGlobalAttributes = true;
3030            if (!mWillDrawSoon) {
3031                scheduleTraversals();
3032            }
3033        }
3034    }
3035
3036    void dispatchDetachedFromWindow() {
3037        if (mView != null && mView.mAttachInfo != null) {
3038            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
3039            mView.dispatchDetachedFromWindow();
3040        }
3041
3042        mAccessibilityInteractionConnectionManager.ensureNoConnection();
3043        mAccessibilityManager.removeAccessibilityStateChangeListener(
3044                mAccessibilityInteractionConnectionManager);
3045        mAccessibilityManager.removeHighTextContrastStateChangeListener(
3046                mHighContrastTextManager);
3047        removeSendWindowContentChangedCallback();
3048
3049        destroyHardwareRenderer();
3050
3051        setAccessibilityFocus(null, null);
3052
3053        mView.assignParent(null);
3054        mView = null;
3055        mAttachInfo.mRootView = null;
3056
3057        mSurface.release();
3058
3059        if (mInputQueueCallback != null && mInputQueue != null) {
3060            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
3061            mInputQueue.dispose();
3062            mInputQueueCallback = null;
3063            mInputQueue = null;
3064        }
3065        if (mInputEventReceiver != null) {
3066            mInputEventReceiver.dispose();
3067            mInputEventReceiver = null;
3068        }
3069        try {
3070            mWindowSession.remove(mWindow);
3071        } catch (RemoteException e) {
3072        }
3073
3074        // Dispose the input channel after removing the window so the Window Manager
3075        // doesn't interpret the input channel being closed as an abnormal termination.
3076        if (mInputChannel != null) {
3077            mInputChannel.dispose();
3078            mInputChannel = null;
3079        }
3080
3081        mDisplayManager.unregisterDisplayListener(mDisplayListener);
3082
3083        unscheduleTraversals();
3084    }
3085
3086    void updateConfiguration(Configuration config, boolean force) {
3087        if (DEBUG_CONFIGURATION) Log.v(TAG,
3088                "Applying new config to window "
3089                + mWindowAttributes.getTitle()
3090                + ": " + config);
3091
3092        CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo();
3093        if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
3094            config = new Configuration(config);
3095            ci.applyToConfiguration(mNoncompatDensity, config);
3096        }
3097
3098        synchronized (sConfigCallbacks) {
3099            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
3100                sConfigCallbacks.get(i).onConfigurationChanged(config);
3101            }
3102        }
3103        if (mView != null) {
3104            // At this point the resources have been updated to
3105            // have the most recent config, whatever that is.  Use
3106            // the one in them which may be newer.
3107            config = mView.getResources().getConfiguration();
3108            if (force || mLastConfiguration.diff(config) != 0) {
3109                final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
3110                final int currentLayoutDirection = config.getLayoutDirection();
3111                mLastConfiguration.setTo(config);
3112                if (lastLayoutDirection != currentLayoutDirection &&
3113                        mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
3114                    mView.setLayoutDirection(currentLayoutDirection);
3115                }
3116                mView.dispatchConfigurationChanged(config);
3117            }
3118        }
3119    }
3120
3121    /**
3122     * Return true if child is an ancestor of parent, (or equal to the parent).
3123     */
3124    public static boolean isViewDescendantOf(View child, View parent) {
3125        if (child == parent) {
3126            return true;
3127        }
3128
3129        final ViewParent theParent = child.getParent();
3130        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
3131    }
3132
3133    private final static int MSG_INVALIDATE = 1;
3134    private final static int MSG_INVALIDATE_RECT = 2;
3135    private final static int MSG_DIE = 3;
3136    private final static int MSG_RESIZED = 4;
3137    private final static int MSG_RESIZED_REPORT = 5;
3138    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
3139    private final static int MSG_DISPATCH_INPUT_EVENT = 7;
3140    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
3141    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
3142    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
3143    private final static int MSG_FINISH_INPUT_CONNECTION = 12;
3144    private final static int MSG_CHECK_FOCUS = 13;
3145    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
3146    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
3147    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
3148    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
3149    private final static int MSG_UPDATE_CONFIGURATION = 18;
3150    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
3151    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
3152    private final static int MSG_INVALIDATE_WORLD = 22;
3153    private final static int MSG_WINDOW_MOVED = 23;
3154    private final static int MSG_SYNTHESIZE_INPUT_EVENT = 24;
3155    private final static int MSG_DISPATCH_WINDOW_SHOWN = 25;
3156    private final static int MSG_DISPATCH_WINDOW_ANIMATION_STOPPED = 26;
3157    private final static int MSG_DISPATCH_WINDOW_ANIMATION_STARTED = 27;
3158
3159    final class ViewRootHandler extends Handler {
3160        @Override
3161        public String getMessageName(Message message) {
3162            switch (message.what) {
3163                case MSG_INVALIDATE:
3164                    return "MSG_INVALIDATE";
3165                case MSG_INVALIDATE_RECT:
3166                    return "MSG_INVALIDATE_RECT";
3167                case MSG_DIE:
3168                    return "MSG_DIE";
3169                case MSG_RESIZED:
3170                    return "MSG_RESIZED";
3171                case MSG_RESIZED_REPORT:
3172                    return "MSG_RESIZED_REPORT";
3173                case MSG_WINDOW_FOCUS_CHANGED:
3174                    return "MSG_WINDOW_FOCUS_CHANGED";
3175                case MSG_DISPATCH_INPUT_EVENT:
3176                    return "MSG_DISPATCH_INPUT_EVENT";
3177                case MSG_DISPATCH_APP_VISIBILITY:
3178                    return "MSG_DISPATCH_APP_VISIBILITY";
3179                case MSG_DISPATCH_GET_NEW_SURFACE:
3180                    return "MSG_DISPATCH_GET_NEW_SURFACE";
3181                case MSG_DISPATCH_KEY_FROM_IME:
3182                    return "MSG_DISPATCH_KEY_FROM_IME";
3183                case MSG_FINISH_INPUT_CONNECTION:
3184                    return "MSG_FINISH_INPUT_CONNECTION";
3185                case MSG_CHECK_FOCUS:
3186                    return "MSG_CHECK_FOCUS";
3187                case MSG_CLOSE_SYSTEM_DIALOGS:
3188                    return "MSG_CLOSE_SYSTEM_DIALOGS";
3189                case MSG_DISPATCH_DRAG_EVENT:
3190                    return "MSG_DISPATCH_DRAG_EVENT";
3191                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
3192                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
3193                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
3194                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
3195                case MSG_UPDATE_CONFIGURATION:
3196                    return "MSG_UPDATE_CONFIGURATION";
3197                case MSG_PROCESS_INPUT_EVENTS:
3198                    return "MSG_PROCESS_INPUT_EVENTS";
3199                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
3200                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
3201                case MSG_DISPATCH_WINDOW_ANIMATION_STARTED:
3202                    return "MSG_DISPATCH_WINDOW_ANIMATION_STARTED";
3203                case MSG_DISPATCH_WINDOW_ANIMATION_STOPPED:
3204                    return "MSG_DISPATCH_WINDOW_ANIMATION_STOPPED";
3205                case MSG_WINDOW_MOVED:
3206                    return "MSG_WINDOW_MOVED";
3207                case MSG_SYNTHESIZE_INPUT_EVENT:
3208                    return "MSG_SYNTHESIZE_INPUT_EVENT";
3209                case MSG_DISPATCH_WINDOW_SHOWN:
3210                    return "MSG_DISPATCH_WINDOW_SHOWN";
3211            }
3212            return super.getMessageName(message);
3213        }
3214
3215        @Override
3216        public void handleMessage(Message msg) {
3217            switch (msg.what) {
3218            case MSG_INVALIDATE:
3219                ((View) msg.obj).invalidate();
3220                break;
3221            case MSG_INVALIDATE_RECT:
3222                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
3223                info.target.invalidate(info.left, info.top, info.right, info.bottom);
3224                info.recycle();
3225                break;
3226            case MSG_PROCESS_INPUT_EVENTS:
3227                mProcessInputEventsScheduled = false;
3228                doProcessInputEvents();
3229                break;
3230            case MSG_DISPATCH_APP_VISIBILITY:
3231                handleAppVisibility(msg.arg1 != 0);
3232                break;
3233            case MSG_DISPATCH_GET_NEW_SURFACE:
3234                handleGetNewSurface();
3235                break;
3236            case MSG_RESIZED: {
3237                // Recycled in the fall through...
3238                SomeArgs args = (SomeArgs) msg.obj;
3239                if (mWinFrame.equals(args.arg1)
3240                        && mPendingOverscanInsets.equals(args.arg5)
3241                        && mPendingContentInsets.equals(args.arg2)
3242                        && mPendingStableInsets.equals(args.arg6)
3243                        && mPendingVisibleInsets.equals(args.arg3)
3244                        && args.arg4 == null) {
3245                    break;
3246                }
3247                } // fall through...
3248            case MSG_RESIZED_REPORT:
3249                if (mAdded) {
3250                    SomeArgs args = (SomeArgs) msg.obj;
3251
3252                    Configuration config = (Configuration) args.arg4;
3253                    if (config != null) {
3254                        updateConfiguration(config, false);
3255                    }
3256
3257                    mWinFrame.set((Rect) args.arg1);
3258                    mPendingOverscanInsets.set((Rect) args.arg5);
3259                    mPendingContentInsets.set((Rect) args.arg2);
3260                    mPendingStableInsets.set((Rect) args.arg6);
3261                    mPendingVisibleInsets.set((Rect) args.arg3);
3262
3263                    args.recycle();
3264
3265                    if (msg.what == MSG_RESIZED_REPORT) {
3266                        mReportNextDraw = true;
3267                    }
3268
3269                    requestLayout();
3270                }
3271                break;
3272            case MSG_WINDOW_MOVED:
3273                if (mAdded) {
3274                    final int w = mWinFrame.width();
3275                    final int h = mWinFrame.height();
3276                    final int l = msg.arg1;
3277                    final int t = msg.arg2;
3278                    mWinFrame.left = l;
3279                    mWinFrame.right = l + w;
3280                    mWinFrame.top = t;
3281                    mWinFrame.bottom = t + h;
3282
3283                    requestLayout();
3284                }
3285                break;
3286            case MSG_WINDOW_FOCUS_CHANGED: {
3287                if (mAdded) {
3288                    boolean hasWindowFocus = msg.arg1 != 0;
3289                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
3290
3291                    profileRendering(hasWindowFocus);
3292
3293                    if (hasWindowFocus) {
3294                        boolean inTouchMode = msg.arg2 != 0;
3295                        ensureTouchModeLocally(inTouchMode);
3296
3297                        if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){
3298                            mFullRedrawNeeded = true;
3299                            try {
3300                                final WindowManager.LayoutParams lp = mWindowAttributes;
3301                                final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null;
3302                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3303                                        mWidth, mHeight, mSurface, surfaceInsets);
3304                            } catch (OutOfResourcesException e) {
3305                                Log.e(TAG, "OutOfResourcesException locking surface", e);
3306                                try {
3307                                    if (!mWindowSession.outOfMemory(mWindow)) {
3308                                        Slog.w(TAG, "No processes killed for memory; killing self");
3309                                        Process.killProcess(Process.myPid());
3310                                    }
3311                                } catch (RemoteException ex) {
3312                                }
3313                                // Retry in a bit.
3314                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3315                                return;
3316                            }
3317                        }
3318                    }
3319
3320                    mLastWasImTarget = WindowManager.LayoutParams
3321                            .mayUseInputMethod(mWindowAttributes.flags);
3322
3323                    InputMethodManager imm = InputMethodManager.peekInstance();
3324                    if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3325                        imm.onPreWindowFocus(mView, hasWindowFocus);
3326                    }
3327                    if (mView != null) {
3328                        mAttachInfo.mKeyDispatchState.reset();
3329                        mView.dispatchWindowFocusChanged(hasWindowFocus);
3330                        mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
3331                    }
3332
3333                    // Note: must be done after the focus change callbacks,
3334                    // so all of the view state is set up correctly.
3335                    if (hasWindowFocus) {
3336                        if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3337                            imm.onPostWindowFocus(mView, mView.findFocus(),
3338                                    mWindowAttributes.softInputMode,
3339                                    !mHasHadWindowFocus, mWindowAttributes.flags);
3340                        }
3341                        // Clear the forward bit.  We can just do this directly, since
3342                        // the window manager doesn't care about it.
3343                        mWindowAttributes.softInputMode &=
3344                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3345                        ((WindowManager.LayoutParams)mView.getLayoutParams())
3346                                .softInputMode &=
3347                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3348                        mHasHadWindowFocus = true;
3349                    }
3350
3351                    if (mView != null && mAccessibilityManager.isEnabled()) {
3352                        if (hasWindowFocus) {
3353                            mView.sendAccessibilityEvent(
3354                                    AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3355                        }
3356                    }
3357                }
3358            } break;
3359            case MSG_DIE:
3360                doDie();
3361                break;
3362            case MSG_DISPATCH_INPUT_EVENT: {
3363                SomeArgs args = (SomeArgs)msg.obj;
3364                InputEvent event = (InputEvent)args.arg1;
3365                InputEventReceiver receiver = (InputEventReceiver)args.arg2;
3366                enqueueInputEvent(event, receiver, 0, true);
3367                args.recycle();
3368            } break;
3369            case MSG_SYNTHESIZE_INPUT_EVENT: {
3370                InputEvent event = (InputEvent)msg.obj;
3371                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true);
3372            } break;
3373            case MSG_DISPATCH_KEY_FROM_IME: {
3374                if (LOCAL_LOGV) Log.v(
3375                    TAG, "Dispatching key "
3376                    + msg.obj + " from IME to " + mView);
3377                KeyEvent event = (KeyEvent)msg.obj;
3378                if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3379                    // The IME is trying to say this event is from the
3380                    // system!  Bad bad bad!
3381                    //noinspection UnusedAssignment
3382                    event = KeyEvent.changeFlags(event, event.getFlags() &
3383                            ~KeyEvent.FLAG_FROM_SYSTEM);
3384                }
3385                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3386            } break;
3387            case MSG_FINISH_INPUT_CONNECTION: {
3388                InputMethodManager imm = InputMethodManager.peekInstance();
3389                if (imm != null) {
3390                    imm.reportFinishInputConnection((InputConnection)msg.obj);
3391                }
3392            } break;
3393            case MSG_CHECK_FOCUS: {
3394                InputMethodManager imm = InputMethodManager.peekInstance();
3395                if (imm != null) {
3396                    imm.checkFocus();
3397                }
3398            } break;
3399            case MSG_CLOSE_SYSTEM_DIALOGS: {
3400                if (mView != null) {
3401                    mView.onCloseSystemDialogs((String)msg.obj);
3402                }
3403            } break;
3404            case MSG_DISPATCH_DRAG_EVENT:
3405            case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3406                DragEvent event = (DragEvent)msg.obj;
3407                event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
3408                handleDragEvent(event);
3409            } break;
3410            case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3411                handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3412            } break;
3413            case MSG_UPDATE_CONFIGURATION: {
3414                Configuration config = (Configuration)msg.obj;
3415                if (config.isOtherSeqNewer(mLastConfiguration)) {
3416                    config = mLastConfiguration;
3417                }
3418                updateConfiguration(config, false);
3419            } break;
3420            case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3421                setAccessibilityFocus(null, null);
3422            } break;
3423            case MSG_DISPATCH_WINDOW_ANIMATION_STARTED: {
3424                int remainingFrameCount = msg.arg1;
3425                handleDispatchWindowAnimationStarted(remainingFrameCount);
3426            } break;
3427            case MSG_DISPATCH_WINDOW_ANIMATION_STOPPED: {
3428                handleDispatchWindowAnimationStopped();
3429            } break;
3430            case MSG_INVALIDATE_WORLD: {
3431                if (mView != null) {
3432                    invalidateWorld(mView);
3433                }
3434            } break;
3435            case MSG_DISPATCH_WINDOW_SHOWN: {
3436                handleDispatchWindowShown();
3437            }
3438            }
3439        }
3440    }
3441
3442    final ViewRootHandler mHandler = new ViewRootHandler();
3443
3444    /**
3445     * Something in the current window tells us we need to change the touch mode.  For
3446     * example, we are not in touch mode, and the user touches the screen.
3447     *
3448     * If the touch mode has changed, tell the window manager, and handle it locally.
3449     *
3450     * @param inTouchMode Whether we want to be in touch mode.
3451     * @return True if the touch mode changed and focus changed was changed as a result
3452     */
3453    boolean ensureTouchMode(boolean inTouchMode) {
3454        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3455                + "touch mode is " + mAttachInfo.mInTouchMode);
3456        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3457
3458        // tell the window manager
3459        try {
3460            if (!isInLocalFocusMode()) {
3461                mWindowSession.setInTouchMode(inTouchMode);
3462            }
3463        } catch (RemoteException e) {
3464            throw new RuntimeException(e);
3465        }
3466
3467        // handle the change
3468        return ensureTouchModeLocally(inTouchMode);
3469    }
3470
3471    /**
3472     * Ensure that the touch mode for this window is set, and if it is changing,
3473     * take the appropriate action.
3474     * @param inTouchMode Whether we want to be in touch mode.
3475     * @return True if the touch mode changed and focus changed was changed as a result
3476     */
3477    private boolean ensureTouchModeLocally(boolean inTouchMode) {
3478        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3479                + "touch mode is " + mAttachInfo.mInTouchMode);
3480
3481        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3482
3483        mAttachInfo.mInTouchMode = inTouchMode;
3484        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3485
3486        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3487    }
3488
3489    private boolean enterTouchMode() {
3490        if (mView != null && mView.hasFocus()) {
3491            // note: not relying on mFocusedView here because this could
3492            // be when the window is first being added, and mFocused isn't
3493            // set yet.
3494            final View focused = mView.findFocus();
3495            if (focused != null && !focused.isFocusableInTouchMode()) {
3496                final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused);
3497                if (ancestorToTakeFocus != null) {
3498                    // there is an ancestor that wants focus after its
3499                    // descendants that is focusable in touch mode.. give it
3500                    // focus
3501                    return ancestorToTakeFocus.requestFocus();
3502                } else {
3503                    // There's nothing to focus. Clear and propagate through the
3504                    // hierarchy, but don't attempt to place new focus.
3505                    focused.clearFocusInternal(null, true, false);
3506                    return true;
3507                }
3508            }
3509        }
3510        return false;
3511    }
3512
3513    /**
3514     * Find an ancestor of focused that wants focus after its descendants and is
3515     * focusable in touch mode.
3516     * @param focused The currently focused view.
3517     * @return An appropriate view, or null if no such view exists.
3518     */
3519    private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3520        ViewParent parent = focused.getParent();
3521        while (parent instanceof ViewGroup) {
3522            final ViewGroup vgParent = (ViewGroup) parent;
3523            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3524                    && vgParent.isFocusableInTouchMode()) {
3525                return vgParent;
3526            }
3527            if (vgParent.isRootNamespace()) {
3528                return null;
3529            } else {
3530                parent = vgParent.getParent();
3531            }
3532        }
3533        return null;
3534    }
3535
3536    private boolean leaveTouchMode() {
3537        if (mView != null) {
3538            if (mView.hasFocus()) {
3539                View focusedView = mView.findFocus();
3540                if (!(focusedView instanceof ViewGroup)) {
3541                    // some view has focus, let it keep it
3542                    return false;
3543                } else if (((ViewGroup) focusedView).getDescendantFocusability() !=
3544                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3545                    // some view group has focus, and doesn't prefer its children
3546                    // over itself for focus, so let them keep it.
3547                    return false;
3548                }
3549            }
3550
3551            // find the best view to give focus to in this brave new non-touch-mode
3552            // world
3553            final View focused = focusSearch(null, View.FOCUS_DOWN);
3554            if (focused != null) {
3555                return focused.requestFocus(View.FOCUS_DOWN);
3556            }
3557        }
3558        return false;
3559    }
3560
3561    /**
3562     * Base class for implementing a stage in the chain of responsibility
3563     * for processing input events.
3564     * <p>
3565     * Events are delivered to the stage by the {@link #deliver} method.  The stage
3566     * then has the choice of finishing the event or forwarding it to the next stage.
3567     * </p>
3568     */
3569    abstract class InputStage {
3570        private final InputStage mNext;
3571
3572        protected static final int FORWARD = 0;
3573        protected static final int FINISH_HANDLED = 1;
3574        protected static final int FINISH_NOT_HANDLED = 2;
3575
3576        /**
3577         * Creates an input stage.
3578         * @param next The next stage to which events should be forwarded.
3579         */
3580        public InputStage(InputStage next) {
3581            mNext = next;
3582        }
3583
3584        /**
3585         * Delivers an event to be processed.
3586         */
3587        public final void deliver(QueuedInputEvent q) {
3588            if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
3589                forward(q);
3590            } else if (shouldDropInputEvent(q)) {
3591                finish(q, false);
3592            } else {
3593                apply(q, onProcess(q));
3594            }
3595        }
3596
3597        /**
3598         * Marks the the input event as finished then forwards it to the next stage.
3599         */
3600        protected void finish(QueuedInputEvent q, boolean handled) {
3601            q.mFlags |= QueuedInputEvent.FLAG_FINISHED;
3602            if (handled) {
3603                q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;
3604            }
3605            forward(q);
3606        }
3607
3608        /**
3609         * Forwards the event to the next stage.
3610         */
3611        protected void forward(QueuedInputEvent q) {
3612            onDeliverToNext(q);
3613        }
3614
3615        /**
3616         * Applies a result code from {@link #onProcess} to the specified event.
3617         */
3618        protected void apply(QueuedInputEvent q, int result) {
3619            if (result == FORWARD) {
3620                forward(q);
3621            } else if (result == FINISH_HANDLED) {
3622                finish(q, true);
3623            } else if (result == FINISH_NOT_HANDLED) {
3624                finish(q, false);
3625            } else {
3626                throw new IllegalArgumentException("Invalid result: " + result);
3627            }
3628        }
3629
3630        /**
3631         * Called when an event is ready to be processed.
3632         * @return A result code indicating how the event was handled.
3633         */
3634        protected int onProcess(QueuedInputEvent q) {
3635            return FORWARD;
3636        }
3637
3638        /**
3639         * Called when an event is being delivered to the next stage.
3640         */
3641        protected void onDeliverToNext(QueuedInputEvent q) {
3642            if (DEBUG_INPUT_STAGES) {
3643                Log.v(TAG, "Done with " + getClass().getSimpleName() + ". " + q);
3644            }
3645            if (mNext != null) {
3646                mNext.deliver(q);
3647            } else {
3648                finishInputEvent(q);
3649            }
3650        }
3651
3652        protected boolean shouldDropInputEvent(QueuedInputEvent q) {
3653            if (mView == null || !mAdded) {
3654                Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent);
3655                return true;
3656            } else if ((!mAttachInfo.mHasWindowFocus
3657                    && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) || mStopped
3658                    || (mPausedForTransition && !isBack(q.mEvent))) {
3659                // This is a focus event and the window doesn't currently have input focus or
3660                // has stopped. This could be an event that came back from the previous stage
3661                // but the window has lost focus or stopped in the meantime.
3662                if (isTerminalInputEvent(q.mEvent)) {
3663                    // Don't drop terminal input events, however mark them as canceled.
3664                    q.mEvent.cancel();
3665                    Slog.w(TAG, "Cancelling event due to no window focus: " + q.mEvent);
3666                    return false;
3667                }
3668
3669                // Drop non-terminal input events.
3670                Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent);
3671                return true;
3672            }
3673            return false;
3674        }
3675
3676        void dump(String prefix, PrintWriter writer) {
3677            if (mNext != null) {
3678                mNext.dump(prefix, writer);
3679            }
3680        }
3681
3682        private boolean isBack(InputEvent event) {
3683            if (event instanceof KeyEvent) {
3684                return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK;
3685            } else {
3686                return false;
3687            }
3688        }
3689    }
3690
3691    /**
3692     * Base class for implementing an input pipeline stage that supports
3693     * asynchronous and out-of-order processing of input events.
3694     * <p>
3695     * In addition to what a normal input stage can do, an asynchronous
3696     * input stage may also defer an input event that has been delivered to it
3697     * and finish or forward it later.
3698     * </p>
3699     */
3700    abstract class AsyncInputStage extends InputStage {
3701        private final String mTraceCounter;
3702
3703        private QueuedInputEvent mQueueHead;
3704        private QueuedInputEvent mQueueTail;
3705        private int mQueueLength;
3706
3707        protected static final int DEFER = 3;
3708
3709        /**
3710         * Creates an asynchronous input stage.
3711         * @param next The next stage to which events should be forwarded.
3712         * @param traceCounter The name of a counter to record the size of
3713         * the queue of pending events.
3714         */
3715        public AsyncInputStage(InputStage next, String traceCounter) {
3716            super(next);
3717            mTraceCounter = traceCounter;
3718        }
3719
3720        /**
3721         * Marks the event as deferred, which is to say that it will be handled
3722         * asynchronously.  The caller is responsible for calling {@link #forward}
3723         * or {@link #finish} later when it is done handling the event.
3724         */
3725        protected void defer(QueuedInputEvent q) {
3726            q.mFlags |= QueuedInputEvent.FLAG_DEFERRED;
3727            enqueue(q);
3728        }
3729
3730        @Override
3731        protected void forward(QueuedInputEvent q) {
3732            // Clear the deferred flag.
3733            q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
3734
3735            // Fast path if the queue is empty.
3736            QueuedInputEvent curr = mQueueHead;
3737            if (curr == null) {
3738                super.forward(q);
3739                return;
3740            }
3741
3742            // Determine whether the event must be serialized behind any others
3743            // before it can be delivered to the next stage.  This is done because
3744            // deferred events might be handled out of order by the stage.
3745            final int deviceId = q.mEvent.getDeviceId();
3746            QueuedInputEvent prev = null;
3747            boolean blocked = false;
3748            while (curr != null && curr != q) {
3749                if (!blocked && deviceId == curr.mEvent.getDeviceId()) {
3750                    blocked = true;
3751                }
3752                prev = curr;
3753                curr = curr.mNext;
3754            }
3755
3756            // If the event is blocked, then leave it in the queue to be delivered later.
3757            // Note that the event might not yet be in the queue if it was not previously
3758            // deferred so we will enqueue it if needed.
3759            if (blocked) {
3760                if (curr == null) {
3761                    enqueue(q);
3762                }
3763                return;
3764            }
3765
3766            // The event is not blocked.  Deliver it immediately.
3767            if (curr != null) {
3768                curr = curr.mNext;
3769                dequeue(q, prev);
3770            }
3771            super.forward(q);
3772
3773            // Dequeuing this event may have unblocked successors.  Deliver them.
3774            while (curr != null) {
3775                if (deviceId == curr.mEvent.getDeviceId()) {
3776                    if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) {
3777                        break;
3778                    }
3779                    QueuedInputEvent next = curr.mNext;
3780                    dequeue(curr, prev);
3781                    super.forward(curr);
3782                    curr = next;
3783                } else {
3784                    prev = curr;
3785                    curr = curr.mNext;
3786                }
3787            }
3788        }
3789
3790        @Override
3791        protected void apply(QueuedInputEvent q, int result) {
3792            if (result == DEFER) {
3793                defer(q);
3794            } else {
3795                super.apply(q, result);
3796            }
3797        }
3798
3799        private void enqueue(QueuedInputEvent q) {
3800            if (mQueueTail == null) {
3801                mQueueHead = q;
3802                mQueueTail = q;
3803            } else {
3804                mQueueTail.mNext = q;
3805                mQueueTail = q;
3806            }
3807
3808            mQueueLength += 1;
3809            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3810        }
3811
3812        private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) {
3813            if (prev == null) {
3814                mQueueHead = q.mNext;
3815            } else {
3816                prev.mNext = q.mNext;
3817            }
3818            if (mQueueTail == q) {
3819                mQueueTail = prev;
3820            }
3821            q.mNext = null;
3822
3823            mQueueLength -= 1;
3824            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3825        }
3826
3827        @Override
3828        void dump(String prefix, PrintWriter writer) {
3829            writer.print(prefix);
3830            writer.print(getClass().getName());
3831            writer.print(": mQueueLength=");
3832            writer.println(mQueueLength);
3833
3834            super.dump(prefix, writer);
3835        }
3836    }
3837
3838    /**
3839     * Delivers pre-ime input events to a native activity.
3840     * Does not support pointer events.
3841     */
3842    final class NativePreImeInputStage extends AsyncInputStage
3843            implements InputQueue.FinishedInputEventCallback {
3844        public NativePreImeInputStage(InputStage next, String traceCounter) {
3845            super(next, traceCounter);
3846        }
3847
3848        @Override
3849        protected int onProcess(QueuedInputEvent q) {
3850            if (mInputQueue != null && q.mEvent instanceof KeyEvent) {
3851                mInputQueue.sendInputEvent(q.mEvent, q, true, this);
3852                return DEFER;
3853            }
3854            return FORWARD;
3855        }
3856
3857        @Override
3858        public void onFinishedInputEvent(Object token, boolean handled) {
3859            QueuedInputEvent q = (QueuedInputEvent)token;
3860            if (handled) {
3861                finish(q, true);
3862                return;
3863            }
3864            forward(q);
3865        }
3866    }
3867
3868    /**
3869     * Delivers pre-ime input events to the view hierarchy.
3870     * Does not support pointer events.
3871     */
3872    final class ViewPreImeInputStage extends InputStage {
3873        public ViewPreImeInputStage(InputStage next) {
3874            super(next);
3875        }
3876
3877        @Override
3878        protected int onProcess(QueuedInputEvent q) {
3879            if (q.mEvent instanceof KeyEvent) {
3880                return processKeyEvent(q);
3881            }
3882            return FORWARD;
3883        }
3884
3885        private int processKeyEvent(QueuedInputEvent q) {
3886            final KeyEvent event = (KeyEvent)q.mEvent;
3887            if (mView.dispatchKeyEventPreIme(event)) {
3888                return FINISH_HANDLED;
3889            }
3890            return FORWARD;
3891        }
3892    }
3893
3894    /**
3895     * Delivers input events to the ime.
3896     * Does not support pointer events.
3897     */
3898    final class ImeInputStage extends AsyncInputStage
3899            implements InputMethodManager.FinishedInputEventCallback {
3900        public ImeInputStage(InputStage next, String traceCounter) {
3901            super(next, traceCounter);
3902        }
3903
3904        @Override
3905        protected int onProcess(QueuedInputEvent q) {
3906            if (mLastWasImTarget && !isInLocalFocusMode()) {
3907                InputMethodManager imm = InputMethodManager.peekInstance();
3908                if (imm != null) {
3909                    final InputEvent event = q.mEvent;
3910                    if (DEBUG_IMF) Log.v(TAG, "Sending input event to IME: " + event);
3911                    int result = imm.dispatchInputEvent(event, q, this, mHandler);
3912                    if (result == InputMethodManager.DISPATCH_HANDLED) {
3913                        return FINISH_HANDLED;
3914                    } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) {
3915                        // The IME could not handle it, so skip along to the next InputStage
3916                        return FORWARD;
3917                    } else {
3918                        return DEFER; // callback will be invoked later
3919                    }
3920                }
3921            }
3922            return FORWARD;
3923        }
3924
3925        @Override
3926        public void onFinishedInputEvent(Object token, boolean handled) {
3927            QueuedInputEvent q = (QueuedInputEvent)token;
3928            if (handled) {
3929                finish(q, true);
3930                return;
3931            }
3932            forward(q);
3933        }
3934    }
3935
3936    /**
3937     * Performs early processing of post-ime input events.
3938     */
3939    final class EarlyPostImeInputStage extends InputStage {
3940        public EarlyPostImeInputStage(InputStage next) {
3941            super(next);
3942        }
3943
3944        @Override
3945        protected int onProcess(QueuedInputEvent q) {
3946            if (q.mEvent instanceof KeyEvent) {
3947                return processKeyEvent(q);
3948            } else {
3949                final int source = q.mEvent.getSource();
3950                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3951                    return processPointerEvent(q);
3952                }
3953            }
3954            return FORWARD;
3955        }
3956
3957        private int processKeyEvent(QueuedInputEvent q) {
3958            final KeyEvent event = (KeyEvent)q.mEvent;
3959
3960            // If the key's purpose is to exit touch mode then we consume it
3961            // and consider it handled.
3962            if (checkForLeavingTouchModeAndConsume(event)) {
3963                return FINISH_HANDLED;
3964            }
3965
3966            // Make sure the fallback event policy sees all keys that will be
3967            // delivered to the view hierarchy.
3968            mFallbackEventHandler.preDispatchKeyEvent(event);
3969            return FORWARD;
3970        }
3971
3972        private int processPointerEvent(QueuedInputEvent q) {
3973            final MotionEvent event = (MotionEvent)q.mEvent;
3974
3975            // Translate the pointer event for compatibility, if needed.
3976            if (mTranslator != null) {
3977                mTranslator.translateEventInScreenToAppWindow(event);
3978            }
3979
3980            // Enter touch mode on down or scroll.
3981            final int action = event.getAction();
3982            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3983                ensureTouchMode(true);
3984            }
3985
3986            // Offset the scroll position.
3987            if (mCurScrollY != 0) {
3988                event.offsetLocation(0, mCurScrollY);
3989            }
3990
3991            // Remember the touch position for possible drag-initiation.
3992            if (event.isTouchEvent()) {
3993                mLastTouchPoint.x = event.getRawX();
3994                mLastTouchPoint.y = event.getRawY();
3995            }
3996            return FORWARD;
3997        }
3998    }
3999
4000    /**
4001     * Delivers post-ime input events to a native activity.
4002     */
4003    final class NativePostImeInputStage extends AsyncInputStage
4004            implements InputQueue.FinishedInputEventCallback {
4005        public NativePostImeInputStage(InputStage next, String traceCounter) {
4006            super(next, traceCounter);
4007        }
4008
4009        @Override
4010        protected int onProcess(QueuedInputEvent q) {
4011            if (mInputQueue != null) {
4012                mInputQueue.sendInputEvent(q.mEvent, q, false, this);
4013                return DEFER;
4014            }
4015            return FORWARD;
4016        }
4017
4018        @Override
4019        public void onFinishedInputEvent(Object token, boolean handled) {
4020            QueuedInputEvent q = (QueuedInputEvent)token;
4021            if (handled) {
4022                finish(q, true);
4023                return;
4024            }
4025            forward(q);
4026        }
4027    }
4028
4029    /**
4030     * Delivers post-ime input events to the view hierarchy.
4031     */
4032    final class ViewPostImeInputStage extends InputStage {
4033        public ViewPostImeInputStage(InputStage next) {
4034            super(next);
4035        }
4036
4037        @Override
4038        protected int onProcess(QueuedInputEvent q) {
4039            if (q.mEvent instanceof KeyEvent) {
4040                return processKeyEvent(q);
4041            } else {
4042                // If delivering a new non-key event, make sure the window is
4043                // now allowed to start updating.
4044                handleDispatchWindowAnimationStopped();
4045                final int source = q.mEvent.getSource();
4046                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
4047                    return processPointerEvent(q);
4048                } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4049                    return processTrackballEvent(q);
4050                } else {
4051                    return processGenericMotionEvent(q);
4052                }
4053            }
4054        }
4055
4056        @Override
4057        protected void onDeliverToNext(QueuedInputEvent q) {
4058            if (mUnbufferedInputDispatch
4059                    && q.mEvent instanceof MotionEvent
4060                    && ((MotionEvent)q.mEvent).isTouchEvent()
4061                    && isTerminalInputEvent(q.mEvent)) {
4062                mUnbufferedInputDispatch = false;
4063                scheduleConsumeBatchedInput();
4064            }
4065            super.onDeliverToNext(q);
4066        }
4067
4068        private int processKeyEvent(QueuedInputEvent q) {
4069            final KeyEvent event = (KeyEvent)q.mEvent;
4070
4071            if (event.getAction() != KeyEvent.ACTION_UP) {
4072                // If delivering a new key event, make sure the window is
4073                // now allowed to start updating.
4074                handleDispatchWindowAnimationStopped();
4075            }
4076
4077            // Deliver the key to the view hierarchy.
4078            if (mView.dispatchKeyEvent(event)) {
4079                return FINISH_HANDLED;
4080            }
4081
4082            if (shouldDropInputEvent(q)) {
4083                return FINISH_NOT_HANDLED;
4084            }
4085
4086            // If the Control modifier is held, try to interpret the key as a shortcut.
4087            if (event.getAction() == KeyEvent.ACTION_DOWN
4088                    && event.isCtrlPressed()
4089                    && event.getRepeatCount() == 0
4090                    && !KeyEvent.isModifierKey(event.getKeyCode())) {
4091                if (mView.dispatchKeyShortcutEvent(event)) {
4092                    return FINISH_HANDLED;
4093                }
4094                if (shouldDropInputEvent(q)) {
4095                    return FINISH_NOT_HANDLED;
4096                }
4097            }
4098
4099            // Apply the fallback event policy.
4100            if (mFallbackEventHandler.dispatchKeyEvent(event)) {
4101                return FINISH_HANDLED;
4102            }
4103            if (shouldDropInputEvent(q)) {
4104                return FINISH_NOT_HANDLED;
4105            }
4106
4107            // Handle automatic focus changes.
4108            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4109                int direction = 0;
4110                switch (event.getKeyCode()) {
4111                    case KeyEvent.KEYCODE_DPAD_LEFT:
4112                        if (event.hasNoModifiers()) {
4113                            direction = View.FOCUS_LEFT;
4114                        }
4115                        break;
4116                    case KeyEvent.KEYCODE_DPAD_RIGHT:
4117                        if (event.hasNoModifiers()) {
4118                            direction = View.FOCUS_RIGHT;
4119                        }
4120                        break;
4121                    case KeyEvent.KEYCODE_DPAD_UP:
4122                        if (event.hasNoModifiers()) {
4123                            direction = View.FOCUS_UP;
4124                        }
4125                        break;
4126                    case KeyEvent.KEYCODE_DPAD_DOWN:
4127                        if (event.hasNoModifiers()) {
4128                            direction = View.FOCUS_DOWN;
4129                        }
4130                        break;
4131                    case KeyEvent.KEYCODE_TAB:
4132                        if (event.hasNoModifiers()) {
4133                            direction = View.FOCUS_FORWARD;
4134                        } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
4135                            direction = View.FOCUS_BACKWARD;
4136                        }
4137                        break;
4138                }
4139                if (direction != 0) {
4140                    View focused = mView.findFocus();
4141                    if (focused != null) {
4142                        View v = focused.focusSearch(direction);
4143                        if (v != null && v != focused) {
4144                            // do the math the get the interesting rect
4145                            // of previous focused into the coord system of
4146                            // newly focused view
4147                            focused.getFocusedRect(mTempRect);
4148                            if (mView instanceof ViewGroup) {
4149                                ((ViewGroup) mView).offsetDescendantRectToMyCoords(
4150                                        focused, mTempRect);
4151                                ((ViewGroup) mView).offsetRectIntoDescendantCoords(
4152                                        v, mTempRect);
4153                            }
4154                            if (v.requestFocus(direction, mTempRect)) {
4155                                playSoundEffect(SoundEffectConstants
4156                                        .getContantForFocusDirection(direction));
4157                                return FINISH_HANDLED;
4158                            }
4159                        }
4160
4161                        // Give the focused view a last chance to handle the dpad key.
4162                        if (mView.dispatchUnhandledMove(focused, direction)) {
4163                            return FINISH_HANDLED;
4164                        }
4165                    } else {
4166                        // find the best view to give focus to in this non-touch-mode with no-focus
4167                        View v = focusSearch(null, direction);
4168                        if (v != null && v.requestFocus(direction)) {
4169                            return FINISH_HANDLED;
4170                        }
4171                    }
4172                }
4173            }
4174            return FORWARD;
4175        }
4176
4177        private int processPointerEvent(QueuedInputEvent q) {
4178            final MotionEvent event = (MotionEvent)q.mEvent;
4179
4180            mAttachInfo.mUnbufferedDispatchRequested = false;
4181            boolean handled = mView.dispatchPointerEvent(event);
4182            if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4183                mUnbufferedInputDispatch = true;
4184                if (mConsumeBatchedInputScheduled) {
4185                    scheduleConsumeBatchedInputImmediately();
4186                }
4187            }
4188            return handled ? FINISH_HANDLED : FORWARD;
4189        }
4190
4191        private int processTrackballEvent(QueuedInputEvent q) {
4192            final MotionEvent event = (MotionEvent)q.mEvent;
4193
4194            if (mView.dispatchTrackballEvent(event)) {
4195                return FINISH_HANDLED;
4196            }
4197            return FORWARD;
4198        }
4199
4200        private int processGenericMotionEvent(QueuedInputEvent q) {
4201            final MotionEvent event = (MotionEvent)q.mEvent;
4202
4203            // Deliver the event to the view.
4204            if (mView.dispatchGenericMotionEvent(event)) {
4205                return FINISH_HANDLED;
4206            }
4207            return FORWARD;
4208        }
4209    }
4210
4211    /**
4212     * Performs synthesis of new input events from unhandled input events.
4213     */
4214    final class SyntheticInputStage extends InputStage {
4215        private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
4216        private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
4217        private final SyntheticTouchNavigationHandler mTouchNavigation =
4218                new SyntheticTouchNavigationHandler();
4219        private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
4220
4221        public SyntheticInputStage() {
4222            super(null);
4223        }
4224
4225        @Override
4226        protected int onProcess(QueuedInputEvent q) {
4227            q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
4228            if (q.mEvent instanceof MotionEvent) {
4229                final MotionEvent event = (MotionEvent)q.mEvent;
4230                final int source = event.getSource();
4231                if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4232                    mTrackball.process(event);
4233                    return FINISH_HANDLED;
4234                } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4235                    mJoystick.process(event);
4236                    return FINISH_HANDLED;
4237                } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4238                        == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4239                    mTouchNavigation.process(event);
4240                    return FINISH_HANDLED;
4241                }
4242            } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4243                mKeyboard.process((KeyEvent)q.mEvent);
4244                return FINISH_HANDLED;
4245            }
4246
4247            return FORWARD;
4248        }
4249
4250        @Override
4251        protected void onDeliverToNext(QueuedInputEvent q) {
4252            if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
4253                // Cancel related synthetic events if any prior stage has handled the event.
4254                if (q.mEvent instanceof MotionEvent) {
4255                    final MotionEvent event = (MotionEvent)q.mEvent;
4256                    final int source = event.getSource();
4257                    if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4258                        mTrackball.cancel(event);
4259                    } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4260                        mJoystick.cancel(event);
4261                    } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4262                            == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4263                        mTouchNavigation.cancel(event);
4264                    }
4265                }
4266            }
4267            super.onDeliverToNext(q);
4268        }
4269    }
4270
4271    /**
4272     * Creates dpad events from unhandled trackball movements.
4273     */
4274    final class SyntheticTrackballHandler {
4275        private final TrackballAxis mX = new TrackballAxis();
4276        private final TrackballAxis mY = new TrackballAxis();
4277        private long mLastTime;
4278
4279        public void process(MotionEvent event) {
4280            // Translate the trackball event into DPAD keys and try to deliver those.
4281            long curTime = SystemClock.uptimeMillis();
4282            if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
4283                // It has been too long since the last movement,
4284                // so restart at the beginning.
4285                mX.reset(0);
4286                mY.reset(0);
4287                mLastTime = curTime;
4288            }
4289
4290            final int action = event.getAction();
4291            final int metaState = event.getMetaState();
4292            switch (action) {
4293                case MotionEvent.ACTION_DOWN:
4294                    mX.reset(2);
4295                    mY.reset(2);
4296                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4297                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4298                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4299                            InputDevice.SOURCE_KEYBOARD));
4300                    break;
4301                case MotionEvent.ACTION_UP:
4302                    mX.reset(2);
4303                    mY.reset(2);
4304                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4305                            KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4306                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4307                            InputDevice.SOURCE_KEYBOARD));
4308                    break;
4309            }
4310
4311            if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step="
4312                    + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
4313                    + " move=" + event.getX()
4314                    + " / Y=" + mY.position + " step="
4315                    + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
4316                    + " move=" + event.getY());
4317            final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
4318            final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
4319
4320            // Generate DPAD events based on the trackball movement.
4321            // We pick the axis that has moved the most as the direction of
4322            // the DPAD.  When we generate DPAD events for one axis, then the
4323            // other axis is reset -- we don't want to perform DPAD jumps due
4324            // to slight movements in the trackball when making major movements
4325            // along the other axis.
4326            int keycode = 0;
4327            int movement = 0;
4328            float accel = 1;
4329            if (xOff > yOff) {
4330                movement = mX.generate();
4331                if (movement != 0) {
4332                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
4333                            : KeyEvent.KEYCODE_DPAD_LEFT;
4334                    accel = mX.acceleration;
4335                    mY.reset(2);
4336                }
4337            } else if (yOff > 0) {
4338                movement = mY.generate();
4339                if (movement != 0) {
4340                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
4341                            : KeyEvent.KEYCODE_DPAD_UP;
4342                    accel = mY.acceleration;
4343                    mX.reset(2);
4344                }
4345            }
4346
4347            if (keycode != 0) {
4348                if (movement < 0) movement = -movement;
4349                int accelMovement = (int)(movement * accel);
4350                if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
4351                        + " accelMovement=" + accelMovement
4352                        + " accel=" + accel);
4353                if (accelMovement > movement) {
4354                    if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4355                            + keycode);
4356                    movement--;
4357                    int repeatCount = accelMovement - movement;
4358                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4359                            KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
4360                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4361                            InputDevice.SOURCE_KEYBOARD));
4362                }
4363                while (movement > 0) {
4364                    if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4365                            + keycode);
4366                    movement--;
4367                    curTime = SystemClock.uptimeMillis();
4368                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4369                            KeyEvent.ACTION_DOWN, keycode, 0, metaState,
4370                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4371                            InputDevice.SOURCE_KEYBOARD));
4372                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4373                            KeyEvent.ACTION_UP, keycode, 0, metaState,
4374                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4375                            InputDevice.SOURCE_KEYBOARD));
4376                }
4377                mLastTime = curTime;
4378            }
4379        }
4380
4381        public void cancel(MotionEvent event) {
4382            mLastTime = Integer.MIN_VALUE;
4383
4384            // If we reach this, we consumed a trackball event.
4385            // Because we will not translate the trackball event into a key event,
4386            // touch mode will not exit, so we exit touch mode here.
4387            if (mView != null && mAdded) {
4388                ensureTouchMode(false);
4389            }
4390        }
4391    }
4392
4393    /**
4394     * Maintains state information for a single trackball axis, generating
4395     * discrete (DPAD) movements based on raw trackball motion.
4396     */
4397    static final class TrackballAxis {
4398        /**
4399         * The maximum amount of acceleration we will apply.
4400         */
4401        static final float MAX_ACCELERATION = 20;
4402
4403        /**
4404         * The maximum amount of time (in milliseconds) between events in order
4405         * for us to consider the user to be doing fast trackball movements,
4406         * and thus apply an acceleration.
4407         */
4408        static final long FAST_MOVE_TIME = 150;
4409
4410        /**
4411         * Scaling factor to the time (in milliseconds) between events to how
4412         * much to multiple/divide the current acceleration.  When movement
4413         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4414         * FAST_MOVE_TIME it divides it.
4415         */
4416        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4417
4418        static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
4419        static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
4420        static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
4421
4422        float position;
4423        float acceleration = 1;
4424        long lastMoveTime = 0;
4425        int step;
4426        int dir;
4427        int nonAccelMovement;
4428
4429        void reset(int _step) {
4430            position = 0;
4431            acceleration = 1;
4432            lastMoveTime = 0;
4433            step = _step;
4434            dir = 0;
4435        }
4436
4437        /**
4438         * Add trackball movement into the state.  If the direction of movement
4439         * has been reversed, the state is reset before adding the
4440         * movement (so that you don't have to compensate for any previously
4441         * collected movement before see the result of the movement in the
4442         * new direction).
4443         *
4444         * @return Returns the absolute value of the amount of movement
4445         * collected so far.
4446         */
4447        float collect(float off, long time, String axis) {
4448            long normTime;
4449            if (off > 0) {
4450                normTime = (long)(off * FAST_MOVE_TIME);
4451                if (dir < 0) {
4452                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4453                    position = 0;
4454                    step = 0;
4455                    acceleration = 1;
4456                    lastMoveTime = 0;
4457                }
4458                dir = 1;
4459            } else if (off < 0) {
4460                normTime = (long)((-off) * FAST_MOVE_TIME);
4461                if (dir > 0) {
4462                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4463                    position = 0;
4464                    step = 0;
4465                    acceleration = 1;
4466                    lastMoveTime = 0;
4467                }
4468                dir = -1;
4469            } else {
4470                normTime = 0;
4471            }
4472
4473            // The number of milliseconds between each movement that is
4474            // considered "normal" and will not result in any acceleration
4475            // or deceleration, scaled by the offset we have here.
4476            if (normTime > 0) {
4477                long delta = time - lastMoveTime;
4478                lastMoveTime = time;
4479                float acc = acceleration;
4480                if (delta < normTime) {
4481                    // The user is scrolling rapidly, so increase acceleration.
4482                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4483                    if (scale > 1) acc *= scale;
4484                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4485                            + off + " normTime=" + normTime + " delta=" + delta
4486                            + " scale=" + scale + " acc=" + acc);
4487                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4488                } else {
4489                    // The user is scrolling slowly, so decrease acceleration.
4490                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4491                    if (scale > 1) acc /= scale;
4492                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4493                            + off + " normTime=" + normTime + " delta=" + delta
4494                            + " scale=" + scale + " acc=" + acc);
4495                    acceleration = acc > 1 ? acc : 1;
4496                }
4497            }
4498            position += off;
4499            return Math.abs(position);
4500        }
4501
4502        /**
4503         * Generate the number of discrete movement events appropriate for
4504         * the currently collected trackball movement.
4505         *
4506         * @return Returns the number of discrete movements, either positive
4507         * or negative, or 0 if there is not enough trackball movement yet
4508         * for a discrete movement.
4509         */
4510        int generate() {
4511            int movement = 0;
4512            nonAccelMovement = 0;
4513            do {
4514                final int dir = position >= 0 ? 1 : -1;
4515                switch (step) {
4516                    // If we are going to execute the first step, then we want
4517                    // to do this as soon as possible instead of waiting for
4518                    // a full movement, in order to make things look responsive.
4519                    case 0:
4520                        if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4521                            return movement;
4522                        }
4523                        movement += dir;
4524                        nonAccelMovement += dir;
4525                        step = 1;
4526                        break;
4527                    // If we have generated the first movement, then we need
4528                    // to wait for the second complete trackball motion before
4529                    // generating the second discrete movement.
4530                    case 1:
4531                        if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4532                            return movement;
4533                        }
4534                        movement += dir;
4535                        nonAccelMovement += dir;
4536                        position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
4537                        step = 2;
4538                        break;
4539                    // After the first two, we generate discrete movements
4540                    // consistently with the trackball, applying an acceleration
4541                    // if the trackball is moving quickly.  This is a simple
4542                    // acceleration on top of what we already compute based
4543                    // on how quickly the wheel is being turned, to apply
4544                    // a longer increasing acceleration to continuous movement
4545                    // in one direction.
4546                    default:
4547                        if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4548                            return movement;
4549                        }
4550                        movement += dir;
4551                        position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4552                        float acc = acceleration;
4553                        acc *= 1.1f;
4554                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4555                        break;
4556                }
4557            } while (true);
4558        }
4559    }
4560
4561    /**
4562     * Creates dpad events from unhandled joystick movements.
4563     */
4564    final class SyntheticJoystickHandler extends Handler {
4565        private final static String TAG = "SyntheticJoystickHandler";
4566        private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
4567        private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
4568
4569        private int mLastXDirection;
4570        private int mLastYDirection;
4571        private int mLastXKeyCode;
4572        private int mLastYKeyCode;
4573
4574        public SyntheticJoystickHandler() {
4575            super(true);
4576        }
4577
4578        @Override
4579        public void handleMessage(Message msg) {
4580            switch (msg.what) {
4581                case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
4582                case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
4583                    KeyEvent oldEvent = (KeyEvent)msg.obj;
4584                    KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
4585                            SystemClock.uptimeMillis(),
4586                            oldEvent.getRepeatCount() + 1);
4587                    if (mAttachInfo.mHasWindowFocus) {
4588                        enqueueInputEvent(e);
4589                        Message m = obtainMessage(msg.what, e);
4590                        m.setAsynchronous(true);
4591                        sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
4592                    }
4593                } break;
4594            }
4595        }
4596
4597        public void process(MotionEvent event) {
4598            switch(event.getActionMasked()) {
4599            case MotionEvent.ACTION_CANCEL:
4600                cancel(event);
4601                break;
4602            case MotionEvent.ACTION_MOVE:
4603                update(event, true);
4604                break;
4605            default:
4606                Log.w(TAG, "Unexpected action: " + event.getActionMasked());
4607            }
4608        }
4609
4610        private void cancel(MotionEvent event) {
4611            removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4612            removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4613            update(event, false);
4614        }
4615
4616        private void update(MotionEvent event, boolean synthesizeNewKeys) {
4617            final long time = event.getEventTime();
4618            final int metaState = event.getMetaState();
4619            final int deviceId = event.getDeviceId();
4620            final int source = event.getSource();
4621
4622            int xDirection = joystickAxisValueToDirection(
4623                    event.getAxisValue(MotionEvent.AXIS_HAT_X));
4624            if (xDirection == 0) {
4625                xDirection = joystickAxisValueToDirection(event.getX());
4626            }
4627
4628            int yDirection = joystickAxisValueToDirection(
4629                    event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4630            if (yDirection == 0) {
4631                yDirection = joystickAxisValueToDirection(event.getY());
4632            }
4633
4634            if (xDirection != mLastXDirection) {
4635                if (mLastXKeyCode != 0) {
4636                    removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4637                    enqueueInputEvent(new KeyEvent(time, time,
4638                            KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState,
4639                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4640                    mLastXKeyCode = 0;
4641                }
4642
4643                mLastXDirection = xDirection;
4644
4645                if (xDirection != 0 && synthesizeNewKeys) {
4646                    mLastXKeyCode = xDirection > 0
4647                            ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
4648                    final KeyEvent e = new KeyEvent(time, time,
4649                            KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState,
4650                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4651                    enqueueInputEvent(e);
4652                    Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
4653                    m.setAsynchronous(true);
4654                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4655                }
4656            }
4657
4658            if (yDirection != mLastYDirection) {
4659                if (mLastYKeyCode != 0) {
4660                    removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4661                    enqueueInputEvent(new KeyEvent(time, time,
4662                            KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState,
4663                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4664                    mLastYKeyCode = 0;
4665                }
4666
4667                mLastYDirection = yDirection;
4668
4669                if (yDirection != 0 && synthesizeNewKeys) {
4670                    mLastYKeyCode = yDirection > 0
4671                            ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
4672                    final KeyEvent e = new KeyEvent(time, time,
4673                            KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState,
4674                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4675                    enqueueInputEvent(e);
4676                    Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e);
4677                    m.setAsynchronous(true);
4678                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4679                }
4680            }
4681        }
4682
4683        private int joystickAxisValueToDirection(float value) {
4684            if (value >= 0.5f) {
4685                return 1;
4686            } else if (value <= -0.5f) {
4687                return -1;
4688            } else {
4689                return 0;
4690            }
4691        }
4692    }
4693
4694    /**
4695     * Creates dpad events from unhandled touch navigation movements.
4696     */
4697    final class SyntheticTouchNavigationHandler extends Handler {
4698        private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4699        private static final boolean LOCAL_DEBUG = false;
4700
4701        // Assumed nominal width and height in millimeters of a touch navigation pad,
4702        // if no resolution information is available from the input system.
4703        private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
4704        private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
4705
4706        /* TODO: These constants should eventually be moved to ViewConfiguration. */
4707
4708        // The nominal distance traveled to move by one unit.
4709        private static final int TICK_DISTANCE_MILLIMETERS = 12;
4710
4711        // Minimum and maximum fling velocity in ticks per second.
4712        // The minimum velocity should be set such that we perform enough ticks per
4713        // second that the fling appears to be fluid.  For example, if we set the minimum
4714        // to 2 ticks per second, then there may be up to half a second delay between the next
4715        // to last and last ticks which is noticeably discrete and jerky.  This value should
4716        // probably not be set to anything less than about 4.
4717        // If fling accuracy is a problem then consider tuning the tick distance instead.
4718        private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
4719        private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
4720
4721        // Fling velocity decay factor applied after each new key is emitted.
4722        // This parameter controls the deceleration and overall duration of the fling.
4723        // The fling stops automatically when its velocity drops below the minimum
4724        // fling velocity defined above.
4725        private static final float FLING_TICK_DECAY = 0.8f;
4726
4727        /* The input device that we are tracking. */
4728
4729        private int mCurrentDeviceId = -1;
4730        private int mCurrentSource;
4731        private boolean mCurrentDeviceSupported;
4732
4733        /* Configuration for the current input device. */
4734
4735        // The scaled tick distance.  A movement of this amount should generally translate
4736        // into a single dpad event in a given direction.
4737        private float mConfigTickDistance;
4738
4739        // The minimum and maximum scaled fling velocity.
4740        private float mConfigMinFlingVelocity;
4741        private float mConfigMaxFlingVelocity;
4742
4743        /* Tracking state. */
4744
4745        // The velocity tracker for detecting flings.
4746        private VelocityTracker mVelocityTracker;
4747
4748        // The active pointer id, or -1 if none.
4749        private int mActivePointerId = -1;
4750
4751        // Location where tracking started.
4752        private float mStartX;
4753        private float mStartY;
4754
4755        // Most recently observed position.
4756        private float mLastX;
4757        private float mLastY;
4758
4759        // Accumulated movement delta since the last direction key was sent.
4760        private float mAccumulatedX;
4761        private float mAccumulatedY;
4762
4763        // Set to true if any movement was delivered to the app.
4764        // Implies that tap slop was exceeded.
4765        private boolean mConsumedMovement;
4766
4767        // The most recently sent key down event.
4768        // The keycode remains set until the direction changes or a fling ends
4769        // so that repeated key events may be generated as required.
4770        private long mPendingKeyDownTime;
4771        private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4772        private int mPendingKeyRepeatCount;
4773        private int mPendingKeyMetaState;
4774
4775        // The current fling velocity while a fling is in progress.
4776        private boolean mFlinging;
4777        private float mFlingVelocity;
4778
4779        public SyntheticTouchNavigationHandler() {
4780            super(true);
4781        }
4782
4783        public void process(MotionEvent event) {
4784            // Update the current device information.
4785            final long time = event.getEventTime();
4786            final int deviceId = event.getDeviceId();
4787            final int source = event.getSource();
4788            if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
4789                finishKeys(time);
4790                finishTracking(time);
4791                mCurrentDeviceId = deviceId;
4792                mCurrentSource = source;
4793                mCurrentDeviceSupported = false;
4794                InputDevice device = event.getDevice();
4795                if (device != null) {
4796                    // In order to support an input device, we must know certain
4797                    // characteristics about it, such as its size and resolution.
4798                    InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
4799                    InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
4800                    if (xRange != null && yRange != null) {
4801                        mCurrentDeviceSupported = true;
4802
4803                        // Infer the resolution if it not actually known.
4804                        float xRes = xRange.getResolution();
4805                        if (xRes <= 0) {
4806                            xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
4807                        }
4808                        float yRes = yRange.getResolution();
4809                        if (yRes <= 0) {
4810                            yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
4811                        }
4812                        float nominalRes = (xRes + yRes) * 0.5f;
4813
4814                        // Precompute all of the configuration thresholds we will need.
4815                        mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
4816                        mConfigMinFlingVelocity =
4817                                MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4818                        mConfigMaxFlingVelocity =
4819                                MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4820
4821                        if (LOCAL_DEBUG) {
4822                            Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
4823                                    + " (" + Integer.toHexString(mCurrentSource) + "): "
4824                                    + ", mConfigTickDistance=" + mConfigTickDistance
4825                                    + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
4826                                    + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
4827                        }
4828                    }
4829                }
4830            }
4831            if (!mCurrentDeviceSupported) {
4832                return;
4833            }
4834
4835            // Handle the event.
4836            final int action = event.getActionMasked();
4837            switch (action) {
4838                case MotionEvent.ACTION_DOWN: {
4839                    boolean caughtFling = mFlinging;
4840                    finishKeys(time);
4841                    finishTracking(time);
4842                    mActivePointerId = event.getPointerId(0);
4843                    mVelocityTracker = VelocityTracker.obtain();
4844                    mVelocityTracker.addMovement(event);
4845                    mStartX = event.getX();
4846                    mStartY = event.getY();
4847                    mLastX = mStartX;
4848                    mLastY = mStartY;
4849                    mAccumulatedX = 0;
4850                    mAccumulatedY = 0;
4851
4852                    // If we caught a fling, then pretend that the tap slop has already
4853                    // been exceeded to suppress taps whose only purpose is to stop the fling.
4854                    mConsumedMovement = caughtFling;
4855                    break;
4856                }
4857
4858                case MotionEvent.ACTION_MOVE:
4859                case MotionEvent.ACTION_UP: {
4860                    if (mActivePointerId < 0) {
4861                        break;
4862                    }
4863                    final int index = event.findPointerIndex(mActivePointerId);
4864                    if (index < 0) {
4865                        finishKeys(time);
4866                        finishTracking(time);
4867                        break;
4868                    }
4869
4870                    mVelocityTracker.addMovement(event);
4871                    final float x = event.getX(index);
4872                    final float y = event.getY(index);
4873                    mAccumulatedX += x - mLastX;
4874                    mAccumulatedY += y - mLastY;
4875                    mLastX = x;
4876                    mLastY = y;
4877
4878                    // Consume any accumulated movement so far.
4879                    final int metaState = event.getMetaState();
4880                    consumeAccumulatedMovement(time, metaState);
4881
4882                    // Detect taps and flings.
4883                    if (action == MotionEvent.ACTION_UP) {
4884                        if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4885                            // It might be a fling.
4886                            mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
4887                            final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
4888                            final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
4889                            if (!startFling(time, vx, vy)) {
4890                                finishKeys(time);
4891                            }
4892                        }
4893                        finishTracking(time);
4894                    }
4895                    break;
4896                }
4897
4898                case MotionEvent.ACTION_CANCEL: {
4899                    finishKeys(time);
4900                    finishTracking(time);
4901                    break;
4902                }
4903            }
4904        }
4905
4906        public void cancel(MotionEvent event) {
4907            if (mCurrentDeviceId == event.getDeviceId()
4908                    && mCurrentSource == event.getSource()) {
4909                final long time = event.getEventTime();
4910                finishKeys(time);
4911                finishTracking(time);
4912            }
4913        }
4914
4915        private void finishKeys(long time) {
4916            cancelFling();
4917            sendKeyUp(time);
4918        }
4919
4920        private void finishTracking(long time) {
4921            if (mActivePointerId >= 0) {
4922                mActivePointerId = -1;
4923                mVelocityTracker.recycle();
4924                mVelocityTracker = null;
4925            }
4926        }
4927
4928        private void consumeAccumulatedMovement(long time, int metaState) {
4929            final float absX = Math.abs(mAccumulatedX);
4930            final float absY = Math.abs(mAccumulatedY);
4931            if (absX >= absY) {
4932                if (absX >= mConfigTickDistance) {
4933                    mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
4934                            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
4935                    mAccumulatedY = 0;
4936                    mConsumedMovement = true;
4937                }
4938            } else {
4939                if (absY >= mConfigTickDistance) {
4940                    mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
4941                            KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
4942                    mAccumulatedX = 0;
4943                    mConsumedMovement = true;
4944                }
4945            }
4946        }
4947
4948        private float consumeAccumulatedMovement(long time, int metaState,
4949                float accumulator, int negativeKeyCode, int positiveKeyCode) {
4950            while (accumulator <= -mConfigTickDistance) {
4951                sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
4952                accumulator += mConfigTickDistance;
4953            }
4954            while (accumulator >= mConfigTickDistance) {
4955                sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
4956                accumulator -= mConfigTickDistance;
4957            }
4958            return accumulator;
4959        }
4960
4961        private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
4962            if (mPendingKeyCode != keyCode) {
4963                sendKeyUp(time);
4964                mPendingKeyDownTime = time;
4965                mPendingKeyCode = keyCode;
4966                mPendingKeyRepeatCount = 0;
4967            } else {
4968                mPendingKeyRepeatCount += 1;
4969            }
4970            mPendingKeyMetaState = metaState;
4971
4972            // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
4973            // but it doesn't quite make sense when simulating the events in this way.
4974            if (LOCAL_DEBUG) {
4975                Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
4976                        + ", repeatCount=" + mPendingKeyRepeatCount
4977                        + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4978            }
4979            enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4980                    KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
4981                    mPendingKeyMetaState, mCurrentDeviceId,
4982                    KeyEvent.FLAG_FALLBACK, mCurrentSource));
4983        }
4984
4985        private void sendKeyUp(long time) {
4986            if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4987                if (LOCAL_DEBUG) {
4988                    Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
4989                            + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4990                }
4991                enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4992                        KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
4993                        mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
4994                        mCurrentSource));
4995                mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4996            }
4997        }
4998
4999        private boolean startFling(long time, float vx, float vy) {
5000            if (LOCAL_DEBUG) {
5001                Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
5002                        + ", min=" + mConfigMinFlingVelocity);
5003            }
5004
5005            // Flings must be oriented in the same direction as the preceding movements.
5006            switch (mPendingKeyCode) {
5007                case KeyEvent.KEYCODE_DPAD_LEFT:
5008                    if (-vx >= mConfigMinFlingVelocity
5009                            && Math.abs(vy) < mConfigMinFlingVelocity) {
5010                        mFlingVelocity = -vx;
5011                        break;
5012                    }
5013                    return false;
5014
5015                case KeyEvent.KEYCODE_DPAD_RIGHT:
5016                    if (vx >= mConfigMinFlingVelocity
5017                            && Math.abs(vy) < mConfigMinFlingVelocity) {
5018                        mFlingVelocity = vx;
5019                        break;
5020                    }
5021                    return false;
5022
5023                case KeyEvent.KEYCODE_DPAD_UP:
5024                    if (-vy >= mConfigMinFlingVelocity
5025                            && Math.abs(vx) < mConfigMinFlingVelocity) {
5026                        mFlingVelocity = -vy;
5027                        break;
5028                    }
5029                    return false;
5030
5031                case KeyEvent.KEYCODE_DPAD_DOWN:
5032                    if (vy >= mConfigMinFlingVelocity
5033                            && Math.abs(vx) < mConfigMinFlingVelocity) {
5034                        mFlingVelocity = vy;
5035                        break;
5036                    }
5037                    return false;
5038            }
5039
5040            // Post the first fling event.
5041            mFlinging = postFling(time);
5042            return mFlinging;
5043        }
5044
5045        private boolean postFling(long time) {
5046            // The idea here is to estimate the time when the pointer would have
5047            // traveled one tick distance unit given the current fling velocity.
5048            // This effect creates continuity of motion.
5049            if (mFlingVelocity >= mConfigMinFlingVelocity) {
5050                long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
5051                postAtTime(mFlingRunnable, time + delay);
5052                if (LOCAL_DEBUG) {
5053                    Log.d(LOCAL_TAG, "Posted fling: velocity="
5054                            + mFlingVelocity + ", delay=" + delay
5055                            + ", keyCode=" + mPendingKeyCode);
5056                }
5057                return true;
5058            }
5059            return false;
5060        }
5061
5062        private void cancelFling() {
5063            if (mFlinging) {
5064                removeCallbacks(mFlingRunnable);
5065                mFlinging = false;
5066            }
5067        }
5068
5069        private final Runnable mFlingRunnable = new Runnable() {
5070            @Override
5071            public void run() {
5072                final long time = SystemClock.uptimeMillis();
5073                sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5074                mFlingVelocity *= FLING_TICK_DECAY;
5075                if (!postFling(time)) {
5076                    mFlinging = false;
5077                    finishKeys(time);
5078                }
5079            }
5080        };
5081    }
5082
5083    final class SyntheticKeyboardHandler {
5084        public void process(KeyEvent event) {
5085            if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5086                return;
5087            }
5088
5089            final KeyCharacterMap kcm = event.getKeyCharacterMap();
5090            final int keyCode = event.getKeyCode();
5091            final int metaState = event.getMetaState();
5092
5093            // Check for fallback actions specified by the key character map.
5094            KeyCharacterMap.FallbackAction fallbackAction =
5095                    kcm.getFallbackAction(keyCode, metaState);
5096            if (fallbackAction != null) {
5097                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5098                KeyEvent fallbackEvent = KeyEvent.obtain(
5099                        event.getDownTime(), event.getEventTime(),
5100                        event.getAction(), fallbackAction.keyCode,
5101                        event.getRepeatCount(), fallbackAction.metaState,
5102                        event.getDeviceId(), event.getScanCode(),
5103                        flags, event.getSource(), null);
5104                fallbackAction.recycle();
5105                enqueueInputEvent(fallbackEvent);
5106            }
5107        }
5108    }
5109
5110    /**
5111     * Returns true if the key is used for keyboard navigation.
5112     * @param keyEvent The key event.
5113     * @return True if the key is used for keyboard navigation.
5114     */
5115    private static boolean isNavigationKey(KeyEvent keyEvent) {
5116        switch (keyEvent.getKeyCode()) {
5117        case KeyEvent.KEYCODE_DPAD_LEFT:
5118        case KeyEvent.KEYCODE_DPAD_RIGHT:
5119        case KeyEvent.KEYCODE_DPAD_UP:
5120        case KeyEvent.KEYCODE_DPAD_DOWN:
5121        case KeyEvent.KEYCODE_DPAD_CENTER:
5122        case KeyEvent.KEYCODE_PAGE_UP:
5123        case KeyEvent.KEYCODE_PAGE_DOWN:
5124        case KeyEvent.KEYCODE_MOVE_HOME:
5125        case KeyEvent.KEYCODE_MOVE_END:
5126        case KeyEvent.KEYCODE_TAB:
5127        case KeyEvent.KEYCODE_SPACE:
5128        case KeyEvent.KEYCODE_ENTER:
5129            return true;
5130        }
5131        return false;
5132    }
5133
5134    /**
5135     * Returns true if the key is used for typing.
5136     * @param keyEvent The key event.
5137     * @return True if the key is used for typing.
5138     */
5139    private static boolean isTypingKey(KeyEvent keyEvent) {
5140        return keyEvent.getUnicodeChar() > 0;
5141    }
5142
5143    /**
5144     * See if the key event means we should leave touch mode (and leave touch mode if so).
5145     * @param event The key event.
5146     * @return Whether this key event should be consumed (meaning the act of
5147     *   leaving touch mode alone is considered the event).
5148     */
5149    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
5150        // Only relevant in touch mode.
5151        if (!mAttachInfo.mInTouchMode) {
5152            return false;
5153        }
5154
5155        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
5156        final int action = event.getAction();
5157        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
5158            return false;
5159        }
5160
5161        // Don't leave touch mode if the IME told us not to.
5162        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
5163            return false;
5164        }
5165
5166        // If the key can be used for keyboard navigation then leave touch mode
5167        // and select a focused view if needed (in ensureTouchMode).
5168        // When a new focused view is selected, we consume the navigation key because
5169        // navigation doesn't make much sense unless a view already has focus so
5170        // the key's purpose is to set focus.
5171        if (isNavigationKey(event)) {
5172            return ensureTouchMode(false);
5173        }
5174
5175        // If the key can be used for typing then leave touch mode
5176        // and select a focused view if needed (in ensureTouchMode).
5177        // Always allow the view to process the typing key.
5178        if (isTypingKey(event)) {
5179            ensureTouchMode(false);
5180            return false;
5181        }
5182
5183        return false;
5184    }
5185
5186    /* drag/drop */
5187    void setLocalDragState(Object obj) {
5188        mLocalDragState = obj;
5189    }
5190
5191    private void handleDragEvent(DragEvent event) {
5192        // From the root, only drag start/end/location are dispatched.  entered/exited
5193        // are determined and dispatched by the viewgroup hierarchy, who then report
5194        // that back here for ultimate reporting back to the framework.
5195        if (mView != null && mAdded) {
5196            final int what = event.mAction;
5197
5198            if (what == DragEvent.ACTION_DRAG_EXITED) {
5199                // A direct EXITED event means that the window manager knows we've just crossed
5200                // a window boundary, so the current drag target within this one must have
5201                // just been exited.  Send it the usual notifications and then we're done
5202                // for now.
5203                mView.dispatchDragEvent(event);
5204            } else {
5205                // Cache the drag description when the operation starts, then fill it in
5206                // on subsequent calls as a convenience
5207                if (what == DragEvent.ACTION_DRAG_STARTED) {
5208                    mCurrentDragView = null;    // Start the current-recipient tracking
5209                    mDragDescription = event.mClipDescription;
5210                } else {
5211                    event.mClipDescription = mDragDescription;
5212                }
5213
5214                // For events with a [screen] location, translate into window coordinates
5215                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
5216                    mDragPoint.set(event.mX, event.mY);
5217                    if (mTranslator != null) {
5218                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
5219                    }
5220
5221                    if (mCurScrollY != 0) {
5222                        mDragPoint.offset(0, mCurScrollY);
5223                    }
5224
5225                    event.mX = mDragPoint.x;
5226                    event.mY = mDragPoint.y;
5227                }
5228
5229                // Remember who the current drag target is pre-dispatch
5230                final View prevDragView = mCurrentDragView;
5231
5232                // Now dispatch the drag/drop event
5233                boolean result = mView.dispatchDragEvent(event);
5234
5235                // If we changed apparent drag target, tell the OS about it
5236                if (prevDragView != mCurrentDragView) {
5237                    try {
5238                        if (prevDragView != null) {
5239                            mWindowSession.dragRecipientExited(mWindow);
5240                        }
5241                        if (mCurrentDragView != null) {
5242                            mWindowSession.dragRecipientEntered(mWindow);
5243                        }
5244                    } catch (RemoteException e) {
5245                        Slog.e(TAG, "Unable to note drag target change");
5246                    }
5247                }
5248
5249                // Report the drop result when we're done
5250                if (what == DragEvent.ACTION_DROP) {
5251                    mDragDescription = null;
5252                    try {
5253                        Log.i(TAG, "Reporting drop result: " + result);
5254                        mWindowSession.reportDropResult(mWindow, result);
5255                    } catch (RemoteException e) {
5256                        Log.e(TAG, "Unable to report drop result");
5257                    }
5258                }
5259
5260                // When the drag operation ends, release any local state object
5261                // that may have been in use
5262                if (what == DragEvent.ACTION_DRAG_ENDED) {
5263                    setLocalDragState(null);
5264                }
5265            }
5266        }
5267        event.recycle();
5268    }
5269
5270    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
5271        if (mSeq != args.seq) {
5272            // The sequence has changed, so we need to update our value and make
5273            // sure to do a traversal afterward so the window manager is given our
5274            // most recent data.
5275            mSeq = args.seq;
5276            mAttachInfo.mForceReportNewAttributes = true;
5277            scheduleTraversals();
5278        }
5279        if (mView == null) return;
5280        if (args.localChanges != 0) {
5281            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
5282        }
5283
5284        int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5285        if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5286            mAttachInfo.mGlobalSystemUiVisibility = visibility;
5287            mView.dispatchSystemUiVisibilityChanged(visibility);
5288        }
5289    }
5290
5291    public void handleDispatchWindowAnimationStarted(int remainingFrameCount) {
5292        if (!mDrawDuringWindowsAnimating) {
5293            mRemainingFrameCount = remainingFrameCount;
5294            mWindowsAnimating = true;
5295        }
5296    }
5297
5298    public void handleDispatchWindowAnimationStopped() {
5299        if (mWindowsAnimating) {
5300            mWindowsAnimating = false;
5301            if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded)  {
5302                scheduleTraversals();
5303            }
5304        }
5305    }
5306
5307    public void handleDispatchWindowShown() {
5308        mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5309    }
5310
5311    public void getLastTouchPoint(Point outLocation) {
5312        outLocation.x = (int) mLastTouchPoint.x;
5313        outLocation.y = (int) mLastTouchPoint.y;
5314    }
5315
5316    public void setDragFocus(View newDragTarget) {
5317        if (mCurrentDragView != newDragTarget) {
5318            mCurrentDragView = newDragTarget;
5319        }
5320    }
5321
5322    private AudioManager getAudioManager() {
5323        if (mView == null) {
5324            throw new IllegalStateException("getAudioManager called when there is no mView");
5325        }
5326        if (mAudioManager == null) {
5327            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5328        }
5329        return mAudioManager;
5330    }
5331
5332    public AccessibilityInteractionController getAccessibilityInteractionController() {
5333        if (mView == null) {
5334            throw new IllegalStateException("getAccessibilityInteractionController"
5335                    + " called when there is no mView");
5336        }
5337        if (mAccessibilityInteractionController == null) {
5338            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
5339        }
5340        return mAccessibilityInteractionController;
5341    }
5342
5343    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5344            boolean insetsPending) throws RemoteException {
5345
5346        float appScale = mAttachInfo.mApplicationScale;
5347        boolean restore = false;
5348        if (params != null && mTranslator != null) {
5349            restore = true;
5350            params.backup();
5351            mTranslator.translateWindowLayout(params);
5352        }
5353        if (params != null) {
5354            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
5355        }
5356        mPendingConfiguration.seq = 0;
5357        //Log.d(TAG, ">>>>>> CALLING relayout");
5358        if (params != null && mOrigWindowType != params.type) {
5359            // For compatibility with old apps, don't crash here.
5360            if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5361                Slog.w(TAG, "Window type can not be changed after "
5362                        + "the window is added; ignoring change of " + mView);
5363                params.type = mOrigWindowType;
5364            }
5365        }
5366        int relayoutResult = mWindowSession.relayout(
5367                mWindow, mSeq, params,
5368                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
5369                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
5370                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
5371                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
5372                mPendingStableInsets, mPendingConfiguration, mSurface);
5373        //Log.d(TAG, "<<<<<< BACK FROM relayout");
5374        if (restore) {
5375            params.restore();
5376        }
5377
5378        if (mTranslator != null) {
5379            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
5380            mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
5381            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5382            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
5383            mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
5384        }
5385        return relayoutResult;
5386    }
5387
5388    /**
5389     * {@inheritDoc}
5390     */
5391    @Override
5392    public void playSoundEffect(int effectId) {
5393        checkThread();
5394
5395        try {
5396            final AudioManager audioManager = getAudioManager();
5397
5398            switch (effectId) {
5399                case SoundEffectConstants.CLICK:
5400                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5401                    return;
5402                case SoundEffectConstants.NAVIGATION_DOWN:
5403                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5404                    return;
5405                case SoundEffectConstants.NAVIGATION_LEFT:
5406                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5407                    return;
5408                case SoundEffectConstants.NAVIGATION_RIGHT:
5409                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5410                    return;
5411                case SoundEffectConstants.NAVIGATION_UP:
5412                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5413                    return;
5414                default:
5415                    throw new IllegalArgumentException("unknown effect id " + effectId +
5416                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
5417            }
5418        } catch (IllegalStateException e) {
5419            // Exception thrown by getAudioManager() when mView is null
5420            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
5421            e.printStackTrace();
5422        }
5423    }
5424
5425    /**
5426     * {@inheritDoc}
5427     */
5428    @Override
5429    public boolean performHapticFeedback(int effectId, boolean always) {
5430        try {
5431            return mWindowSession.performHapticFeedback(mWindow, effectId, always);
5432        } catch (RemoteException e) {
5433            return false;
5434        }
5435    }
5436
5437    /**
5438     * {@inheritDoc}
5439     */
5440    @Override
5441    public View focusSearch(View focused, int direction) {
5442        checkThread();
5443        if (!(mView instanceof ViewGroup)) {
5444            return null;
5445        }
5446        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5447    }
5448
5449    public void debug() {
5450        mView.debug();
5451    }
5452
5453    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5454        String innerPrefix = prefix + "  ";
5455        writer.print(prefix); writer.println("ViewRoot:");
5456        writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded);
5457                writer.print(" mRemoved="); writer.println(mRemoved);
5458        writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled=");
5459                writer.println(mConsumeBatchedInputScheduled);
5460        writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled=");
5461                writer.println(mConsumeBatchedInputImmediatelyScheduled);
5462        writer.print(innerPrefix); writer.print("mPendingInputEventCount=");
5463                writer.println(mPendingInputEventCount);
5464        writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled=");
5465                writer.println(mProcessInputEventsScheduled);
5466        writer.print(innerPrefix); writer.print("mTraversalScheduled=");
5467                writer.print(mTraversalScheduled);
5468        if (mTraversalScheduled) {
5469            writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")");
5470        } else {
5471            writer.println();
5472        }
5473        mFirstInputStage.dump(innerPrefix, writer);
5474
5475        mChoreographer.dump(prefix, writer);
5476
5477        writer.print(prefix); writer.println("View Hierarchy:");
5478        dumpViewHierarchy(innerPrefix, writer, mView);
5479    }
5480
5481    private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5482        writer.print(prefix);
5483        if (view == null) {
5484            writer.println("null");
5485            return;
5486        }
5487        writer.println(view.toString());
5488        if (!(view instanceof ViewGroup)) {
5489            return;
5490        }
5491        ViewGroup grp = (ViewGroup)view;
5492        final int N = grp.getChildCount();
5493        if (N <= 0) {
5494            return;
5495        }
5496        prefix = prefix + "  ";
5497        for (int i=0; i<N; i++) {
5498            dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5499        }
5500    }
5501
5502    public void dumpGfxInfo(int[] info) {
5503        info[0] = info[1] = 0;
5504        if (mView != null) {
5505            getGfxInfo(mView, info);
5506        }
5507    }
5508
5509    private static void getGfxInfo(View view, int[] info) {
5510        RenderNode renderNode = view.mRenderNode;
5511        info[0]++;
5512        if (renderNode != null) {
5513            info[1] += renderNode.getDebugSize();
5514        }
5515
5516        if (view instanceof ViewGroup) {
5517            ViewGroup group = (ViewGroup) view;
5518
5519            int count = group.getChildCount();
5520            for (int i = 0; i < count; i++) {
5521                getGfxInfo(group.getChildAt(i), info);
5522            }
5523        }
5524    }
5525
5526    /**
5527     * @param immediate True, do now if not in traversal. False, put on queue and do later.
5528     * @return True, request has been queued. False, request has been completed.
5529     */
5530    boolean die(boolean immediate) {
5531        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
5532        // done by dispatchDetachedFromWindow will cause havoc on return.
5533        if (immediate && !mIsInTraversal) {
5534            doDie();
5535            return false;
5536        }
5537
5538        if (!mIsDrawing) {
5539            destroyHardwareRenderer();
5540        } else {
5541            Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
5542                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
5543        }
5544        mHandler.sendEmptyMessage(MSG_DIE);
5545        return true;
5546    }
5547
5548    void doDie() {
5549        checkThread();
5550        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
5551        synchronized (this) {
5552            if (mRemoved) {
5553                return;
5554            }
5555            mRemoved = true;
5556            if (mAdded) {
5557                dispatchDetachedFromWindow();
5558            }
5559
5560            if (mAdded && !mFirst) {
5561                destroyHardwareRenderer();
5562
5563                if (mView != null) {
5564                    int viewVisibility = mView.getVisibility();
5565                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
5566                    if (mWindowAttributesChanged || viewVisibilityChanged) {
5567                        // If layout params have been changed, first give them
5568                        // to the window manager to make sure it has the correct
5569                        // animation info.
5570                        try {
5571                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5572                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5573                                mWindowSession.finishDrawing(mWindow);
5574                            }
5575                        } catch (RemoteException e) {
5576                        }
5577                    }
5578
5579                    mSurface.release();
5580                }
5581            }
5582
5583            mAdded = false;
5584        }
5585        WindowManagerGlobal.getInstance().doRemoveView(this);
5586    }
5587
5588    public void requestUpdateConfiguration(Configuration config) {
5589        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5590        mHandler.sendMessage(msg);
5591    }
5592
5593    public void loadSystemProperties() {
5594        mHandler.post(new Runnable() {
5595            @Override
5596            public void run() {
5597                // Profiling
5598                mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5599                profileRendering(mAttachInfo.mHasWindowFocus);
5600
5601                // Hardware rendering
5602                if (mAttachInfo.mHardwareRenderer != null) {
5603                    if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
5604                        invalidate();
5605                    }
5606                }
5607
5608                // Layout debugging
5609                boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5610                if (layout != mAttachInfo.mDebugLayout) {
5611                    mAttachInfo.mDebugLayout = layout;
5612                    if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5613                        mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5614                    }
5615                }
5616            }
5617        });
5618    }
5619
5620    private void destroyHardwareRenderer() {
5621        HardwareRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
5622
5623        if (hardwareRenderer != null) {
5624            if (mView != null) {
5625                hardwareRenderer.destroyHardwareResources(mView);
5626            }
5627            hardwareRenderer.destroy();
5628            hardwareRenderer.setRequested(false);
5629
5630            mAttachInfo.mHardwareRenderer = null;
5631            mAttachInfo.mHardwareAccelerated = false;
5632        }
5633    }
5634
5635    public void dispatchFinishInputConnection(InputConnection connection) {
5636        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
5637        mHandler.sendMessage(msg);
5638    }
5639
5640    public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
5641            Rect visibleInsets, Rect stableInsets, boolean reportDraw, Configuration newConfig) {
5642        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
5643                + " contentInsets=" + contentInsets.toShortString()
5644                + " visibleInsets=" + visibleInsets.toShortString()
5645                + " reportDraw=" + reportDraw);
5646        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
5647        if (mTranslator != null) {
5648            mTranslator.translateRectInScreenToAppWindow(frame);
5649            mTranslator.translateRectInScreenToAppWindow(overscanInsets);
5650            mTranslator.translateRectInScreenToAppWindow(contentInsets);
5651            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
5652        }
5653        SomeArgs args = SomeArgs.obtain();
5654        final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5655        args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5656        args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5657        args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5658        args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
5659        args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
5660        args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets;
5661        msg.obj = args;
5662        mHandler.sendMessage(msg);
5663    }
5664
5665    public void dispatchMoved(int newX, int newY) {
5666        if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
5667        if (mTranslator != null) {
5668            PointF point = new PointF(newX, newY);
5669            mTranslator.translatePointInScreenToAppWindow(point);
5670            newX = (int) (point.x + 0.5);
5671            newY = (int) (point.y + 0.5);
5672        }
5673        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5674        mHandler.sendMessage(msg);
5675    }
5676
5677    /**
5678     * Represents a pending input event that is waiting in a queue.
5679     *
5680     * Input events are processed in serial order by the timestamp specified by
5681     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
5682     * one input event to the application at a time and waits for the application
5683     * to finish handling it before delivering the next one.
5684     *
5685     * However, because the application or IME can synthesize and inject multiple
5686     * key events at a time without going through the input dispatcher, we end up
5687     * needing a queue on the application's side.
5688     */
5689    private static final class QueuedInputEvent {
5690        public static final int FLAG_DELIVER_POST_IME = 1 << 0;
5691        public static final int FLAG_DEFERRED = 1 << 1;
5692        public static final int FLAG_FINISHED = 1 << 2;
5693        public static final int FLAG_FINISHED_HANDLED = 1 << 3;
5694        public static final int FLAG_RESYNTHESIZED = 1 << 4;
5695        public static final int FLAG_UNHANDLED = 1 << 5;
5696
5697        public QueuedInputEvent mNext;
5698
5699        public InputEvent mEvent;
5700        public InputEventReceiver mReceiver;
5701        public int mFlags;
5702
5703        public boolean shouldSkipIme() {
5704            if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5705                return true;
5706            }
5707            return mEvent instanceof MotionEvent
5708                    && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5709        }
5710
5711        public boolean shouldSendToSynthesizer() {
5712            if ((mFlags & FLAG_UNHANDLED) != 0) {
5713                return true;
5714            }
5715
5716            return false;
5717        }
5718
5719        @Override
5720        public String toString() {
5721            StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
5722            boolean hasPrevious = false;
5723            hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
5724            hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
5725            hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
5726            hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
5727            hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
5728            hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
5729            if (!hasPrevious) {
5730                sb.append("0");
5731            }
5732            sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
5733            sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
5734            sb.append(", mEvent=" + mEvent + "}");
5735            return sb.toString();
5736        }
5737
5738        private boolean flagToString(String name, int flag,
5739                boolean hasPrevious, StringBuilder sb) {
5740            if ((mFlags & flag) != 0) {
5741                if (hasPrevious) {
5742                    sb.append("|");
5743                }
5744                sb.append(name);
5745                return true;
5746            }
5747            return hasPrevious;
5748        }
5749    }
5750
5751    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
5752            InputEventReceiver receiver, int flags) {
5753        QueuedInputEvent q = mQueuedInputEventPool;
5754        if (q != null) {
5755            mQueuedInputEventPoolSize -= 1;
5756            mQueuedInputEventPool = q.mNext;
5757            q.mNext = null;
5758        } else {
5759            q = new QueuedInputEvent();
5760        }
5761
5762        q.mEvent = event;
5763        q.mReceiver = receiver;
5764        q.mFlags = flags;
5765        return q;
5766    }
5767
5768    private void recycleQueuedInputEvent(QueuedInputEvent q) {
5769        q.mEvent = null;
5770        q.mReceiver = null;
5771
5772        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
5773            mQueuedInputEventPoolSize += 1;
5774            q.mNext = mQueuedInputEventPool;
5775            mQueuedInputEventPool = q;
5776        }
5777    }
5778
5779    void enqueueInputEvent(InputEvent event) {
5780        enqueueInputEvent(event, null, 0, false);
5781    }
5782
5783    void enqueueInputEvent(InputEvent event,
5784            InputEventReceiver receiver, int flags, boolean processImmediately) {
5785        adjustInputEventForCompatibility(event);
5786        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
5787
5788        // Always enqueue the input event in order, regardless of its time stamp.
5789        // We do this because the application or the IME may inject key events
5790        // in response to touch events and we want to ensure that the injected keys
5791        // are processed in the order they were received and we cannot trust that
5792        // the time stamp of injected events are monotonic.
5793        QueuedInputEvent last = mPendingInputEventTail;
5794        if (last == null) {
5795            mPendingInputEventHead = q;
5796            mPendingInputEventTail = q;
5797        } else {
5798            last.mNext = q;
5799            mPendingInputEventTail = q;
5800        }
5801        mPendingInputEventCount += 1;
5802        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5803                mPendingInputEventCount);
5804
5805        if (processImmediately) {
5806            doProcessInputEvents();
5807        } else {
5808            scheduleProcessInputEvents();
5809        }
5810    }
5811
5812    private void scheduleProcessInputEvents() {
5813        if (!mProcessInputEventsScheduled) {
5814            mProcessInputEventsScheduled = true;
5815            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
5816            msg.setAsynchronous(true);
5817            mHandler.sendMessage(msg);
5818        }
5819    }
5820
5821    void doProcessInputEvents() {
5822        // Deliver all pending input events in the queue.
5823        while (mPendingInputEventHead != null) {
5824            QueuedInputEvent q = mPendingInputEventHead;
5825            mPendingInputEventHead = q.mNext;
5826            if (mPendingInputEventHead == null) {
5827                mPendingInputEventTail = null;
5828            }
5829            q.mNext = null;
5830
5831            mPendingInputEventCount -= 1;
5832            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5833                    mPendingInputEventCount);
5834
5835            long eventTime = q.mEvent.getEventTimeNano();
5836            long oldestEventTime = eventTime;
5837            if (q.mEvent instanceof MotionEvent) {
5838                MotionEvent me = (MotionEvent)q.mEvent;
5839                if (me.getHistorySize() > 0) {
5840                    oldestEventTime = me.getHistoricalEventTimeNano(0);
5841                }
5842            }
5843            mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);
5844
5845            deliverInputEvent(q);
5846        }
5847
5848        // We are done processing all input events that we can process right now
5849        // so we can clear the pending flag immediately.
5850        if (mProcessInputEventsScheduled) {
5851            mProcessInputEventsScheduled = false;
5852            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
5853        }
5854    }
5855
5856    private void deliverInputEvent(QueuedInputEvent q) {
5857        Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5858                q.mEvent.getSequenceNumber());
5859        if (mInputEventConsistencyVerifier != null) {
5860            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
5861        }
5862
5863        InputStage stage;
5864        if (q.shouldSendToSynthesizer()) {
5865            stage = mSyntheticInputStage;
5866        } else {
5867            stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
5868        }
5869
5870        if (stage != null) {
5871            stage.deliver(q);
5872        } else {
5873            finishInputEvent(q);
5874        }
5875    }
5876
5877    private void finishInputEvent(QueuedInputEvent q) {
5878        Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5879                q.mEvent.getSequenceNumber());
5880
5881        if (q.mReceiver != null) {
5882            boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
5883            q.mReceiver.finishInputEvent(q.mEvent, handled);
5884        } else {
5885            q.mEvent.recycleIfNeededAfterDispatch();
5886        }
5887
5888        recycleQueuedInputEvent(q);
5889    }
5890
5891    private void adjustInputEventForCompatibility(InputEvent e) {
5892        if (mTargetSdkVersion < Build.VERSION_CODES.MNC && e instanceof MotionEvent) {
5893            MotionEvent motion = (MotionEvent) e;
5894            final int mask =
5895                MotionEvent.BUTTON_STYLUS_PRIMARY | MotionEvent.BUTTON_STYLUS_SECONDARY;
5896            final int buttonState = motion.getButtonState();
5897            final int compatButtonState = (buttonState & mask) >> 4;
5898            if (compatButtonState != 0) {
5899                motion.setButtonState(buttonState | compatButtonState);
5900            }
5901        }
5902    }
5903
5904    static boolean isTerminalInputEvent(InputEvent event) {
5905        if (event instanceof KeyEvent) {
5906            final KeyEvent keyEvent = (KeyEvent)event;
5907            return keyEvent.getAction() == KeyEvent.ACTION_UP;
5908        } else {
5909            final MotionEvent motionEvent = (MotionEvent)event;
5910            final int action = motionEvent.getAction();
5911            return action == MotionEvent.ACTION_UP
5912                    || action == MotionEvent.ACTION_CANCEL
5913                    || action == MotionEvent.ACTION_HOVER_EXIT;
5914        }
5915    }
5916
5917    void scheduleConsumeBatchedInput() {
5918        if (!mConsumeBatchedInputScheduled) {
5919            mConsumeBatchedInputScheduled = true;
5920            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
5921                    mConsumedBatchedInputRunnable, null);
5922        }
5923    }
5924
5925    void unscheduleConsumeBatchedInput() {
5926        if (mConsumeBatchedInputScheduled) {
5927            mConsumeBatchedInputScheduled = false;
5928            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
5929                    mConsumedBatchedInputRunnable, null);
5930        }
5931    }
5932
5933    void scheduleConsumeBatchedInputImmediately() {
5934        if (!mConsumeBatchedInputImmediatelyScheduled) {
5935            unscheduleConsumeBatchedInput();
5936            mConsumeBatchedInputImmediatelyScheduled = true;
5937            mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
5938        }
5939    }
5940
5941    void doConsumeBatchedInput(long frameTimeNanos) {
5942        if (mConsumeBatchedInputScheduled) {
5943            mConsumeBatchedInputScheduled = false;
5944            if (mInputEventReceiver != null) {
5945                if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
5946                        && frameTimeNanos != -1) {
5947                    // If we consumed a batch here, we want to go ahead and schedule the
5948                    // consumption of batched input events on the next frame. Otherwise, we would
5949                    // wait until we have more input events pending and might get starved by other
5950                    // things occurring in the process. If the frame time is -1, however, then
5951                    // we're in a non-batching mode, so there's no need to schedule this.
5952                    scheduleConsumeBatchedInput();
5953                }
5954            }
5955            doProcessInputEvents();
5956        }
5957    }
5958
5959    final class TraversalRunnable implements Runnable {
5960        @Override
5961        public void run() {
5962            doTraversal();
5963        }
5964    }
5965    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
5966
5967    final class WindowInputEventReceiver extends InputEventReceiver {
5968        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
5969            super(inputChannel, looper);
5970        }
5971
5972        @Override
5973        public void onInputEvent(InputEvent event) {
5974            enqueueInputEvent(event, this, 0, true);
5975        }
5976
5977        @Override
5978        public void onBatchedInputEventPending() {
5979            if (mUnbufferedInputDispatch) {
5980                super.onBatchedInputEventPending();
5981            } else {
5982                scheduleConsumeBatchedInput();
5983            }
5984        }
5985
5986        @Override
5987        public void dispose() {
5988            unscheduleConsumeBatchedInput();
5989            super.dispose();
5990        }
5991    }
5992    WindowInputEventReceiver mInputEventReceiver;
5993
5994    final class ConsumeBatchedInputRunnable implements Runnable {
5995        @Override
5996        public void run() {
5997            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
5998        }
5999    }
6000    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
6001            new ConsumeBatchedInputRunnable();
6002    boolean mConsumeBatchedInputScheduled;
6003
6004    final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
6005        @Override
6006        public void run() {
6007            doConsumeBatchedInput(-1);
6008        }
6009    }
6010    final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
6011            new ConsumeBatchedInputImmediatelyRunnable();
6012    boolean mConsumeBatchedInputImmediatelyScheduled;
6013
6014    final class InvalidateOnAnimationRunnable implements Runnable {
6015        private boolean mPosted;
6016        private final ArrayList<View> mViews = new ArrayList<View>();
6017        private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
6018                new ArrayList<AttachInfo.InvalidateInfo>();
6019        private View[] mTempViews;
6020        private AttachInfo.InvalidateInfo[] mTempViewRects;
6021
6022        public void addView(View view) {
6023            synchronized (this) {
6024                mViews.add(view);
6025                postIfNeededLocked();
6026            }
6027        }
6028
6029        public void addViewRect(AttachInfo.InvalidateInfo info) {
6030            synchronized (this) {
6031                mViewRects.add(info);
6032                postIfNeededLocked();
6033            }
6034        }
6035
6036        public void removeView(View view) {
6037            synchronized (this) {
6038                mViews.remove(view);
6039
6040                for (int i = mViewRects.size(); i-- > 0; ) {
6041                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
6042                    if (info.target == view) {
6043                        mViewRects.remove(i);
6044                        info.recycle();
6045                    }
6046                }
6047
6048                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
6049                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
6050                    mPosted = false;
6051                }
6052            }
6053        }
6054
6055        @Override
6056        public void run() {
6057            final int viewCount;
6058            final int viewRectCount;
6059            synchronized (this) {
6060                mPosted = false;
6061
6062                viewCount = mViews.size();
6063                if (viewCount != 0) {
6064                    mTempViews = mViews.toArray(mTempViews != null
6065                            ? mTempViews : new View[viewCount]);
6066                    mViews.clear();
6067                }
6068
6069                viewRectCount = mViewRects.size();
6070                if (viewRectCount != 0) {
6071                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
6072                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6073                    mViewRects.clear();
6074                }
6075            }
6076
6077            for (int i = 0; i < viewCount; i++) {
6078                mTempViews[i].invalidate();
6079                mTempViews[i] = null;
6080            }
6081
6082            for (int i = 0; i < viewRectCount; i++) {
6083                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
6084                info.target.invalidate(info.left, info.top, info.right, info.bottom);
6085                info.recycle();
6086            }
6087        }
6088
6089        private void postIfNeededLocked() {
6090            if (!mPosted) {
6091                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
6092                mPosted = true;
6093            }
6094        }
6095    }
6096    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6097            new InvalidateOnAnimationRunnable();
6098
6099    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6100        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6101        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6102    }
6103
6104    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
6105            long delayMilliseconds) {
6106        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
6107        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6108    }
6109
6110    public void dispatchInvalidateOnAnimation(View view) {
6111        mInvalidateOnAnimationRunnable.addView(view);
6112    }
6113
6114    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6115        mInvalidateOnAnimationRunnable.addViewRect(info);
6116    }
6117
6118    public void cancelInvalidate(View view) {
6119        mHandler.removeMessages(MSG_INVALIDATE, view);
6120        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6121        // them to the pool
6122        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6123        mInvalidateOnAnimationRunnable.removeView(view);
6124    }
6125
6126    public void dispatchInputEvent(InputEvent event) {
6127        dispatchInputEvent(event, null);
6128    }
6129
6130    public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6131        SomeArgs args = SomeArgs.obtain();
6132        args.arg1 = event;
6133        args.arg2 = receiver;
6134        Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
6135        msg.setAsynchronous(true);
6136        mHandler.sendMessage(msg);
6137    }
6138
6139    public void synthesizeInputEvent(InputEvent event) {
6140        Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6141        msg.setAsynchronous(true);
6142        mHandler.sendMessage(msg);
6143    }
6144
6145    public void dispatchKeyFromIme(KeyEvent event) {
6146        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
6147        msg.setAsynchronous(true);
6148        mHandler.sendMessage(msg);
6149    }
6150
6151    /**
6152     * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6153     *
6154     * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6155     * passes in.
6156     */
6157    public void dispatchUnhandledInputEvent(InputEvent event) {
6158        if (event instanceof MotionEvent) {
6159            event = MotionEvent.obtain((MotionEvent) event);
6160        }
6161        synthesizeInputEvent(event);
6162    }
6163
6164    public void dispatchAppVisibility(boolean visible) {
6165        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
6166        msg.arg1 = visible ? 1 : 0;
6167        mHandler.sendMessage(msg);
6168    }
6169
6170    public void dispatchGetNewSurface() {
6171        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6172        mHandler.sendMessage(msg);
6173    }
6174
6175    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6176        Message msg = Message.obtain();
6177        msg.what = MSG_WINDOW_FOCUS_CHANGED;
6178        msg.arg1 = hasFocus ? 1 : 0;
6179        msg.arg2 = inTouchMode ? 1 : 0;
6180        mHandler.sendMessage(msg);
6181    }
6182
6183    public void dispatchWindowShown() {
6184        mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6185    }
6186
6187    public void dispatchCloseSystemDialogs(String reason) {
6188        Message msg = Message.obtain();
6189        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
6190        msg.obj = reason;
6191        mHandler.sendMessage(msg);
6192    }
6193
6194    public void dispatchDragEvent(DragEvent event) {
6195        final int what;
6196        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
6197            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6198            mHandler.removeMessages(what);
6199        } else {
6200            what = MSG_DISPATCH_DRAG_EVENT;
6201        }
6202        Message msg = mHandler.obtainMessage(what, event);
6203        mHandler.sendMessage(msg);
6204    }
6205
6206    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6207            int localValue, int localChanges) {
6208        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6209        args.seq = seq;
6210        args.globalVisibility = globalVisibility;
6211        args.localValue = localValue;
6212        args.localChanges = localChanges;
6213        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6214    }
6215
6216    public void dispatchWindowAnimationStarted(int remainingFrameCount) {
6217        mHandler.obtainMessage(MSG_DISPATCH_WINDOW_ANIMATION_STARTED,
6218                remainingFrameCount, 0 /* unused */).sendToTarget();
6219    }
6220
6221    public void dispatchWindowAnimationStopped() {
6222        mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_ANIMATION_STOPPED);
6223    }
6224
6225    public void dispatchCheckFocus() {
6226        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
6227            // This will result in a call to checkFocus() below.
6228            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
6229        }
6230    }
6231
6232    /**
6233     * Post a callback to send a
6234     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6235     * This event is send at most once every
6236     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
6237     */
6238    private void postSendWindowContentChangedCallback(View source, int changeType) {
6239        if (mSendWindowContentChangedAccessibilityEvent == null) {
6240            mSendWindowContentChangedAccessibilityEvent =
6241                new SendWindowContentChangedAccessibilityEvent();
6242        }
6243        mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
6244    }
6245
6246    /**
6247     * Remove a posted callback to send a
6248     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6249     */
6250    private void removeSendWindowContentChangedCallback() {
6251        if (mSendWindowContentChangedAccessibilityEvent != null) {
6252            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
6253        }
6254    }
6255
6256    @Override
6257    public boolean showContextMenuForChild(View originalView) {
6258        return false;
6259    }
6260
6261    @Override
6262    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6263        return null;
6264    }
6265
6266    @Override
6267    public ActionMode startActionModeForChild(
6268            View originalView, ActionMode.Callback callback, int type) {
6269        return null;
6270    }
6271
6272    @Override
6273    public void createContextMenu(ContextMenu menu) {
6274    }
6275
6276    @Override
6277    public void childDrawableStateChanged(View child) {
6278    }
6279
6280    @Override
6281    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
6282        if (mView == null || mStopped || mPausedForTransition) {
6283            return false;
6284        }
6285        // Intercept accessibility focus events fired by virtual nodes to keep
6286        // track of accessibility focus position in such nodes.
6287        final int eventType = event.getEventType();
6288        switch (eventType) {
6289            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
6290                final long sourceNodeId = event.getSourceNodeId();
6291                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6292                        sourceNodeId);
6293                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6294                if (source != null) {
6295                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6296                    if (provider != null) {
6297                        final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
6298                                sourceNodeId);
6299                        final AccessibilityNodeInfo node;
6300                        if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6301                            node = provider.createAccessibilityNodeInfo(
6302                                    AccessibilityNodeProvider.HOST_VIEW_ID);
6303                        } else {
6304                            node = provider.createAccessibilityNodeInfo(virtualNodeId);
6305                        }
6306                        setAccessibilityFocus(source, node);
6307                    }
6308                }
6309            } break;
6310            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
6311                final long sourceNodeId = event.getSourceNodeId();
6312                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6313                        sourceNodeId);
6314                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6315                if (source != null) {
6316                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6317                    if (provider != null) {
6318                        setAccessibilityFocus(null, null);
6319                    }
6320                }
6321            } break;
6322
6323
6324            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
6325                handleWindowContentChangedEvent(event);
6326            } break;
6327        }
6328        mAccessibilityManager.sendAccessibilityEvent(event);
6329        return true;
6330    }
6331
6332    /**
6333     * Updates the focused virtual view, when necessary, in response to a
6334     * content changed event.
6335     * <p>
6336     * This is necessary to get updated bounds after a position change.
6337     *
6338     * @param event an accessibility event of type
6339     *              {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
6340     */
6341    private void handleWindowContentChangedEvent(AccessibilityEvent event) {
6342        // No virtual view focused, nothing to do here.
6343        if (mAccessibilityFocusedHost == null || mAccessibilityFocusedVirtualView == null) {
6344            return;
6345        }
6346
6347        // If we have a node but no provider, abort.
6348        final AccessibilityNodeProvider provider =
6349                mAccessibilityFocusedHost.getAccessibilityNodeProvider();
6350        if (provider == null) {
6351            // TODO: Should we clear the focused virtual view?
6352            return;
6353        }
6354
6355        // We only care about change types that may affect the bounds of the
6356        // focused virtual view.
6357        final int changes = event.getContentChangeTypes();
6358        if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) == 0
6359                && changes != AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
6360            return;
6361        }
6362
6363        final long eventSourceNodeId = event.getSourceNodeId();
6364        final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId);
6365
6366        // Search up the tree for subtree containment.
6367        boolean hostInSubtree = false;
6368        View root = mAccessibilityFocusedHost;
6369        while (root != null && !hostInSubtree) {
6370            if (changedViewId == root.getAccessibilityViewId()) {
6371                hostInSubtree = true;
6372            } else {
6373                final ViewParent parent = root.getParent();
6374                if (parent instanceof View) {
6375                    root = (View) parent;
6376                } else {
6377                    root = null;
6378                }
6379            }
6380        }
6381
6382        // We care only about changes in subtrees containing the host view.
6383        if (!hostInSubtree) {
6384            return;
6385        }
6386
6387        final long focusedSourceNodeId = mAccessibilityFocusedVirtualView.getSourceNodeId();
6388        int focusedChildId = AccessibilityNodeInfo.getVirtualDescendantId(focusedSourceNodeId);
6389        if (focusedChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6390            // TODO: Should we clear the focused virtual view?
6391            focusedChildId = AccessibilityNodeProvider.HOST_VIEW_ID;
6392        }
6393
6394        // Refresh the node for the focused virtual view.
6395        mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId);
6396    }
6397
6398    @Override
6399    public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6400        postSendWindowContentChangedCallback(source, changeType);
6401    }
6402
6403    @Override
6404    public boolean canResolveLayoutDirection() {
6405        return true;
6406    }
6407
6408    @Override
6409    public boolean isLayoutDirectionResolved() {
6410        return true;
6411    }
6412
6413    @Override
6414    public int getLayoutDirection() {
6415        return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6416    }
6417
6418    @Override
6419    public boolean canResolveTextDirection() {
6420        return true;
6421    }
6422
6423    @Override
6424    public boolean isTextDirectionResolved() {
6425        return true;
6426    }
6427
6428    @Override
6429    public int getTextDirection() {
6430        return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6431    }
6432
6433    @Override
6434    public boolean canResolveTextAlignment() {
6435        return true;
6436    }
6437
6438    @Override
6439    public boolean isTextAlignmentResolved() {
6440        return true;
6441    }
6442
6443    @Override
6444    public int getTextAlignment() {
6445        return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6446    }
6447
6448    private View getCommonPredecessor(View first, View second) {
6449        if (mTempHashSet == null) {
6450            mTempHashSet = new HashSet<View>();
6451        }
6452        HashSet<View> seen = mTempHashSet;
6453        seen.clear();
6454        View firstCurrent = first;
6455        while (firstCurrent != null) {
6456            seen.add(firstCurrent);
6457            ViewParent firstCurrentParent = firstCurrent.mParent;
6458            if (firstCurrentParent instanceof View) {
6459                firstCurrent = (View) firstCurrentParent;
6460            } else {
6461                firstCurrent = null;
6462            }
6463        }
6464        View secondCurrent = second;
6465        while (secondCurrent != null) {
6466            if (seen.contains(secondCurrent)) {
6467                seen.clear();
6468                return secondCurrent;
6469            }
6470            ViewParent secondCurrentParent = secondCurrent.mParent;
6471            if (secondCurrentParent instanceof View) {
6472                secondCurrent = (View) secondCurrentParent;
6473            } else {
6474                secondCurrent = null;
6475            }
6476        }
6477        seen.clear();
6478        return null;
6479    }
6480
6481    void checkThread() {
6482        if (mThread != Thread.currentThread()) {
6483            throw new CalledFromWrongThreadException(
6484                    "Only the original thread that created a view hierarchy can touch its views.");
6485        }
6486    }
6487
6488    @Override
6489    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
6490        // ViewAncestor never intercepts touch event, so this can be a no-op
6491    }
6492
6493    @Override
6494    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
6495        final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
6496        if (rectangle != null) {
6497            mTempRect.set(rectangle);
6498            mTempRect.offset(0, -mCurScrollY);
6499            mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6500            try {
6501                mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6502            } catch (RemoteException re) {
6503                /* ignore */
6504            }
6505        }
6506        return scrolled;
6507    }
6508
6509    @Override
6510    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6511        // Do nothing.
6512    }
6513
6514    @Override
6515    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6516        return false;
6517    }
6518
6519    @Override
6520    public void onStopNestedScroll(View target) {
6521    }
6522
6523    @Override
6524    public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6525    }
6526
6527    @Override
6528    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6529            int dxUnconsumed, int dyUnconsumed) {
6530    }
6531
6532    @Override
6533    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6534    }
6535
6536    @Override
6537    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6538        return false;
6539    }
6540
6541    @Override
6542    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6543        return false;
6544    }
6545
6546    @Override
6547    public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6548        return false;
6549    }
6550
6551    void changeCanvasOpacity(boolean opaque) {
6552        Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque);
6553        if (mAttachInfo.mHardwareRenderer != null) {
6554            mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6555        }
6556    }
6557
6558    class TakenSurfaceHolder extends BaseSurfaceHolder {
6559        @Override
6560        public boolean onAllowLockCanvas() {
6561            return mDrawingAllowed;
6562        }
6563
6564        @Override
6565        public void onRelayoutContainer() {
6566            // Not currently interesting -- from changing between fixed and layout size.
6567        }
6568
6569        @Override
6570        public void setFormat(int format) {
6571            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6572        }
6573
6574        @Override
6575        public void setType(int type) {
6576            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6577        }
6578
6579        @Override
6580        public void onUpdateSurface() {
6581            // We take care of format and type changes on our own.
6582            throw new IllegalStateException("Shouldn't be here");
6583        }
6584
6585        @Override
6586        public boolean isCreating() {
6587            return mIsCreating;
6588        }
6589
6590        @Override
6591        public void setFixedSize(int width, int height) {
6592            throw new UnsupportedOperationException(
6593                    "Currently only support sizing from layout");
6594        }
6595
6596        @Override
6597        public void setKeepScreenOn(boolean screenOn) {
6598            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6599        }
6600    }
6601
6602    static class W extends IWindow.Stub {
6603        private final WeakReference<ViewRootImpl> mViewAncestor;
6604        private final IWindowSession mWindowSession;
6605
6606        W(ViewRootImpl viewAncestor) {
6607            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
6608            mWindowSession = viewAncestor.mWindowSession;
6609        }
6610
6611        @Override
6612        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
6613                Rect visibleInsets, Rect stableInsets, boolean reportDraw,
6614                Configuration newConfig) {
6615            final ViewRootImpl viewAncestor = mViewAncestor.get();
6616            if (viewAncestor != null) {
6617                viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
6618                        visibleInsets, stableInsets, reportDraw, newConfig);
6619            }
6620        }
6621
6622        @Override
6623        public void moved(int newX, int newY) {
6624            final ViewRootImpl viewAncestor = mViewAncestor.get();
6625            if (viewAncestor != null) {
6626                viewAncestor.dispatchMoved(newX, newY);
6627            }
6628        }
6629
6630        @Override
6631        public void dispatchAppVisibility(boolean visible) {
6632            final ViewRootImpl viewAncestor = mViewAncestor.get();
6633            if (viewAncestor != null) {
6634                viewAncestor.dispatchAppVisibility(visible);
6635            }
6636        }
6637
6638        @Override
6639        public void dispatchGetNewSurface() {
6640            final ViewRootImpl viewAncestor = mViewAncestor.get();
6641            if (viewAncestor != null) {
6642                viewAncestor.dispatchGetNewSurface();
6643            }
6644        }
6645
6646        @Override
6647        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6648            final ViewRootImpl viewAncestor = mViewAncestor.get();
6649            if (viewAncestor != null) {
6650                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
6651            }
6652        }
6653
6654        private static int checkCallingPermission(String permission) {
6655            try {
6656                return ActivityManagerNative.getDefault().checkPermission(
6657                        permission, Binder.getCallingPid(), Binder.getCallingUid());
6658            } catch (RemoteException e) {
6659                return PackageManager.PERMISSION_DENIED;
6660            }
6661        }
6662
6663        @Override
6664        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
6665            final ViewRootImpl viewAncestor = mViewAncestor.get();
6666            if (viewAncestor != null) {
6667                final View view = viewAncestor.mView;
6668                if (view != null) {
6669                    if (checkCallingPermission(Manifest.permission.DUMP) !=
6670                            PackageManager.PERMISSION_GRANTED) {
6671                        throw new SecurityException("Insufficient permissions to invoke"
6672                                + " executeCommand() from pid=" + Binder.getCallingPid()
6673                                + ", uid=" + Binder.getCallingUid());
6674                    }
6675
6676                    OutputStream clientStream = null;
6677                    try {
6678                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
6679                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
6680                    } catch (IOException e) {
6681                        e.printStackTrace();
6682                    } finally {
6683                        if (clientStream != null) {
6684                            try {
6685                                clientStream.close();
6686                            } catch (IOException e) {
6687                                e.printStackTrace();
6688                            }
6689                        }
6690                    }
6691                }
6692            }
6693        }
6694
6695        @Override
6696        public void closeSystemDialogs(String reason) {
6697            final ViewRootImpl viewAncestor = mViewAncestor.get();
6698            if (viewAncestor != null) {
6699                viewAncestor.dispatchCloseSystemDialogs(reason);
6700            }
6701        }
6702
6703        @Override
6704        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
6705                boolean sync) {
6706            if (sync) {
6707                try {
6708                    mWindowSession.wallpaperOffsetsComplete(asBinder());
6709                } catch (RemoteException e) {
6710                }
6711            }
6712        }
6713
6714        @Override
6715        public void dispatchWallpaperCommand(String action, int x, int y,
6716                int z, Bundle extras, boolean sync) {
6717            if (sync) {
6718                try {
6719                    mWindowSession.wallpaperCommandComplete(asBinder(), null);
6720                } catch (RemoteException e) {
6721                }
6722            }
6723        }
6724
6725        /* Drag/drop */
6726        @Override
6727        public void dispatchDragEvent(DragEvent event) {
6728            final ViewRootImpl viewAncestor = mViewAncestor.get();
6729            if (viewAncestor != null) {
6730                viewAncestor.dispatchDragEvent(event);
6731            }
6732        }
6733
6734        @Override
6735        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6736                int localValue, int localChanges) {
6737            final ViewRootImpl viewAncestor = mViewAncestor.get();
6738            if (viewAncestor != null) {
6739                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
6740                        localValue, localChanges);
6741            }
6742        }
6743
6744        @Override
6745        public void onAnimationStarted(int remainingFrameCount) {
6746            final ViewRootImpl viewAncestor = mViewAncestor.get();
6747            if (viewAncestor != null) {
6748                viewAncestor.dispatchWindowAnimationStarted(remainingFrameCount);
6749            }
6750        }
6751
6752        @Override
6753        public void onAnimationStopped() {
6754            final ViewRootImpl viewAncestor = mViewAncestor.get();
6755            if (viewAncestor != null) {
6756                viewAncestor.dispatchWindowAnimationStopped();
6757            }
6758        }
6759
6760        @Override
6761        public void dispatchWindowShown() {
6762            final ViewRootImpl viewAncestor = mViewAncestor.get();
6763            if (viewAncestor != null) {
6764                viewAncestor.dispatchWindowShown();
6765            }
6766        }
6767    }
6768
6769    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
6770        public CalledFromWrongThreadException(String msg) {
6771            super(msg);
6772        }
6773    }
6774
6775    static RunQueue getRunQueue() {
6776        RunQueue rq = sRunQueues.get();
6777        if (rq != null) {
6778            return rq;
6779        }
6780        rq = new RunQueue();
6781        sRunQueues.set(rq);
6782        return rq;
6783    }
6784
6785    /**
6786     * The run queue is used to enqueue pending work from Views when no Handler is
6787     * attached.  The work is executed during the next call to performTraversals on
6788     * the thread.
6789     * @hide
6790     */
6791    static final class RunQueue {
6792        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
6793
6794        void post(Runnable action) {
6795            postDelayed(action, 0);
6796        }
6797
6798        void postDelayed(Runnable action, long delayMillis) {
6799            HandlerAction handlerAction = new HandlerAction();
6800            handlerAction.action = action;
6801            handlerAction.delay = delayMillis;
6802
6803            synchronized (mActions) {
6804                mActions.add(handlerAction);
6805            }
6806        }
6807
6808        void removeCallbacks(Runnable action) {
6809            final HandlerAction handlerAction = new HandlerAction();
6810            handlerAction.action = action;
6811
6812            synchronized (mActions) {
6813                final ArrayList<HandlerAction> actions = mActions;
6814
6815                while (actions.remove(handlerAction)) {
6816                    // Keep going
6817                }
6818            }
6819        }
6820
6821        void executeActions(Handler handler) {
6822            synchronized (mActions) {
6823                final ArrayList<HandlerAction> actions = mActions;
6824                final int count = actions.size();
6825
6826                for (int i = 0; i < count; i++) {
6827                    final HandlerAction handlerAction = actions.get(i);
6828                    handler.postDelayed(handlerAction.action, handlerAction.delay);
6829                }
6830
6831                actions.clear();
6832            }
6833        }
6834
6835        private static class HandlerAction {
6836            Runnable action;
6837            long delay;
6838
6839            @Override
6840            public boolean equals(Object o) {
6841                if (this == o) return true;
6842                if (o == null || getClass() != o.getClass()) return false;
6843
6844                HandlerAction that = (HandlerAction) o;
6845                return !(action != null ? !action.equals(that.action) : that.action != null);
6846
6847            }
6848
6849            @Override
6850            public int hashCode() {
6851                int result = action != null ? action.hashCode() : 0;
6852                result = 31 * result + (int) (delay ^ (delay >>> 32));
6853                return result;
6854            }
6855        }
6856    }
6857
6858    /**
6859     * Class for managing the accessibility interaction connection
6860     * based on the global accessibility state.
6861     */
6862    final class AccessibilityInteractionConnectionManager
6863            implements AccessibilityStateChangeListener {
6864        @Override
6865        public void onAccessibilityStateChanged(boolean enabled) {
6866            if (enabled) {
6867                ensureConnection();
6868                if (mAttachInfo.mHasWindowFocus) {
6869                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
6870                    View focusedView = mView.findFocus();
6871                    if (focusedView != null && focusedView != mView) {
6872                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6873                    }
6874                }
6875            } else {
6876                ensureNoConnection();
6877                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
6878            }
6879        }
6880
6881        public void ensureConnection() {
6882            final boolean registered =
6883                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6884            if (!registered) {
6885                mAttachInfo.mAccessibilityWindowId =
6886                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
6887                                new AccessibilityInteractionConnection(ViewRootImpl.this));
6888            }
6889        }
6890
6891        public void ensureNoConnection() {
6892            final boolean registered =
6893                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6894            if (registered) {
6895                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6896                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
6897            }
6898        }
6899    }
6900
6901    final class HighContrastTextManager implements HighTextContrastChangeListener {
6902        HighContrastTextManager() {
6903            mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
6904        }
6905        @Override
6906        public void onHighTextContrastStateChanged(boolean enabled) {
6907            mAttachInfo.mHighContrastText = enabled;
6908
6909            // Destroy Displaylists so they can be recreated with high contrast recordings
6910            destroyHardwareResources();
6911
6912            // Schedule redraw, which will rerecord + redraw all text
6913            invalidate();
6914        }
6915    }
6916
6917    /**
6918     * This class is an interface this ViewAncestor provides to the
6919     * AccessibilityManagerService to the latter can interact with
6920     * the view hierarchy in this ViewAncestor.
6921     */
6922    static final class AccessibilityInteractionConnection
6923            extends IAccessibilityInteractionConnection.Stub {
6924        private final WeakReference<ViewRootImpl> mViewRootImpl;
6925
6926        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
6927            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
6928        }
6929
6930        @Override
6931        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
6932                Region interactiveRegion, int interactionId,
6933                IAccessibilityInteractionConnectionCallback callback, int flags,
6934                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6935            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6936            if (viewRootImpl != null && viewRootImpl.mView != null) {
6937                viewRootImpl.getAccessibilityInteractionController()
6938                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
6939                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
6940                            interrogatingTid, spec);
6941            } else {
6942                // We cannot make the call and notify the caller so it does not wait.
6943                try {
6944                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6945                } catch (RemoteException re) {
6946                    /* best effort - ignore */
6947                }
6948            }
6949        }
6950
6951        @Override
6952        public void performAccessibilityAction(long accessibilityNodeId, int action,
6953                Bundle arguments, int interactionId,
6954                IAccessibilityInteractionConnectionCallback callback, int flags,
6955                int interrogatingPid, long interrogatingTid) {
6956            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6957            if (viewRootImpl != null && viewRootImpl.mView != null) {
6958                viewRootImpl.getAccessibilityInteractionController()
6959                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
6960                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
6961            } else {
6962                // We cannot make the call and notify the caller so it does not wait.
6963                try {
6964                    callback.setPerformAccessibilityActionResult(false, interactionId);
6965                } catch (RemoteException re) {
6966                    /* best effort - ignore */
6967                }
6968            }
6969        }
6970
6971        @Override
6972        public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
6973                String viewId, Region interactiveRegion, int interactionId,
6974                IAccessibilityInteractionConnectionCallback callback, int flags,
6975                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6976            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6977            if (viewRootImpl != null && viewRootImpl.mView != null) {
6978                viewRootImpl.getAccessibilityInteractionController()
6979                    .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
6980                            viewId, interactiveRegion, interactionId, callback, flags,
6981                            interrogatingPid, interrogatingTid, spec);
6982            } else {
6983                // We cannot make the call and notify the caller so it does not wait.
6984                try {
6985                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6986                } catch (RemoteException re) {
6987                    /* best effort - ignore */
6988                }
6989            }
6990        }
6991
6992        @Override
6993        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
6994                Region interactiveRegion, int interactionId,
6995                IAccessibilityInteractionConnectionCallback callback, int flags,
6996                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6997            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6998            if (viewRootImpl != null && viewRootImpl.mView != null) {
6999                viewRootImpl.getAccessibilityInteractionController()
7000                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
7001                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
7002                            interrogatingTid, spec);
7003            } else {
7004                // We cannot make the call and notify the caller so it does not wait.
7005                try {
7006                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
7007                } catch (RemoteException re) {
7008                    /* best effort - ignore */
7009                }
7010            }
7011        }
7012
7013        @Override
7014        public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
7015                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
7016                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7017            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7018            if (viewRootImpl != null && viewRootImpl.mView != null) {
7019                viewRootImpl.getAccessibilityInteractionController()
7020                    .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
7021                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
7022                            spec);
7023            } else {
7024                // We cannot make the call and notify the caller so it does not wait.
7025                try {
7026                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7027                } catch (RemoteException re) {
7028                    /* best effort - ignore */
7029                }
7030            }
7031        }
7032
7033        @Override
7034        public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
7035                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
7036                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7037            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7038            if (viewRootImpl != null && viewRootImpl.mView != null) {
7039                viewRootImpl.getAccessibilityInteractionController()
7040                    .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
7041                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
7042                            spec);
7043            } else {
7044                // We cannot make the call and notify the caller so it does not wait.
7045                try {
7046                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7047                } catch (RemoteException re) {
7048                    /* best effort - ignore */
7049                }
7050            }
7051        }
7052    }
7053
7054    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
7055        private int mChangeTypes = 0;
7056
7057        public View mSource;
7058        public long mLastEventTimeMillis;
7059
7060        @Override
7061        public void run() {
7062            // The accessibility may be turned off while we were waiting so check again.
7063            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7064                mLastEventTimeMillis = SystemClock.uptimeMillis();
7065                AccessibilityEvent event = AccessibilityEvent.obtain();
7066                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
7067                event.setContentChangeTypes(mChangeTypes);
7068                mSource.sendAccessibilityEventUnchecked(event);
7069            } else {
7070                mLastEventTimeMillis = 0;
7071            }
7072            // In any case reset to initial state.
7073            mSource.resetSubtreeAccessibilityStateChanged();
7074            mSource = null;
7075            mChangeTypes = 0;
7076        }
7077
7078        public void runOrPost(View source, int changeType) {
7079            if (mSource != null) {
7080                // If there is no common predecessor, then mSource points to
7081                // a removed view, hence in this case always prefer the source.
7082                View predecessor = getCommonPredecessor(mSource, source);
7083                mSource = (predecessor != null) ? predecessor : source;
7084                mChangeTypes |= changeType;
7085                return;
7086            }
7087            mSource = source;
7088            mChangeTypes = changeType;
7089            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
7090            final long minEventIntevalMillis =
7091                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
7092            if (timeSinceLastMillis >= minEventIntevalMillis) {
7093                mSource.removeCallbacks(this);
7094                run();
7095            } else {
7096                mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
7097            }
7098        }
7099    }
7100}
7101