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