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