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