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