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