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