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