ViewRootImpl.java revision c66ee745dc84699a25be53b8ce7a41c56aa5031d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.Manifest;
20import android.animation.LayoutTransition;
21import android.app.ActivityManagerNative;
22import android.content.ClipDescription;
23import android.content.ComponentCallbacks;
24import android.content.Context;
25import android.content.pm.PackageManager;
26import android.content.res.CompatibilityInfo;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.graphics.Canvas;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PointF;
35import android.graphics.PorterDuff;
36import android.graphics.Rect;
37import android.graphics.Region;
38import android.graphics.drawable.Drawable;
39import android.hardware.display.DisplayManager;
40import android.hardware.display.DisplayManager.DisplayListener;
41import android.media.AudioManager;
42import android.os.Binder;
43import android.os.Build;
44import android.os.Bundle;
45import android.os.Debug;
46import android.os.Handler;
47import android.os.Looper;
48import android.os.Message;
49import android.os.ParcelFileDescriptor;
50import android.os.Process;
51import android.os.RemoteException;
52import android.os.SystemClock;
53import android.os.SystemProperties;
54import android.os.Trace;
55import android.util.AndroidRuntimeException;
56import android.util.DisplayMetrics;
57import android.util.Log;
58import android.util.Slog;
59import android.util.TypedValue;
60import android.view.Surface.OutOfResourcesException;
61import android.view.View.AttachInfo;
62import android.view.View.MeasureSpec;
63import android.view.accessibility.AccessibilityEvent;
64import android.view.accessibility.AccessibilityManager;
65import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
66import android.view.accessibility.AccessibilityManager.HighTextContrastChangeListener;
67import android.view.accessibility.AccessibilityNodeInfo;
68import android.view.accessibility.AccessibilityNodeProvider;
69import android.view.accessibility.IAccessibilityInteractionConnection;
70import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
71import android.view.animation.AccelerateDecelerateInterpolator;
72import android.view.animation.Interpolator;
73import android.view.inputmethod.InputConnection;
74import android.view.inputmethod.InputMethodManager;
75import android.widget.Scroller;
76
77import com.android.internal.R;
78import com.android.internal.os.SomeArgs;
79import com.android.internal.policy.PolicyManager;
80import com.android.internal.view.BaseSurfaceHolder;
81import com.android.internal.view.RootViewSurfaceTaker;
82
83import java.io.FileDescriptor;
84import java.io.IOException;
85import java.io.OutputStream;
86import java.io.PrintWriter;
87import java.lang.ref.WeakReference;
88import java.util.ArrayList;
89import java.util.HashSet;
90
91/**
92 * The top of a view hierarchy, implementing the needed protocol between View
93 * and the WindowManager.  This is for the most part an internal implementation
94 * detail of {@link WindowManagerGlobal}.
95 *
96 * {@hide}
97 */
98@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
99public final class ViewRootImpl implements ViewParent,
100        View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
101    private static final String TAG = "ViewRootImpl";
102    private static final boolean DBG = false;
103    private static final boolean LOCAL_LOGV = false;
104    /** @noinspection PointlessBooleanExpression*/
105    private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
106    private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
107    private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
108    private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
109    private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
110    private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
111    private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
112    private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
113    private static final boolean DEBUG_FPS = false;
114    private static final boolean DEBUG_INPUT_STAGES = false || LOCAL_LOGV;
115
116    /**
117     * Set this system property to true to force the view hierarchy to render
118     * at 60 Hz. This can be used to measure the potential framerate.
119     */
120    private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering";
121    private static final String PROPERTY_MEDIA_DISABLED = "config.disable_media";
122
123    // property used by emulator to determine display shape
124    public static final String PROPERTY_EMULATOR_CIRCULAR = "ro.emulator.circular";
125
126    /**
127     * Maximum time we allow the user to roll the trackball enough to generate
128     * a key event, before resetting the counters.
129     */
130    static final int MAX_TRACKBALL_DELAY = 250;
131
132    static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
133
134    static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
135    static boolean sFirstDrawComplete = false;
136
137    static final ArrayList<ComponentCallbacks> sConfigCallbacks
138            = new ArrayList<ComponentCallbacks>();
139
140    final Context mContext;
141    final IWindowSession mWindowSession;
142    final Display mDisplay;
143    final DisplayManager mDisplayManager;
144    final String mBasePackageName;
145
146    final int[] mTmpLocation = new int[2];
147
148    final TypedValue mTmpValue = new TypedValue();
149
150    final Thread mThread;
151
152    final WindowLeaked mLocation;
153
154    final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
155
156    final W mWindow;
157
158    final int mTargetSdkVersion;
159
160    int mSeq;
161
162    View mView;
163
164    View mAccessibilityFocusedHost;
165    AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
166
167    int mViewVisibility;
168    boolean mAppVisible = true;
169    int mOrigWindowType = -1;
170
171    // Set to true if the owner of this window is in the stopped state,
172    // so the window should no longer be active.
173    boolean mStopped = false;
174
175    boolean mLastInCompatMode = false;
176
177    SurfaceHolder.Callback2 mSurfaceHolderCallback;
178    BaseSurfaceHolder mSurfaceHolder;
179    boolean mIsCreating;
180    boolean mDrawingAllowed;
181
182    final Region mTransparentRegion;
183    final Region mPreviousTransparentRegion;
184
185    int mWidth;
186    int mHeight;
187    Rect mDirty;
188    boolean mIsAnimating;
189
190    CompatibilityInfo.Translator mTranslator;
191
192    final View.AttachInfo mAttachInfo;
193    InputChannel mInputChannel;
194    InputQueue.Callback mInputQueueCallback;
195    InputQueue mInputQueue;
196    FallbackEventHandler mFallbackEventHandler;
197    Choreographer mChoreographer;
198
199    final Rect mTempRect; // used in the transaction to not thrash the heap.
200    final Rect mVisRect; // used to retrieve visible rect of focused view.
201
202    boolean mTraversalScheduled;
203    int mTraversalBarrier;
204    boolean mWillDrawSoon;
205    /** Set to true while in performTraversals for detecting when die(true) is called from internal
206     * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
207    boolean mIsInTraversal;
208    boolean mApplyInsetsRequested;
209    boolean mLayoutRequested;
210    boolean mFirst;
211    boolean mReportNextDraw;
212    boolean mFullRedrawNeeded;
213    boolean mNewSurfaceNeeded;
214    boolean mHasHadWindowFocus;
215    boolean mLastWasImTarget;
216    boolean mWindowsAnimating;
217    boolean mDrawDuringWindowsAnimating;
218    boolean mIsDrawing;
219    int mLastSystemUiVisibility;
220    int mClientWindowLayoutFlags;
221    boolean mLastOverscanRequested;
222
223    // Pool of queued input events.
224    private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
225    private QueuedInputEvent mQueuedInputEventPool;
226    private int mQueuedInputEventPoolSize;
227
228    /* Input event queue.
229     * Pending input events are input events waiting to be delivered to the input stages
230     * and handled by the application.
231     */
232    QueuedInputEvent mPendingInputEventHead;
233    QueuedInputEvent mPendingInputEventTail;
234    int mPendingInputEventCount;
235    boolean mProcessInputEventsScheduled;
236    boolean mUnbufferedInputDispatch;
237    String mPendingInputEventQueueLengthCounterName = "pq";
238
239    InputStage mFirstInputStage;
240    InputStage mFirstPostImeInputStage;
241    InputStage mSyntheticInputStage;
242
243    boolean mWindowAttributesChanged = false;
244    int mWindowAttributesChangesFlag = 0;
245
246    // These can be accessed by any thread, must be protected with a lock.
247    // Surface can never be reassigned or cleared (use Surface.clear()).
248    final Surface mSurface = new Surface();
249
250    boolean mAdded;
251    boolean mAddedTouchMode;
252
253    final DisplayAdjustments mDisplayAdjustments;
254
255    // These are accessed by multiple threads.
256    final Rect mWinFrame; // frame given by window manager.
257
258    final Rect mPendingOverscanInsets = new Rect();
259    final Rect mPendingVisibleInsets = new Rect();
260    final Rect mPendingStableInsets = new Rect();
261    final Rect mPendingContentInsets = new Rect();
262    final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
263            = new ViewTreeObserver.InternalInsetsInfo();
264
265    final Rect mDispatchContentInsets = new Rect();
266    final Rect mDispatchStableInsets = new Rect();
267
268    final Configuration mLastConfiguration = new Configuration();
269    final Configuration mPendingConfiguration = new Configuration();
270
271    boolean mScrollMayChange;
272    int mSoftInputMode;
273    WeakReference<View> mLastScrolledFocus;
274    int mScrollY;
275    int mCurScrollY;
276    Scroller mScroller;
277    HardwareLayer mResizeBuffer;
278    long mResizeBufferStartTime;
279    int mResizeBufferDuration;
280    // Used to block the creation of the ResizeBuffer due to invalidations in
281    // the previous DisplayList tree that must prevent re-execution.
282    // Currently this means a functor was detached.
283    boolean mBlockResizeBuffer;
284    static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
285    private ArrayList<LayoutTransition> mPendingTransitions;
286
287    final ViewConfiguration mViewConfiguration;
288
289    /* Drag/drop */
290    ClipDescription mDragDescription;
291    View mCurrentDragView;
292    volatile Object mLocalDragState;
293    final PointF mDragPoint = new PointF();
294    final PointF mLastTouchPoint = new PointF();
295
296    private boolean mProfileRendering;
297    private Choreographer.FrameCallback mRenderProfiler;
298    private boolean mRenderProfilingEnabled;
299
300    private boolean mMediaDisabled;
301
302    // Variables to track frames per second, enabled via DEBUG_FPS flag
303    private long mFpsStartTime = -1;
304    private long mFpsPrevTime = -1;
305    private int mFpsNumFrames;
306
307    /**
308     * see {@link #playSoundEffect(int)}
309     */
310    AudioManager mAudioManager;
311
312    final AccessibilityManager mAccessibilityManager;
313
314    AccessibilityInteractionController mAccessibilityInteractionController;
315
316    AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
317    HighContrastTextManager mHighContrastTextManager;
318
319    SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
320
321    HashSet<View> mTempHashSet;
322
323    private final int mDensity;
324    private final int mNoncompatDensity;
325
326    private boolean mInLayout = false;
327    ArrayList<View> mLayoutRequesters = new ArrayList<View>();
328    boolean mHandlingLayoutInLayoutRequest = false;
329
330    private int mViewLayoutDirectionInitial;
331
332    /** Set to true once doDie() has been called. */
333    private boolean mRemoved;
334
335    private boolean mIsEmulator;
336    private boolean mIsCircularEmulator;
337    private final boolean mWindowIsRound;
338
339    /**
340     * Consistency verifier for debugging purposes.
341     */
342    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
343            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
344                    new InputEventConsistencyVerifier(this, 0) : null;
345
346    static final class SystemUiVisibilityInfo {
347        int seq;
348        int globalVisibility;
349        int localValue;
350        int localChanges;
351    }
352
353    public ViewRootImpl(Context context, Display display) {
354        mContext = context;
355        mWindowSession = WindowManagerGlobal.getWindowSession();
356        mDisplay = display;
357        mBasePackageName = context.getBasePackageName();
358
359        mDisplayAdjustments = display.getDisplayAdjustments();
360
361        mThread = Thread.currentThread();
362        mLocation = new WindowLeaked(null);
363        mLocation.fillInStackTrace();
364        mWidth = -1;
365        mHeight = -1;
366        mDirty = new Rect();
367        mTempRect = new Rect();
368        mVisRect = new Rect();
369        mWinFrame = new Rect();
370        mWindow = new W(this);
371        mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
372        mViewVisibility = View.GONE;
373        mTransparentRegion = new Region();
374        mPreviousTransparentRegion = new Region();
375        mFirst = true; // true for the first time the view is added
376        mAdded = false;
377        mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
378        mAccessibilityManager = AccessibilityManager.getInstance(context);
379        mAccessibilityInteractionConnectionManager =
380            new AccessibilityInteractionConnectionManager();
381        mAccessibilityManager.addAccessibilityStateChangeListener(
382                mAccessibilityInteractionConnectionManager);
383        mHighContrastTextManager = new HighContrastTextManager();
384        mAccessibilityManager.addHighTextContrastStateChangeListener(
385                mHighContrastTextManager);
386        mViewConfiguration = ViewConfiguration.get(context);
387        mDensity = context.getResources().getDisplayMetrics().densityDpi;
388        mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
389        mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
390        mChoreographer = Choreographer.getInstance();
391        mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
392        loadSystemProperties();
393        mWindowIsRound = context.getResources().getBoolean(
394                com.android.internal.R.bool.config_windowIsRound);
395    }
396
397    public static void addFirstDrawHandler(Runnable callback) {
398        synchronized (sFirstDrawHandlers) {
399            if (!sFirstDrawComplete) {
400                sFirstDrawHandlers.add(callback);
401            }
402        }
403    }
404
405    public static void addConfigCallback(ComponentCallbacks callback) {
406        synchronized (sConfigCallbacks) {
407            sConfigCallbacks.add(callback);
408        }
409    }
410
411    // FIXME for perf testing only
412    private boolean mProfile = false;
413
414    /**
415     * Call this to profile the next traversal call.
416     * FIXME for perf testing only. Remove eventually
417     */
418    public void profile() {
419        mProfile = true;
420    }
421
422    /**
423     * Indicates whether we are in touch mode. Calling this method triggers an IPC
424     * call and should be avoided whenever possible.
425     *
426     * @return True, if the device is in touch mode, false otherwise.
427     *
428     * @hide
429     */
430    static boolean isInTouchMode() {
431        IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
432        if (windowSession != null) {
433            try {
434                return windowSession.getInTouchMode();
435            } catch (RemoteException e) {
436            }
437        }
438        return false;
439    }
440
441    /**
442     * We have one child
443     */
444    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
445        synchronized (this) {
446            if (mView == null) {
447                mView = view;
448
449                mAttachInfo.mDisplayState = mDisplay.getState();
450                mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);
451
452                mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
453                mFallbackEventHandler.setView(view);
454                mWindowAttributes.copyFrom(attrs);
455                if (mWindowAttributes.packageName == null) {
456                    mWindowAttributes.packageName = mBasePackageName;
457                }
458                attrs = mWindowAttributes;
459                // Keep track of the actual window flags supplied by the client.
460                mClientWindowLayoutFlags = attrs.flags;
461
462                setAccessibilityFocus(null, null);
463
464                if (view instanceof RootViewSurfaceTaker) {
465                    mSurfaceHolderCallback =
466                            ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
467                    if (mSurfaceHolderCallback != null) {
468                        mSurfaceHolder = new TakenSurfaceHolder();
469                        mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
470                    }
471                }
472
473                // Compute surface insets required to draw at specified Z value.
474                // TODO: Use real shadow insets for a constant max Z.
475                if (!attrs.hasManualSurfaceInsets) {
476                    final int surfaceInset = (int) Math.ceil(view.getZ() * 2);
477                    attrs.surfaceInsets.set(surfaceInset, surfaceInset, surfaceInset, surfaceInset);
478                }
479
480                CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
481                mTranslator = compatibilityInfo.getTranslator();
482                mDisplayAdjustments.setActivityToken(attrs.token);
483
484                // If the application owns the surface, don't enable hardware acceleration
485                if (mSurfaceHolder == null) {
486                    enableHardwareAcceleration(attrs);
487                }
488
489                boolean restore = false;
490                if (mTranslator != null) {
491                    mSurface.setCompatibilityTranslator(mTranslator);
492                    restore = true;
493                    attrs.backup();
494                    mTranslator.translateWindowLayout(attrs);
495                }
496                if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
497
498                if (!compatibilityInfo.supportsScreen()) {
499                    attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
500                    mLastInCompatMode = true;
501                }
502
503                mSoftInputMode = attrs.softInputMode;
504                mWindowAttributesChanged = true;
505                mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
506                mAttachInfo.mRootView = view;
507                mAttachInfo.mScalingRequired = mTranslator != null;
508                mAttachInfo.mApplicationScale =
509                        mTranslator == null ? 1.0f : mTranslator.applicationScale;
510                if (panelParentView != null) {
511                    mAttachInfo.mPanelParentWindowToken
512                            = panelParentView.getApplicationWindowToken();
513                }
514                mAdded = true;
515                int res; /* = WindowManagerImpl.ADD_OKAY; */
516
517                // Schedule the first layout -before- adding to the window
518                // manager, to make sure we do the relayout before receiving
519                // any other events from the system.
520                requestLayout();
521                if ((mWindowAttributes.inputFeatures
522                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
523                    mInputChannel = new InputChannel();
524                }
525                try {
526                    mOrigWindowType = mWindowAttributes.type;
527                    mAttachInfo.mRecomputeGlobalAttributes = true;
528                    collectViewAttributes();
529                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
530                            getHostVisibility(), mDisplay.getDisplayId(),
531                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mInputChannel);
532                } catch (RemoteException e) {
533                    mAdded = false;
534                    mView = null;
535                    mAttachInfo.mRootView = null;
536                    mInputChannel = null;
537                    mFallbackEventHandler.setView(null);
538                    unscheduleTraversals();
539                    setAccessibilityFocus(null, null);
540                    throw new RuntimeException("Adding window failed", e);
541                } finally {
542                    if (restore) {
543                        attrs.restore();
544                    }
545                }
546
547                if (mTranslator != null) {
548                    mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
549                }
550                mPendingOverscanInsets.set(0, 0, 0, 0);
551                mPendingContentInsets.set(mAttachInfo.mContentInsets);
552                mPendingStableInsets.set(mAttachInfo.mStableInsets);
553                mPendingVisibleInsets.set(0, 0, 0, 0);
554                if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
555                if (res < WindowManagerGlobal.ADD_OKAY) {
556                    mAttachInfo.mRootView = null;
557                    mAdded = false;
558                    mFallbackEventHandler.setView(null);
559                    unscheduleTraversals();
560                    setAccessibilityFocus(null, null);
561                    switch (res) {
562                        case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
563                        case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
564                            throw new WindowManager.BadTokenException(
565                                    "Unable to add window -- token " + attrs.token
566                                    + " is not valid; is your activity running?");
567                        case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
568                            throw new WindowManager.BadTokenException(
569                                    "Unable to add window -- token " + attrs.token
570                                    + " is not for an application");
571                        case WindowManagerGlobal.ADD_APP_EXITING:
572                            throw new WindowManager.BadTokenException(
573                                    "Unable to add window -- app for token " + attrs.token
574                                    + " is exiting");
575                        case WindowManagerGlobal.ADD_DUPLICATE_ADD:
576                            throw new WindowManager.BadTokenException(
577                                    "Unable to add window -- window " + mWindow
578                                    + " has already been added");
579                        case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
580                            // Silently ignore -- we would have just removed it
581                            // right away, anyway.
582                            return;
583                        case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
584                            throw new WindowManager.BadTokenException(
585                                    "Unable to add window " + mWindow +
586                                    " -- another window of this type already exists");
587                        case WindowManagerGlobal.ADD_PERMISSION_DENIED:
588                            throw new WindowManager.BadTokenException(
589                                    "Unable to add window " + mWindow +
590                                    " -- permission denied for this window type");
591                        case WindowManagerGlobal.ADD_INVALID_DISPLAY:
592                            throw new WindowManager.InvalidDisplayException(
593                                    "Unable to add window " + mWindow +
594                                    " -- the specified display can not be found");
595                        case WindowManagerGlobal.ADD_INVALID_TYPE:
596                            throw new WindowManager.InvalidDisplayException(
597                                    "Unable to add window " + mWindow
598                                    + " -- the specified window type is not valid");
599                    }
600                    throw new RuntimeException(
601                            "Unable to add window -- unknown error code " + res);
602                }
603
604                if (view instanceof RootViewSurfaceTaker) {
605                    mInputQueueCallback =
606                        ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
607                }
608                if (mInputChannel != null) {
609                    if (mInputQueueCallback != null) {
610                        mInputQueue = new InputQueue();
611                        mInputQueueCallback.onInputQueueCreated(mInputQueue);
612                    }
613                    mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
614                            Looper.myLooper());
615                }
616
617                view.assignParent(this);
618                mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
619                mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
620
621                if (mAccessibilityManager.isEnabled()) {
622                    mAccessibilityInteractionConnectionManager.ensureConnection();
623                }
624
625                if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
626                    view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
627                }
628
629                // Set up the input pipeline.
630                CharSequence counterSuffix = attrs.getTitle();
631                mSyntheticInputStage = new SyntheticInputStage();
632                InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
633                InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
634                        "aq:native-post-ime:" + counterSuffix);
635                InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
636                InputStage imeStage = new ImeInputStage(earlyPostImeStage,
637                        "aq:ime:" + counterSuffix);
638                InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
639                InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
640                        "aq:native-pre-ime:" + counterSuffix);
641
642                mFirstInputStage = nativePreImeStage;
643                mFirstPostImeInputStage = earlyPostImeStage;
644                mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
645            }
646        }
647    }
648
649    /** Whether the window is in local focus mode or not */
650    private boolean isInLocalFocusMode() {
651        return (mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE) != 0;
652    }
653
654    public CharSequence getTitle() {
655        return mWindowAttributes.getTitle();
656    }
657
658    void destroyHardwareResources() {
659        if (mAttachInfo.mHardwareRenderer != null) {
660            mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
661            mAttachInfo.mHardwareRenderer.destroy();
662        }
663    }
664
665    public void detachFunctor(long functor) {
666        // TODO: Make the resize buffer some other way to not need this block
667        mBlockResizeBuffer = true;
668        if (mAttachInfo.mHardwareRenderer != null) {
669            // Fence so that any pending invokeFunctor() messages will be processed
670            // before we return from detachFunctor.
671            mAttachInfo.mHardwareRenderer.stopDrawing();
672        }
673    }
674
675    /**
676     * Schedules the functor for execution in either kModeProcess or
677     * kModeProcessNoContext, depending on whether or not there is an EGLContext.
678     *
679     * @param functor The native functor to invoke
680     * @param waitForCompletion If true, this will not return until the functor
681     *                          has invoked. If false, the functor may be invoked
682     *                          asynchronously.
683     */
684    public void invokeFunctor(long functor, boolean waitForCompletion) {
685        ThreadedRenderer.invokeFunctor(functor, waitForCompletion);
686    }
687
688    public void registerAnimatingRenderNode(RenderNode animator) {
689        if (mAttachInfo.mHardwareRenderer != null) {
690            mAttachInfo.mHardwareRenderer.registerAnimatingRenderNode(animator);
691        } else {
692            if (mAttachInfo.mPendingAnimatingRenderNodes == null) {
693                mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>();
694            }
695            mAttachInfo.mPendingAnimatingRenderNodes.add(animator);
696        }
697    }
698
699    private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
700        mAttachInfo.mHardwareAccelerated = false;
701        mAttachInfo.mHardwareAccelerationRequested = false;
702
703        // Don't enable hardware acceleration when the application is in compatibility mode
704        if (mTranslator != null) return;
705
706        // Try to enable hardware acceleration if requested
707        final boolean hardwareAccelerated =
708                (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
709
710        if (hardwareAccelerated) {
711            if (!HardwareRenderer.isAvailable()) {
712                return;
713            }
714
715            // Persistent processes (including the system) should not do
716            // accelerated rendering on low-end devices.  In that case,
717            // sRendererDisabled will be set.  In addition, the system process
718            // itself should never do accelerated rendering.  In that case, both
719            // sRendererDisabled and sSystemRendererDisabled are set.  When
720            // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
721            // can be used by code on the system process to escape that and enable
722            // HW accelerated drawing.  (This is basically for the lock screen.)
723
724            final boolean fakeHwAccelerated = (attrs.privateFlags &
725                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
726            final boolean forceHwAccelerated = (attrs.privateFlags &
727                    WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
728
729            if (fakeHwAccelerated) {
730                // This is exclusively for the preview windows the window manager
731                // shows for launching applications, so they will look more like
732                // the app being launched.
733                mAttachInfo.mHardwareAccelerationRequested = true;
734            } else if (!HardwareRenderer.sRendererDisabled
735                    || (HardwareRenderer.sSystemRendererDisabled && forceHwAccelerated)) {
736                if (mAttachInfo.mHardwareRenderer != null) {
737                    mAttachInfo.mHardwareRenderer.destroy();
738                }
739
740                final Rect insets = attrs.surfaceInsets;
741                final boolean hasSurfaceInsets = insets.left != 0 || insets.right != 0
742                        || insets.top != 0 || insets.bottom != 0;
743                final boolean translucent = attrs.format != PixelFormat.OPAQUE || hasSurfaceInsets;
744                mAttachInfo.mHardwareRenderer = HardwareRenderer.create(mContext, translucent);
745                if (mAttachInfo.mHardwareRenderer != null) {
746                    mAttachInfo.mHardwareRenderer.setName(attrs.getTitle().toString());
747                    mAttachInfo.mHardwareAccelerated =
748                            mAttachInfo.mHardwareAccelerationRequested = true;
749                }
750            }
751        }
752    }
753
754    public View getView() {
755        return mView;
756    }
757
758    final WindowLeaked getLocation() {
759        return mLocation;
760    }
761
762    void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
763        synchronized (this) {
764            final int oldInsetLeft = mWindowAttributes.surfaceInsets.left;
765            final int oldInsetTop = mWindowAttributes.surfaceInsets.top;
766            final int oldInsetRight = mWindowAttributes.surfaceInsets.right;
767            final int oldInsetBottom = mWindowAttributes.surfaceInsets.bottom;
768            final int oldSoftInputMode = mWindowAttributes.softInputMode;
769            final boolean oldHasManualSurfaceInsets = mWindowAttributes.hasManualSurfaceInsets;
770
771            // Keep track of the actual window flags supplied by the client.
772            mClientWindowLayoutFlags = attrs.flags;
773
774            // Preserve compatible window flag if exists.
775            final int compatibleWindowFlag = mWindowAttributes.privateFlags
776                    & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
777
778            // Transfer over system UI visibility values as they carry current state.
779            attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
780            attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
781
782            mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
783            if ((mWindowAttributesChangesFlag
784                    & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) {
785                // Recompute system ui visibility.
786                mAttachInfo.mRecomputeGlobalAttributes = true;
787            }
788            if (mWindowAttributes.packageName == null) {
789                mWindowAttributes.packageName = mBasePackageName;
790            }
791            mWindowAttributes.privateFlags |= compatibleWindowFlag;
792
793            // Restore old surface insets.
794            mWindowAttributes.surfaceInsets.set(
795                    oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
796            mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
797
798            applyKeepScreenOnFlag(mWindowAttributes);
799
800            if (newView) {
801                mSoftInputMode = attrs.softInputMode;
802                requestLayout();
803            }
804
805            // Don't lose the mode we last auto-computed.
806            if ((attrs.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
807                    == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
808                mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
809                        & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
810                        | (oldSoftInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
811            }
812
813            mWindowAttributesChanged = true;
814            scheduleTraversals();
815        }
816    }
817
818    void handleAppVisibility(boolean visible) {
819        if (mAppVisible != visible) {
820            mAppVisible = visible;
821            scheduleTraversals();
822            if (!mAppVisible) {
823                WindowManagerGlobal.trimForeground();
824            }
825        }
826    }
827
828    void handleGetNewSurface() {
829        mNewSurfaceNeeded = true;
830        mFullRedrawNeeded = true;
831        scheduleTraversals();
832    }
833
834    private final DisplayListener mDisplayListener = new DisplayListener() {
835        @Override
836        public void onDisplayChanged(int displayId) {
837            if (mView != null && mDisplay.getDisplayId() == displayId) {
838                final int oldDisplayState = mAttachInfo.mDisplayState;
839                final int newDisplayState = mDisplay.getState();
840                if (oldDisplayState != newDisplayState) {
841                    mAttachInfo.mDisplayState = newDisplayState;
842                    if (oldDisplayState != Display.STATE_UNKNOWN) {
843                        final int oldScreenState = toViewScreenState(oldDisplayState);
844                        final int newScreenState = toViewScreenState(newDisplayState);
845                        if (oldScreenState != newScreenState) {
846                            mView.dispatchScreenStateChanged(newScreenState);
847                        }
848                        if (oldDisplayState == Display.STATE_OFF) {
849                            // Draw was suppressed so we need to for it to happen here.
850                            mFullRedrawNeeded = true;
851                            scheduleTraversals();
852                        }
853                    }
854                }
855            }
856        }
857
858        @Override
859        public void onDisplayRemoved(int displayId) {
860        }
861
862        @Override
863        public void onDisplayAdded(int displayId) {
864        }
865
866        private int toViewScreenState(int displayState) {
867            return displayState == Display.STATE_OFF ?
868                    View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON;
869        }
870    };
871
872    @Override
873    public void requestFitSystemWindows() {
874        checkThread();
875        mApplyInsetsRequested = true;
876        scheduleTraversals();
877    }
878
879    @Override
880    public void requestLayout() {
881        if (!mHandlingLayoutInLayoutRequest) {
882            checkThread();
883            mLayoutRequested = true;
884            scheduleTraversals();
885        }
886    }
887
888    @Override
889    public boolean isLayoutRequested() {
890        return mLayoutRequested;
891    }
892
893    void invalidate() {
894        mDirty.set(0, 0, mWidth, mHeight);
895        if (!mWillDrawSoon) {
896            scheduleTraversals();
897        }
898    }
899
900    void invalidateWorld(View view) {
901        view.invalidate();
902        if (view instanceof ViewGroup) {
903            ViewGroup parent = (ViewGroup) view;
904            for (int i = 0; i < parent.getChildCount(); i++) {
905                invalidateWorld(parent.getChildAt(i));
906            }
907        }
908    }
909
910    @Override
911    public void invalidateChild(View child, Rect dirty) {
912        invalidateChildInParent(null, dirty);
913    }
914
915    @Override
916    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
917        checkThread();
918        if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
919
920        if (dirty == null) {
921            invalidate();
922            return null;
923        } else if (dirty.isEmpty() && !mIsAnimating) {
924            return null;
925        }
926
927        if (mCurScrollY != 0 || mTranslator != null) {
928            mTempRect.set(dirty);
929            dirty = mTempRect;
930            if (mCurScrollY != 0) {
931                dirty.offset(0, -mCurScrollY);
932            }
933            if (mTranslator != null) {
934                mTranslator.translateRectInAppWindowToScreen(dirty);
935            }
936            if (mAttachInfo.mScalingRequired) {
937                dirty.inset(-1, -1);
938            }
939        }
940
941        final Rect localDirty = mDirty;
942        if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
943            mAttachInfo.mSetIgnoreDirtyState = true;
944            mAttachInfo.mIgnoreDirtyState = true;
945        }
946
947        // Add the new dirty rect to the current one
948        localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
949        // Intersect with the bounds of the window to skip
950        // updates that lie outside of the visible region
951        final float appScale = mAttachInfo.mApplicationScale;
952        final boolean intersected = localDirty.intersect(0, 0,
953                (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
954        if (!intersected) {
955            localDirty.setEmpty();
956        }
957        if (!mWillDrawSoon && (intersected || mIsAnimating)) {
958            scheduleTraversals();
959        }
960
961        return null;
962    }
963
964    void setStopped(boolean stopped) {
965        if (mStopped != stopped) {
966            mStopped = stopped;
967            if (!stopped) {
968                scheduleTraversals();
969            }
970        }
971    }
972
973    @Override
974    public ViewParent getParent() {
975        return null;
976    }
977
978    @Override
979    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
980        if (child != mView) {
981            throw new RuntimeException("child is not mine, honest!");
982        }
983        // Note: don't apply scroll offset, because we want to know its
984        // visibility in the virtual canvas being given to the view hierarchy.
985        return r.intersect(0, 0, mWidth, mHeight);
986    }
987
988    @Override
989    public void bringChildToFront(View child) {
990    }
991
992    int getHostVisibility() {
993        return mAppVisible ? mView.getVisibility() : View.GONE;
994    }
995
996    void disposeResizeBuffer() {
997        if (mResizeBuffer != null) {
998            mResizeBuffer.destroy();
999            mResizeBuffer = null;
1000        }
1001    }
1002
1003    /**
1004     * Add LayoutTransition to the list of transitions to be started in the next traversal.
1005     * This list will be cleared after the transitions on the list are start()'ed. These
1006     * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
1007     * happens during the layout phase of traversal, which we want to complete before any of the
1008     * animations are started (because those animations may side-effect properties that layout
1009     * depends upon, like the bounding rectangles of the affected views). So we add the transition
1010     * to the list and it is started just prior to starting the drawing phase of traversal.
1011     *
1012     * @param transition The LayoutTransition to be started on the next traversal.
1013     *
1014     * @hide
1015     */
1016    public void requestTransitionStart(LayoutTransition transition) {
1017        if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
1018            if (mPendingTransitions == null) {
1019                 mPendingTransitions = new ArrayList<LayoutTransition>();
1020            }
1021            mPendingTransitions.add(transition);
1022        }
1023    }
1024
1025    /**
1026     * Notifies the HardwareRenderer that a new frame will be coming soon.
1027     * Currently only {@link ThreadedRenderer} cares about this, and uses
1028     * this knowledge to adjust the scheduling of off-thread animations
1029     */
1030    void notifyRendererOfFramePending() {
1031        if (mAttachInfo.mHardwareRenderer != null) {
1032            mAttachInfo.mHardwareRenderer.notifyFramePending();
1033        }
1034    }
1035
1036    void scheduleTraversals() {
1037        if (!mTraversalScheduled) {
1038            mTraversalScheduled = true;
1039            mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
1040            mChoreographer.postCallback(
1041                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1042            if (!mUnbufferedInputDispatch) {
1043                scheduleConsumeBatchedInput();
1044            }
1045            notifyRendererOfFramePending();
1046        }
1047    }
1048
1049    void unscheduleTraversals() {
1050        if (mTraversalScheduled) {
1051            mTraversalScheduled = false;
1052            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
1053            mChoreographer.removeCallbacks(
1054                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1055        }
1056    }
1057
1058    void doTraversal() {
1059        if (mTraversalScheduled) {
1060            mTraversalScheduled = false;
1061            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
1062
1063            if (mProfile) {
1064                Debug.startMethodTracing("ViewAncestor");
1065            }
1066
1067            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
1068            try {
1069                performTraversals();
1070            } finally {
1071                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1072            }
1073
1074            if (mProfile) {
1075                Debug.stopMethodTracing();
1076                mProfile = false;
1077            }
1078        }
1079    }
1080
1081    private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1082        // Update window's global keep screen on flag: if a view has requested
1083        // that the screen be kept on, then it is always set; otherwise, it is
1084        // set to whatever the client last requested for the global state.
1085        if (mAttachInfo.mKeepScreenOn) {
1086            params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1087        } else {
1088            params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1089                    | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1090        }
1091    }
1092
1093    private boolean collectViewAttributes() {
1094        if (mAttachInfo.mRecomputeGlobalAttributes) {
1095            //Log.i(TAG, "Computing view hierarchy attributes!");
1096            mAttachInfo.mRecomputeGlobalAttributes = false;
1097            boolean oldScreenOn = mAttachInfo.mKeepScreenOn;
1098            mAttachInfo.mKeepScreenOn = false;
1099            mAttachInfo.mSystemUiVisibility = 0;
1100            mAttachInfo.mHasSystemUiListeners = false;
1101            mView.dispatchCollectViewAttributes(mAttachInfo, 0);
1102            mAttachInfo.mSystemUiVisibility &= ~mAttachInfo.mDisabledSystemUiVisibility;
1103            WindowManager.LayoutParams params = mWindowAttributes;
1104            mAttachInfo.mSystemUiVisibility |= getImpliedSystemUiVisibility(params);
1105            if (mAttachInfo.mKeepScreenOn != oldScreenOn
1106                    || mAttachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1107                    || mAttachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
1108                applyKeepScreenOnFlag(params);
1109                params.subtreeSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1110                params.hasSystemUiListeners = mAttachInfo.mHasSystemUiListeners;
1111                mView.dispatchWindowSystemUiVisiblityChanged(mAttachInfo.mSystemUiVisibility);
1112                return true;
1113            }
1114        }
1115        return false;
1116    }
1117
1118    private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
1119        int vis = 0;
1120        // Translucent decor window flags imply stable system ui visibility.
1121        if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
1122            vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
1123        }
1124        if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) {
1125            vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
1126        }
1127        return vis;
1128    }
1129
1130    private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1131            final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1132        int childWidthMeasureSpec;
1133        int childHeightMeasureSpec;
1134        boolean windowSizeMayChange = false;
1135
1136        if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
1137                "Measuring " + host + " in display " + desiredWindowWidth
1138                + "x" + desiredWindowHeight + "...");
1139
1140        boolean goodMeasure = false;
1141        if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1142            // On large screens, we don't want to allow dialogs to just
1143            // stretch to fill the entire width of the screen to display
1144            // one line of text.  First try doing the layout at a smaller
1145            // size to see if it will fit.
1146            final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1147            res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1148            int baseSize = 0;
1149            if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1150                baseSize = (int)mTmpValue.getDimension(packageMetrics);
1151            }
1152            if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
1153            if (baseSize != 0 && desiredWindowWidth > baseSize) {
1154                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1155                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1156                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1157                if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1158                        + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1159                if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1160                    goodMeasure = true;
1161                } else {
1162                    // Didn't fit in that size... try expanding a bit.
1163                    baseSize = (baseSize+desiredWindowWidth)/2;
1164                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
1165                            + baseSize);
1166                    childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1167                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1168                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1169                            + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1170                    if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1171                        if (DEBUG_DIALOG) Log.v(TAG, "Good!");
1172                        goodMeasure = true;
1173                    }
1174                }
1175            }
1176        }
1177
1178        if (!goodMeasure) {
1179            childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1180            childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1181            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1182            if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1183                windowSizeMayChange = true;
1184            }
1185        }
1186
1187        if (DBG) {
1188            System.out.println("======================================");
1189            System.out.println("performTraversals -- after measure");
1190            host.debug();
1191        }
1192
1193        return windowSizeMayChange;
1194    }
1195
1196    /**
1197     * Modifies the input matrix such that it maps view-local coordinates to
1198     * on-screen coordinates.
1199     *
1200     * @param m input matrix to modify
1201     */
1202    void transformMatrixToGlobal(Matrix m) {
1203        m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
1204    }
1205
1206    /**
1207     * Modifies the input matrix such that it maps on-screen coordinates to
1208     * view-local coordinates.
1209     *
1210     * @param m input matrix to modify
1211     */
1212    void transformMatrixToLocal(Matrix m) {
1213        m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
1214    }
1215
1216    void dispatchApplyInsets(View host) {
1217        mDispatchContentInsets.set(mAttachInfo.mContentInsets);
1218        mDispatchStableInsets.set(mAttachInfo.mStableInsets);
1219        final boolean isRound = (mIsEmulator && mIsCircularEmulator) || mWindowIsRound;
1220        host.dispatchApplyWindowInsets(new WindowInsets(
1221                mDispatchContentInsets, null /* windowDecorInsets */,
1222                mDispatchStableInsets, isRound));
1223    }
1224
1225    private void performTraversals() {
1226        // cache mView since it is used so much below...
1227        final View host = mView;
1228
1229        if (DBG) {
1230            System.out.println("======================================");
1231            System.out.println("performTraversals");
1232            host.debug();
1233        }
1234
1235        if (host == null || !mAdded)
1236            return;
1237
1238        mIsInTraversal = true;
1239        mWillDrawSoon = true;
1240        boolean windowSizeMayChange = false;
1241        boolean newSurface = false;
1242        boolean surfaceChanged = false;
1243        WindowManager.LayoutParams lp = mWindowAttributes;
1244
1245        int desiredWindowWidth;
1246        int desiredWindowHeight;
1247
1248        final int viewVisibility = getHostVisibility();
1249        boolean viewVisibilityChanged = mViewVisibility != viewVisibility
1250                || mNewSurfaceNeeded;
1251
1252        WindowManager.LayoutParams params = null;
1253        if (mWindowAttributesChanged) {
1254            mWindowAttributesChanged = false;
1255            surfaceChanged = true;
1256            params = lp;
1257        }
1258        CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
1259        if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1260            params = lp;
1261            mFullRedrawNeeded = true;
1262            mLayoutRequested = true;
1263            if (mLastInCompatMode) {
1264                params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1265                mLastInCompatMode = false;
1266            } else {
1267                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1268                mLastInCompatMode = true;
1269            }
1270        }
1271
1272        mWindowAttributesChangesFlag = 0;
1273
1274        Rect frame = mWinFrame;
1275        if (mFirst) {
1276            mFullRedrawNeeded = true;
1277            mLayoutRequested = true;
1278
1279            if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
1280                    || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
1281                // NOTE -- system code, won't try to do compat mode.
1282                Point size = new Point();
1283                mDisplay.getRealSize(size);
1284                desiredWindowWidth = size.x;
1285                desiredWindowHeight = size.y;
1286            } else {
1287                DisplayMetrics packageMetrics =
1288                    mView.getContext().getResources().getDisplayMetrics();
1289                desiredWindowWidth = packageMetrics.widthPixels;
1290                desiredWindowHeight = packageMetrics.heightPixels;
1291            }
1292
1293            // We used to use the following condition to choose 32 bits drawing caches:
1294            // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1295            // However, windows are now always 32 bits by default, so choose 32 bits
1296            mAttachInfo.mUse32BitDrawingCache = true;
1297            mAttachInfo.mHasWindowFocus = false;
1298            mAttachInfo.mWindowVisibility = viewVisibility;
1299            mAttachInfo.mRecomputeGlobalAttributes = false;
1300            viewVisibilityChanged = false;
1301            mLastConfiguration.setTo(host.getResources().getConfiguration());
1302            mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1303            // Set the layout direction if it has not been set before (inherit is the default)
1304            if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1305                host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1306            }
1307            host.dispatchAttachedToWindow(mAttachInfo, 0);
1308            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
1309            dispatchApplyInsets(host);
1310            //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
1311
1312        } else {
1313            desiredWindowWidth = frame.width();
1314            desiredWindowHeight = frame.height();
1315            if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
1316                if (DEBUG_ORIENTATION) Log.v(TAG,
1317                        "View " + host + " resized to: " + frame);
1318                mFullRedrawNeeded = true;
1319                mLayoutRequested = true;
1320                windowSizeMayChange = true;
1321            }
1322        }
1323
1324        if (viewVisibilityChanged) {
1325            mAttachInfo.mWindowVisibility = viewVisibility;
1326            host.dispatchWindowVisibilityChanged(viewVisibility);
1327            if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1328                destroyHardwareResources();
1329            }
1330            if (viewVisibility == View.GONE) {
1331                // After making a window gone, we will count it as being
1332                // shown for the first time the next time it gets focus.
1333                mHasHadWindowFocus = false;
1334            }
1335        }
1336
1337        // Non-visible windows can't hold accessibility focus.
1338        if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
1339            host.clearAccessibilityFocus();
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 (!handled && event.isTargetAccessibilityFocus()) {
4138                // The event was targeting accessibility focused view and is not handled,
4139                // it is very rare but possible that a predecessor of the focused view handles
4140                // the event but didn't due to special dispatch, perform normal event dispatch.
4141                event.setTargetAccessibilityFocus(false);
4142                handled = mView.dispatchPointerEvent(event);
4143            }
4144            if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4145                mUnbufferedInputDispatch = true;
4146                if (mConsumeBatchedInputScheduled) {
4147                    scheduleConsumeBatchedInputImmediately();
4148                }
4149            }
4150            return handled ? FINISH_HANDLED : FORWARD;
4151        }
4152
4153        private int processTrackballEvent(QueuedInputEvent q) {
4154            final MotionEvent event = (MotionEvent)q.mEvent;
4155
4156            if (mView.dispatchTrackballEvent(event)) {
4157                return FINISH_HANDLED;
4158            }
4159            return FORWARD;
4160        }
4161
4162        private int processGenericMotionEvent(QueuedInputEvent q) {
4163            final MotionEvent event = (MotionEvent)q.mEvent;
4164
4165            // Deliver the event to the view.
4166            if (mView.dispatchGenericMotionEvent(event)) {
4167                return FINISH_HANDLED;
4168            }
4169            return FORWARD;
4170        }
4171    }
4172
4173    /**
4174     * Performs synthesis of new input events from unhandled input events.
4175     */
4176    final class SyntheticInputStage extends InputStage {
4177        private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
4178        private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
4179        private final SyntheticTouchNavigationHandler mTouchNavigation =
4180                new SyntheticTouchNavigationHandler();
4181        private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
4182
4183        public SyntheticInputStage() {
4184            super(null);
4185        }
4186
4187        @Override
4188        protected int onProcess(QueuedInputEvent q) {
4189            q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
4190            if (q.mEvent instanceof MotionEvent) {
4191                final MotionEvent event = (MotionEvent)q.mEvent;
4192                final int source = event.getSource();
4193                if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4194                    mTrackball.process(event);
4195                    return FINISH_HANDLED;
4196                } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4197                    mJoystick.process(event);
4198                    return FINISH_HANDLED;
4199                } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4200                        == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4201                    mTouchNavigation.process(event);
4202                    return FINISH_HANDLED;
4203                }
4204            } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4205                mKeyboard.process((KeyEvent)q.mEvent);
4206                return FINISH_HANDLED;
4207            }
4208
4209            return FORWARD;
4210        }
4211
4212        @Override
4213        protected void onDeliverToNext(QueuedInputEvent q) {
4214            if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
4215                // Cancel related synthetic events if any prior stage has handled the event.
4216                if (q.mEvent instanceof MotionEvent) {
4217                    final MotionEvent event = (MotionEvent)q.mEvent;
4218                    final int source = event.getSource();
4219                    if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4220                        mTrackball.cancel(event);
4221                    } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4222                        mJoystick.cancel(event);
4223                    } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4224                            == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4225                        mTouchNavigation.cancel(event);
4226                    }
4227                }
4228            }
4229            super.onDeliverToNext(q);
4230        }
4231    }
4232
4233    /**
4234     * Creates dpad events from unhandled trackball movements.
4235     */
4236    final class SyntheticTrackballHandler {
4237        private final TrackballAxis mX = new TrackballAxis();
4238        private final TrackballAxis mY = new TrackballAxis();
4239        private long mLastTime;
4240
4241        public void process(MotionEvent event) {
4242            // Translate the trackball event into DPAD keys and try to deliver those.
4243            long curTime = SystemClock.uptimeMillis();
4244            if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
4245                // It has been too long since the last movement,
4246                // so restart at the beginning.
4247                mX.reset(0);
4248                mY.reset(0);
4249                mLastTime = curTime;
4250            }
4251
4252            final int action = event.getAction();
4253            final int metaState = event.getMetaState();
4254            switch (action) {
4255                case MotionEvent.ACTION_DOWN:
4256                    mX.reset(2);
4257                    mY.reset(2);
4258                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4259                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4260                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4261                            InputDevice.SOURCE_KEYBOARD));
4262                    break;
4263                case MotionEvent.ACTION_UP:
4264                    mX.reset(2);
4265                    mY.reset(2);
4266                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4267                            KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4268                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4269                            InputDevice.SOURCE_KEYBOARD));
4270                    break;
4271            }
4272
4273            if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step="
4274                    + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
4275                    + " move=" + event.getX()
4276                    + " / Y=" + mY.position + " step="
4277                    + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
4278                    + " move=" + event.getY());
4279            final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
4280            final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
4281
4282            // Generate DPAD events based on the trackball movement.
4283            // We pick the axis that has moved the most as the direction of
4284            // the DPAD.  When we generate DPAD events for one axis, then the
4285            // other axis is reset -- we don't want to perform DPAD jumps due
4286            // to slight movements in the trackball when making major movements
4287            // along the other axis.
4288            int keycode = 0;
4289            int movement = 0;
4290            float accel = 1;
4291            if (xOff > yOff) {
4292                movement = mX.generate();
4293                if (movement != 0) {
4294                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
4295                            : KeyEvent.KEYCODE_DPAD_LEFT;
4296                    accel = mX.acceleration;
4297                    mY.reset(2);
4298                }
4299            } else if (yOff > 0) {
4300                movement = mY.generate();
4301                if (movement != 0) {
4302                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
4303                            : KeyEvent.KEYCODE_DPAD_UP;
4304                    accel = mY.acceleration;
4305                    mX.reset(2);
4306                }
4307            }
4308
4309            if (keycode != 0) {
4310                if (movement < 0) movement = -movement;
4311                int accelMovement = (int)(movement * accel);
4312                if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
4313                        + " accelMovement=" + accelMovement
4314                        + " accel=" + accel);
4315                if (accelMovement > movement) {
4316                    if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4317                            + keycode);
4318                    movement--;
4319                    int repeatCount = accelMovement - movement;
4320                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4321                            KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
4322                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4323                            InputDevice.SOURCE_KEYBOARD));
4324                }
4325                while (movement > 0) {
4326                    if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4327                            + keycode);
4328                    movement--;
4329                    curTime = SystemClock.uptimeMillis();
4330                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4331                            KeyEvent.ACTION_DOWN, keycode, 0, metaState,
4332                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4333                            InputDevice.SOURCE_KEYBOARD));
4334                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4335                            KeyEvent.ACTION_UP, keycode, 0, metaState,
4336                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4337                            InputDevice.SOURCE_KEYBOARD));
4338                }
4339                mLastTime = curTime;
4340            }
4341        }
4342
4343        public void cancel(MotionEvent event) {
4344            mLastTime = Integer.MIN_VALUE;
4345
4346            // If we reach this, we consumed a trackball event.
4347            // Because we will not translate the trackball event into a key event,
4348            // touch mode will not exit, so we exit touch mode here.
4349            if (mView != null && mAdded) {
4350                ensureTouchMode(false);
4351            }
4352        }
4353    }
4354
4355    /**
4356     * Maintains state information for a single trackball axis, generating
4357     * discrete (DPAD) movements based on raw trackball motion.
4358     */
4359    static final class TrackballAxis {
4360        /**
4361         * The maximum amount of acceleration we will apply.
4362         */
4363        static final float MAX_ACCELERATION = 20;
4364
4365        /**
4366         * The maximum amount of time (in milliseconds) between events in order
4367         * for us to consider the user to be doing fast trackball movements,
4368         * and thus apply an acceleration.
4369         */
4370        static final long FAST_MOVE_TIME = 150;
4371
4372        /**
4373         * Scaling factor to the time (in milliseconds) between events to how
4374         * much to multiple/divide the current acceleration.  When movement
4375         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4376         * FAST_MOVE_TIME it divides it.
4377         */
4378        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4379
4380        static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
4381        static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
4382        static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
4383
4384        float position;
4385        float acceleration = 1;
4386        long lastMoveTime = 0;
4387        int step;
4388        int dir;
4389        int nonAccelMovement;
4390
4391        void reset(int _step) {
4392            position = 0;
4393            acceleration = 1;
4394            lastMoveTime = 0;
4395            step = _step;
4396            dir = 0;
4397        }
4398
4399        /**
4400         * Add trackball movement into the state.  If the direction of movement
4401         * has been reversed, the state is reset before adding the
4402         * movement (so that you don't have to compensate for any previously
4403         * collected movement before see the result of the movement in the
4404         * new direction).
4405         *
4406         * @return Returns the absolute value of the amount of movement
4407         * collected so far.
4408         */
4409        float collect(float off, long time, String axis) {
4410            long normTime;
4411            if (off > 0) {
4412                normTime = (long)(off * FAST_MOVE_TIME);
4413                if (dir < 0) {
4414                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4415                    position = 0;
4416                    step = 0;
4417                    acceleration = 1;
4418                    lastMoveTime = 0;
4419                }
4420                dir = 1;
4421            } else if (off < 0) {
4422                normTime = (long)((-off) * FAST_MOVE_TIME);
4423                if (dir > 0) {
4424                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4425                    position = 0;
4426                    step = 0;
4427                    acceleration = 1;
4428                    lastMoveTime = 0;
4429                }
4430                dir = -1;
4431            } else {
4432                normTime = 0;
4433            }
4434
4435            // The number of milliseconds between each movement that is
4436            // considered "normal" and will not result in any acceleration
4437            // or deceleration, scaled by the offset we have here.
4438            if (normTime > 0) {
4439                long delta = time - lastMoveTime;
4440                lastMoveTime = time;
4441                float acc = acceleration;
4442                if (delta < normTime) {
4443                    // The user is scrolling rapidly, so increase acceleration.
4444                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4445                    if (scale > 1) acc *= scale;
4446                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4447                            + off + " normTime=" + normTime + " delta=" + delta
4448                            + " scale=" + scale + " acc=" + acc);
4449                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4450                } else {
4451                    // The user is scrolling slowly, so decrease acceleration.
4452                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4453                    if (scale > 1) acc /= scale;
4454                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4455                            + off + " normTime=" + normTime + " delta=" + delta
4456                            + " scale=" + scale + " acc=" + acc);
4457                    acceleration = acc > 1 ? acc : 1;
4458                }
4459            }
4460            position += off;
4461            return Math.abs(position);
4462        }
4463
4464        /**
4465         * Generate the number of discrete movement events appropriate for
4466         * the currently collected trackball movement.
4467         *
4468         * @return Returns the number of discrete movements, either positive
4469         * or negative, or 0 if there is not enough trackball movement yet
4470         * for a discrete movement.
4471         */
4472        int generate() {
4473            int movement = 0;
4474            nonAccelMovement = 0;
4475            do {
4476                final int dir = position >= 0 ? 1 : -1;
4477                switch (step) {
4478                    // If we are going to execute the first step, then we want
4479                    // to do this as soon as possible instead of waiting for
4480                    // a full movement, in order to make things look responsive.
4481                    case 0:
4482                        if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4483                            return movement;
4484                        }
4485                        movement += dir;
4486                        nonAccelMovement += dir;
4487                        step = 1;
4488                        break;
4489                    // If we have generated the first movement, then we need
4490                    // to wait for the second complete trackball motion before
4491                    // generating the second discrete movement.
4492                    case 1:
4493                        if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4494                            return movement;
4495                        }
4496                        movement += dir;
4497                        nonAccelMovement += dir;
4498                        position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
4499                        step = 2;
4500                        break;
4501                    // After the first two, we generate discrete movements
4502                    // consistently with the trackball, applying an acceleration
4503                    // if the trackball is moving quickly.  This is a simple
4504                    // acceleration on top of what we already compute based
4505                    // on how quickly the wheel is being turned, to apply
4506                    // a longer increasing acceleration to continuous movement
4507                    // in one direction.
4508                    default:
4509                        if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4510                            return movement;
4511                        }
4512                        movement += dir;
4513                        position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4514                        float acc = acceleration;
4515                        acc *= 1.1f;
4516                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4517                        break;
4518                }
4519            } while (true);
4520        }
4521    }
4522
4523    /**
4524     * Creates dpad events from unhandled joystick movements.
4525     */
4526    final class SyntheticJoystickHandler extends Handler {
4527        private final static String TAG = "SyntheticJoystickHandler";
4528        private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
4529        private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
4530
4531        private int mLastXDirection;
4532        private int mLastYDirection;
4533        private int mLastXKeyCode;
4534        private int mLastYKeyCode;
4535
4536        public SyntheticJoystickHandler() {
4537            super(true);
4538        }
4539
4540        @Override
4541        public void handleMessage(Message msg) {
4542            switch (msg.what) {
4543                case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
4544                case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
4545                    KeyEvent oldEvent = (KeyEvent)msg.obj;
4546                    KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
4547                            SystemClock.uptimeMillis(),
4548                            oldEvent.getRepeatCount() + 1);
4549                    if (mAttachInfo.mHasWindowFocus) {
4550                        enqueueInputEvent(e);
4551                        Message m = obtainMessage(msg.what, e);
4552                        m.setAsynchronous(true);
4553                        sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
4554                    }
4555                } break;
4556            }
4557        }
4558
4559        public void process(MotionEvent event) {
4560            switch(event.getActionMasked()) {
4561            case MotionEvent.ACTION_CANCEL:
4562                cancel(event);
4563                break;
4564            case MotionEvent.ACTION_MOVE:
4565                update(event, true);
4566                break;
4567            default:
4568                Log.w(TAG, "Unexpected action: " + event.getActionMasked());
4569            }
4570        }
4571
4572        private void cancel(MotionEvent event) {
4573            removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4574            removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4575            update(event, false);
4576        }
4577
4578        private void update(MotionEvent event, boolean synthesizeNewKeys) {
4579            final long time = event.getEventTime();
4580            final int metaState = event.getMetaState();
4581            final int deviceId = event.getDeviceId();
4582            final int source = event.getSource();
4583
4584            int xDirection = joystickAxisValueToDirection(
4585                    event.getAxisValue(MotionEvent.AXIS_HAT_X));
4586            if (xDirection == 0) {
4587                xDirection = joystickAxisValueToDirection(event.getX());
4588            }
4589
4590            int yDirection = joystickAxisValueToDirection(
4591                    event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4592            if (yDirection == 0) {
4593                yDirection = joystickAxisValueToDirection(event.getY());
4594            }
4595
4596            if (xDirection != mLastXDirection) {
4597                if (mLastXKeyCode != 0) {
4598                    removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4599                    enqueueInputEvent(new KeyEvent(time, time,
4600                            KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState,
4601                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4602                    mLastXKeyCode = 0;
4603                }
4604
4605                mLastXDirection = xDirection;
4606
4607                if (xDirection != 0 && synthesizeNewKeys) {
4608                    mLastXKeyCode = xDirection > 0
4609                            ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
4610                    final KeyEvent e = new KeyEvent(time, time,
4611                            KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState,
4612                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4613                    enqueueInputEvent(e);
4614                    Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
4615                    m.setAsynchronous(true);
4616                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4617                }
4618            }
4619
4620            if (yDirection != mLastYDirection) {
4621                if (mLastYKeyCode != 0) {
4622                    removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4623                    enqueueInputEvent(new KeyEvent(time, time,
4624                            KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState,
4625                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4626                    mLastYKeyCode = 0;
4627                }
4628
4629                mLastYDirection = yDirection;
4630
4631                if (yDirection != 0 && synthesizeNewKeys) {
4632                    mLastYKeyCode = yDirection > 0
4633                            ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
4634                    final KeyEvent e = new KeyEvent(time, time,
4635                            KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState,
4636                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4637                    enqueueInputEvent(e);
4638                    Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e);
4639                    m.setAsynchronous(true);
4640                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4641                }
4642            }
4643        }
4644
4645        private int joystickAxisValueToDirection(float value) {
4646            if (value >= 0.5f) {
4647                return 1;
4648            } else if (value <= -0.5f) {
4649                return -1;
4650            } else {
4651                return 0;
4652            }
4653        }
4654    }
4655
4656    /**
4657     * Creates dpad events from unhandled touch navigation movements.
4658     */
4659    final class SyntheticTouchNavigationHandler extends Handler {
4660        private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4661        private static final boolean LOCAL_DEBUG = false;
4662
4663        // Assumed nominal width and height in millimeters of a touch navigation pad,
4664        // if no resolution information is available from the input system.
4665        private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
4666        private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
4667
4668        /* TODO: These constants should eventually be moved to ViewConfiguration. */
4669
4670        // The nominal distance traveled to move by one unit.
4671        private static final int TICK_DISTANCE_MILLIMETERS = 12;
4672
4673        // Minimum and maximum fling velocity in ticks per second.
4674        // The minimum velocity should be set such that we perform enough ticks per
4675        // second that the fling appears to be fluid.  For example, if we set the minimum
4676        // to 2 ticks per second, then there may be up to half a second delay between the next
4677        // to last and last ticks which is noticeably discrete and jerky.  This value should
4678        // probably not be set to anything less than about 4.
4679        // If fling accuracy is a problem then consider tuning the tick distance instead.
4680        private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
4681        private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
4682
4683        // Fling velocity decay factor applied after each new key is emitted.
4684        // This parameter controls the deceleration and overall duration of the fling.
4685        // The fling stops automatically when its velocity drops below the minimum
4686        // fling velocity defined above.
4687        private static final float FLING_TICK_DECAY = 0.8f;
4688
4689        /* The input device that we are tracking. */
4690
4691        private int mCurrentDeviceId = -1;
4692        private int mCurrentSource;
4693        private boolean mCurrentDeviceSupported;
4694
4695        /* Configuration for the current input device. */
4696
4697        // The scaled tick distance.  A movement of this amount should generally translate
4698        // into a single dpad event in a given direction.
4699        private float mConfigTickDistance;
4700
4701        // The minimum and maximum scaled fling velocity.
4702        private float mConfigMinFlingVelocity;
4703        private float mConfigMaxFlingVelocity;
4704
4705        /* Tracking state. */
4706
4707        // The velocity tracker for detecting flings.
4708        private VelocityTracker mVelocityTracker;
4709
4710        // The active pointer id, or -1 if none.
4711        private int mActivePointerId = -1;
4712
4713        // Location where tracking started.
4714        private float mStartX;
4715        private float mStartY;
4716
4717        // Most recently observed position.
4718        private float mLastX;
4719        private float mLastY;
4720
4721        // Accumulated movement delta since the last direction key was sent.
4722        private float mAccumulatedX;
4723        private float mAccumulatedY;
4724
4725        // Set to true if any movement was delivered to the app.
4726        // Implies that tap slop was exceeded.
4727        private boolean mConsumedMovement;
4728
4729        // The most recently sent key down event.
4730        // The keycode remains set until the direction changes or a fling ends
4731        // so that repeated key events may be generated as required.
4732        private long mPendingKeyDownTime;
4733        private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4734        private int mPendingKeyRepeatCount;
4735        private int mPendingKeyMetaState;
4736
4737        // The current fling velocity while a fling is in progress.
4738        private boolean mFlinging;
4739        private float mFlingVelocity;
4740
4741        public SyntheticTouchNavigationHandler() {
4742            super(true);
4743        }
4744
4745        public void process(MotionEvent event) {
4746            // Update the current device information.
4747            final long time = event.getEventTime();
4748            final int deviceId = event.getDeviceId();
4749            final int source = event.getSource();
4750            if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
4751                finishKeys(time);
4752                finishTracking(time);
4753                mCurrentDeviceId = deviceId;
4754                mCurrentSource = source;
4755                mCurrentDeviceSupported = false;
4756                InputDevice device = event.getDevice();
4757                if (device != null) {
4758                    // In order to support an input device, we must know certain
4759                    // characteristics about it, such as its size and resolution.
4760                    InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
4761                    InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
4762                    if (xRange != null && yRange != null) {
4763                        mCurrentDeviceSupported = true;
4764
4765                        // Infer the resolution if it not actually known.
4766                        float xRes = xRange.getResolution();
4767                        if (xRes <= 0) {
4768                            xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
4769                        }
4770                        float yRes = yRange.getResolution();
4771                        if (yRes <= 0) {
4772                            yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
4773                        }
4774                        float nominalRes = (xRes + yRes) * 0.5f;
4775
4776                        // Precompute all of the configuration thresholds we will need.
4777                        mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
4778                        mConfigMinFlingVelocity =
4779                                MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4780                        mConfigMaxFlingVelocity =
4781                                MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4782
4783                        if (LOCAL_DEBUG) {
4784                            Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
4785                                    + " (" + Integer.toHexString(mCurrentSource) + "): "
4786                                    + ", mConfigTickDistance=" + mConfigTickDistance
4787                                    + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
4788                                    + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
4789                        }
4790                    }
4791                }
4792            }
4793            if (!mCurrentDeviceSupported) {
4794                return;
4795            }
4796
4797            // Handle the event.
4798            final int action = event.getActionMasked();
4799            switch (action) {
4800                case MotionEvent.ACTION_DOWN: {
4801                    boolean caughtFling = mFlinging;
4802                    finishKeys(time);
4803                    finishTracking(time);
4804                    mActivePointerId = event.getPointerId(0);
4805                    mVelocityTracker = VelocityTracker.obtain();
4806                    mVelocityTracker.addMovement(event);
4807                    mStartX = event.getX();
4808                    mStartY = event.getY();
4809                    mLastX = mStartX;
4810                    mLastY = mStartY;
4811                    mAccumulatedX = 0;
4812                    mAccumulatedY = 0;
4813
4814                    // If we caught a fling, then pretend that the tap slop has already
4815                    // been exceeded to suppress taps whose only purpose is to stop the fling.
4816                    mConsumedMovement = caughtFling;
4817                    break;
4818                }
4819
4820                case MotionEvent.ACTION_MOVE:
4821                case MotionEvent.ACTION_UP: {
4822                    if (mActivePointerId < 0) {
4823                        break;
4824                    }
4825                    final int index = event.findPointerIndex(mActivePointerId);
4826                    if (index < 0) {
4827                        finishKeys(time);
4828                        finishTracking(time);
4829                        break;
4830                    }
4831
4832                    mVelocityTracker.addMovement(event);
4833                    final float x = event.getX(index);
4834                    final float y = event.getY(index);
4835                    mAccumulatedX += x - mLastX;
4836                    mAccumulatedY += y - mLastY;
4837                    mLastX = x;
4838                    mLastY = y;
4839
4840                    // Consume any accumulated movement so far.
4841                    final int metaState = event.getMetaState();
4842                    consumeAccumulatedMovement(time, metaState);
4843
4844                    // Detect taps and flings.
4845                    if (action == MotionEvent.ACTION_UP) {
4846                        if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4847                            // It might be a fling.
4848                            mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
4849                            final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
4850                            final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
4851                            if (!startFling(time, vx, vy)) {
4852                                finishKeys(time);
4853                            }
4854                        }
4855                        finishTracking(time);
4856                    }
4857                    break;
4858                }
4859
4860                case MotionEvent.ACTION_CANCEL: {
4861                    finishKeys(time);
4862                    finishTracking(time);
4863                    break;
4864                }
4865            }
4866        }
4867
4868        public void cancel(MotionEvent event) {
4869            if (mCurrentDeviceId == event.getDeviceId()
4870                    && mCurrentSource == event.getSource()) {
4871                final long time = event.getEventTime();
4872                finishKeys(time);
4873                finishTracking(time);
4874            }
4875        }
4876
4877        private void finishKeys(long time) {
4878            cancelFling();
4879            sendKeyUp(time);
4880        }
4881
4882        private void finishTracking(long time) {
4883            if (mActivePointerId >= 0) {
4884                mActivePointerId = -1;
4885                mVelocityTracker.recycle();
4886                mVelocityTracker = null;
4887            }
4888        }
4889
4890        private void consumeAccumulatedMovement(long time, int metaState) {
4891            final float absX = Math.abs(mAccumulatedX);
4892            final float absY = Math.abs(mAccumulatedY);
4893            if (absX >= absY) {
4894                if (absX >= mConfigTickDistance) {
4895                    mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
4896                            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
4897                    mAccumulatedY = 0;
4898                    mConsumedMovement = true;
4899                }
4900            } else {
4901                if (absY >= mConfigTickDistance) {
4902                    mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
4903                            KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
4904                    mAccumulatedX = 0;
4905                    mConsumedMovement = true;
4906                }
4907            }
4908        }
4909
4910        private float consumeAccumulatedMovement(long time, int metaState,
4911                float accumulator, int negativeKeyCode, int positiveKeyCode) {
4912            while (accumulator <= -mConfigTickDistance) {
4913                sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
4914                accumulator += mConfigTickDistance;
4915            }
4916            while (accumulator >= mConfigTickDistance) {
4917                sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
4918                accumulator -= mConfigTickDistance;
4919            }
4920            return accumulator;
4921        }
4922
4923        private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
4924            if (mPendingKeyCode != keyCode) {
4925                sendKeyUp(time);
4926                mPendingKeyDownTime = time;
4927                mPendingKeyCode = keyCode;
4928                mPendingKeyRepeatCount = 0;
4929            } else {
4930                mPendingKeyRepeatCount += 1;
4931            }
4932            mPendingKeyMetaState = metaState;
4933
4934            // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
4935            // but it doesn't quite make sense when simulating the events in this way.
4936            if (LOCAL_DEBUG) {
4937                Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
4938                        + ", repeatCount=" + mPendingKeyRepeatCount
4939                        + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4940            }
4941            enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4942                    KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
4943                    mPendingKeyMetaState, mCurrentDeviceId,
4944                    KeyEvent.FLAG_FALLBACK, mCurrentSource));
4945        }
4946
4947        private void sendKeyUp(long time) {
4948            if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4949                if (LOCAL_DEBUG) {
4950                    Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
4951                            + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4952                }
4953                enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4954                        KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
4955                        mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
4956                        mCurrentSource));
4957                mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4958            }
4959        }
4960
4961        private boolean startFling(long time, float vx, float vy) {
4962            if (LOCAL_DEBUG) {
4963                Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
4964                        + ", min=" + mConfigMinFlingVelocity);
4965            }
4966
4967            // Flings must be oriented in the same direction as the preceding movements.
4968            switch (mPendingKeyCode) {
4969                case KeyEvent.KEYCODE_DPAD_LEFT:
4970                    if (-vx >= mConfigMinFlingVelocity
4971                            && Math.abs(vy) < mConfigMinFlingVelocity) {
4972                        mFlingVelocity = -vx;
4973                        break;
4974                    }
4975                    return false;
4976
4977                case KeyEvent.KEYCODE_DPAD_RIGHT:
4978                    if (vx >= mConfigMinFlingVelocity
4979                            && Math.abs(vy) < mConfigMinFlingVelocity) {
4980                        mFlingVelocity = vx;
4981                        break;
4982                    }
4983                    return false;
4984
4985                case KeyEvent.KEYCODE_DPAD_UP:
4986                    if (-vy >= mConfigMinFlingVelocity
4987                            && Math.abs(vx) < mConfigMinFlingVelocity) {
4988                        mFlingVelocity = -vy;
4989                        break;
4990                    }
4991                    return false;
4992
4993                case KeyEvent.KEYCODE_DPAD_DOWN:
4994                    if (vy >= mConfigMinFlingVelocity
4995                            && Math.abs(vx) < mConfigMinFlingVelocity) {
4996                        mFlingVelocity = vy;
4997                        break;
4998                    }
4999                    return false;
5000            }
5001
5002            // Post the first fling event.
5003            mFlinging = postFling(time);
5004            return mFlinging;
5005        }
5006
5007        private boolean postFling(long time) {
5008            // The idea here is to estimate the time when the pointer would have
5009            // traveled one tick distance unit given the current fling velocity.
5010            // This effect creates continuity of motion.
5011            if (mFlingVelocity >= mConfigMinFlingVelocity) {
5012                long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
5013                postAtTime(mFlingRunnable, time + delay);
5014                if (LOCAL_DEBUG) {
5015                    Log.d(LOCAL_TAG, "Posted fling: velocity="
5016                            + mFlingVelocity + ", delay=" + delay
5017                            + ", keyCode=" + mPendingKeyCode);
5018                }
5019                return true;
5020            }
5021            return false;
5022        }
5023
5024        private void cancelFling() {
5025            if (mFlinging) {
5026                removeCallbacks(mFlingRunnable);
5027                mFlinging = false;
5028            }
5029        }
5030
5031        private final Runnable mFlingRunnable = new Runnable() {
5032            @Override
5033            public void run() {
5034                final long time = SystemClock.uptimeMillis();
5035                sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5036                mFlingVelocity *= FLING_TICK_DECAY;
5037                if (!postFling(time)) {
5038                    mFlinging = false;
5039                    finishKeys(time);
5040                }
5041            }
5042        };
5043    }
5044
5045    final class SyntheticKeyboardHandler {
5046        public void process(KeyEvent event) {
5047            if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5048                return;
5049            }
5050
5051            final KeyCharacterMap kcm = event.getKeyCharacterMap();
5052            final int keyCode = event.getKeyCode();
5053            final int metaState = event.getMetaState();
5054
5055            // Check for fallback actions specified by the key character map.
5056            KeyCharacterMap.FallbackAction fallbackAction =
5057                    kcm.getFallbackAction(keyCode, metaState);
5058            if (fallbackAction != null) {
5059                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5060                KeyEvent fallbackEvent = KeyEvent.obtain(
5061                        event.getDownTime(), event.getEventTime(),
5062                        event.getAction(), fallbackAction.keyCode,
5063                        event.getRepeatCount(), fallbackAction.metaState,
5064                        event.getDeviceId(), event.getScanCode(),
5065                        flags, event.getSource(), null);
5066                fallbackAction.recycle();
5067                enqueueInputEvent(fallbackEvent);
5068            }
5069        }
5070    }
5071
5072    /**
5073     * Returns true if the key is used for keyboard navigation.
5074     * @param keyEvent The key event.
5075     * @return True if the key is used for keyboard navigation.
5076     */
5077    private static boolean isNavigationKey(KeyEvent keyEvent) {
5078        switch (keyEvent.getKeyCode()) {
5079        case KeyEvent.KEYCODE_DPAD_LEFT:
5080        case KeyEvent.KEYCODE_DPAD_RIGHT:
5081        case KeyEvent.KEYCODE_DPAD_UP:
5082        case KeyEvent.KEYCODE_DPAD_DOWN:
5083        case KeyEvent.KEYCODE_DPAD_CENTER:
5084        case KeyEvent.KEYCODE_PAGE_UP:
5085        case KeyEvent.KEYCODE_PAGE_DOWN:
5086        case KeyEvent.KEYCODE_MOVE_HOME:
5087        case KeyEvent.KEYCODE_MOVE_END:
5088        case KeyEvent.KEYCODE_TAB:
5089        case KeyEvent.KEYCODE_SPACE:
5090        case KeyEvent.KEYCODE_ENTER:
5091            return true;
5092        }
5093        return false;
5094    }
5095
5096    /**
5097     * Returns true if the key is used for typing.
5098     * @param keyEvent The key event.
5099     * @return True if the key is used for typing.
5100     */
5101    private static boolean isTypingKey(KeyEvent keyEvent) {
5102        return keyEvent.getUnicodeChar() > 0;
5103    }
5104
5105    /**
5106     * See if the key event means we should leave touch mode (and leave touch mode if so).
5107     * @param event The key event.
5108     * @return Whether this key event should be consumed (meaning the act of
5109     *   leaving touch mode alone is considered the event).
5110     */
5111    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
5112        // Only relevant in touch mode.
5113        if (!mAttachInfo.mInTouchMode) {
5114            return false;
5115        }
5116
5117        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
5118        final int action = event.getAction();
5119        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
5120            return false;
5121        }
5122
5123        // Don't leave touch mode if the IME told us not to.
5124        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
5125            return false;
5126        }
5127
5128        // If the key can be used for keyboard navigation then leave touch mode
5129        // and select a focused view if needed (in ensureTouchMode).
5130        // When a new focused view is selected, we consume the navigation key because
5131        // navigation doesn't make much sense unless a view already has focus so
5132        // the key's purpose is to set focus.
5133        if (isNavigationKey(event)) {
5134            return ensureTouchMode(false);
5135        }
5136
5137        // If the key can be used for typing then leave touch mode
5138        // and select a focused view if needed (in ensureTouchMode).
5139        // Always allow the view to process the typing key.
5140        if (isTypingKey(event)) {
5141            ensureTouchMode(false);
5142            return false;
5143        }
5144
5145        return false;
5146    }
5147
5148    /* drag/drop */
5149    void setLocalDragState(Object obj) {
5150        mLocalDragState = obj;
5151    }
5152
5153    private void handleDragEvent(DragEvent event) {
5154        // From the root, only drag start/end/location are dispatched.  entered/exited
5155        // are determined and dispatched by the viewgroup hierarchy, who then report
5156        // that back here for ultimate reporting back to the framework.
5157        if (mView != null && mAdded) {
5158            final int what = event.mAction;
5159
5160            if (what == DragEvent.ACTION_DRAG_EXITED) {
5161                // A direct EXITED event means that the window manager knows we've just crossed
5162                // a window boundary, so the current drag target within this one must have
5163                // just been exited.  Send it the usual notifications and then we're done
5164                // for now.
5165                mView.dispatchDragEvent(event);
5166            } else {
5167                // Cache the drag description when the operation starts, then fill it in
5168                // on subsequent calls as a convenience
5169                if (what == DragEvent.ACTION_DRAG_STARTED) {
5170                    mCurrentDragView = null;    // Start the current-recipient tracking
5171                    mDragDescription = event.mClipDescription;
5172                } else {
5173                    event.mClipDescription = mDragDescription;
5174                }
5175
5176                // For events with a [screen] location, translate into window coordinates
5177                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
5178                    mDragPoint.set(event.mX, event.mY);
5179                    if (mTranslator != null) {
5180                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
5181                    }
5182
5183                    if (mCurScrollY != 0) {
5184                        mDragPoint.offset(0, mCurScrollY);
5185                    }
5186
5187                    event.mX = mDragPoint.x;
5188                    event.mY = mDragPoint.y;
5189                }
5190
5191                // Remember who the current drag target is pre-dispatch
5192                final View prevDragView = mCurrentDragView;
5193
5194                // Now dispatch the drag/drop event
5195                boolean result = mView.dispatchDragEvent(event);
5196
5197                // If we changed apparent drag target, tell the OS about it
5198                if (prevDragView != mCurrentDragView) {
5199                    try {
5200                        if (prevDragView != null) {
5201                            mWindowSession.dragRecipientExited(mWindow);
5202                        }
5203                        if (mCurrentDragView != null) {
5204                            mWindowSession.dragRecipientEntered(mWindow);
5205                        }
5206                    } catch (RemoteException e) {
5207                        Slog.e(TAG, "Unable to note drag target change");
5208                    }
5209                }
5210
5211                // Report the drop result when we're done
5212                if (what == DragEvent.ACTION_DROP) {
5213                    mDragDescription = null;
5214                    try {
5215                        Log.i(TAG, "Reporting drop result: " + result);
5216                        mWindowSession.reportDropResult(mWindow, result);
5217                    } catch (RemoteException e) {
5218                        Log.e(TAG, "Unable to report drop result");
5219                    }
5220                }
5221
5222                // When the drag operation ends, release any local state object
5223                // that may have been in use
5224                if (what == DragEvent.ACTION_DRAG_ENDED) {
5225                    setLocalDragState(null);
5226                }
5227            }
5228        }
5229        event.recycle();
5230    }
5231
5232    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
5233        if (mSeq != args.seq) {
5234            // The sequence has changed, so we need to update our value and make
5235            // sure to do a traversal afterward so the window manager is given our
5236            // most recent data.
5237            mSeq = args.seq;
5238            mAttachInfo.mForceReportNewAttributes = true;
5239            scheduleTraversals();
5240        }
5241        if (mView == null) return;
5242        if (args.localChanges != 0) {
5243            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
5244        }
5245
5246        int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5247        if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5248            mAttachInfo.mGlobalSystemUiVisibility = visibility;
5249            mView.dispatchSystemUiVisibilityChanged(visibility);
5250        }
5251    }
5252
5253    public void handleDispatchDoneAnimating() {
5254        if (mWindowsAnimating) {
5255            mWindowsAnimating = false;
5256            if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded)  {
5257                scheduleTraversals();
5258            }
5259        }
5260    }
5261
5262    public void handleDispatchWindowShown() {
5263        mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5264    }
5265
5266    public void getLastTouchPoint(Point outLocation) {
5267        outLocation.x = (int) mLastTouchPoint.x;
5268        outLocation.y = (int) mLastTouchPoint.y;
5269    }
5270
5271    public void setDragFocus(View newDragTarget) {
5272        if (mCurrentDragView != newDragTarget) {
5273            mCurrentDragView = newDragTarget;
5274        }
5275    }
5276
5277    private AudioManager getAudioManager() {
5278        if (mView == null) {
5279            throw new IllegalStateException("getAudioManager called when there is no mView");
5280        }
5281        if (mAudioManager == null) {
5282            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5283        }
5284        return mAudioManager;
5285    }
5286
5287    public AccessibilityInteractionController getAccessibilityInteractionController() {
5288        if (mView == null) {
5289            throw new IllegalStateException("getAccessibilityInteractionController"
5290                    + " called when there is no mView");
5291        }
5292        if (mAccessibilityInteractionController == null) {
5293            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
5294        }
5295        return mAccessibilityInteractionController;
5296    }
5297
5298    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5299            boolean insetsPending) throws RemoteException {
5300
5301        float appScale = mAttachInfo.mApplicationScale;
5302        boolean restore = false;
5303        if (params != null && mTranslator != null) {
5304            restore = true;
5305            params.backup();
5306            mTranslator.translateWindowLayout(params);
5307        }
5308        if (params != null) {
5309            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
5310        }
5311        mPendingConfiguration.seq = 0;
5312        //Log.d(TAG, ">>>>>> CALLING relayout");
5313        if (params != null && mOrigWindowType != params.type) {
5314            // For compatibility with old apps, don't crash here.
5315            if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5316                Slog.w(TAG, "Window type can not be changed after "
5317                        + "the window is added; ignoring change of " + mView);
5318                params.type = mOrigWindowType;
5319            }
5320        }
5321        int relayoutResult = mWindowSession.relayout(
5322                mWindow, mSeq, params,
5323                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
5324                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
5325                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
5326                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
5327                mPendingStableInsets, mPendingConfiguration, mSurface);
5328        //Log.d(TAG, "<<<<<< BACK FROM relayout");
5329        if (restore) {
5330            params.restore();
5331        }
5332
5333        if (mTranslator != null) {
5334            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
5335            mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
5336            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5337            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
5338            mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
5339        }
5340        return relayoutResult;
5341    }
5342
5343    /**
5344     * {@inheritDoc}
5345     */
5346    @Override
5347    public void playSoundEffect(int effectId) {
5348        checkThread();
5349
5350        if (mMediaDisabled) {
5351            return;
5352        }
5353
5354        try {
5355            final AudioManager audioManager = getAudioManager();
5356
5357            switch (effectId) {
5358                case SoundEffectConstants.CLICK:
5359                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5360                    return;
5361                case SoundEffectConstants.NAVIGATION_DOWN:
5362                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5363                    return;
5364                case SoundEffectConstants.NAVIGATION_LEFT:
5365                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5366                    return;
5367                case SoundEffectConstants.NAVIGATION_RIGHT:
5368                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5369                    return;
5370                case SoundEffectConstants.NAVIGATION_UP:
5371                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5372                    return;
5373                default:
5374                    throw new IllegalArgumentException("unknown effect id " + effectId +
5375                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
5376            }
5377        } catch (IllegalStateException e) {
5378            // Exception thrown by getAudioManager() when mView is null
5379            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
5380            e.printStackTrace();
5381        }
5382    }
5383
5384    /**
5385     * {@inheritDoc}
5386     */
5387    @Override
5388    public boolean performHapticFeedback(int effectId, boolean always) {
5389        try {
5390            return mWindowSession.performHapticFeedback(mWindow, effectId, always);
5391        } catch (RemoteException e) {
5392            return false;
5393        }
5394    }
5395
5396    /**
5397     * {@inheritDoc}
5398     */
5399    @Override
5400    public View focusSearch(View focused, int direction) {
5401        checkThread();
5402        if (!(mView instanceof ViewGroup)) {
5403            return null;
5404        }
5405        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5406    }
5407
5408    public void debug() {
5409        mView.debug();
5410    }
5411
5412    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5413        String innerPrefix = prefix + "  ";
5414        writer.print(prefix); writer.println("ViewRoot:");
5415        writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded);
5416                writer.print(" mRemoved="); writer.println(mRemoved);
5417        writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled=");
5418                writer.println(mConsumeBatchedInputScheduled);
5419        writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled=");
5420                writer.println(mConsumeBatchedInputImmediatelyScheduled);
5421        writer.print(innerPrefix); writer.print("mPendingInputEventCount=");
5422                writer.println(mPendingInputEventCount);
5423        writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled=");
5424                writer.println(mProcessInputEventsScheduled);
5425        writer.print(innerPrefix); writer.print("mTraversalScheduled=");
5426                writer.print(mTraversalScheduled);
5427        if (mTraversalScheduled) {
5428            writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")");
5429        } else {
5430            writer.println();
5431        }
5432        mFirstInputStage.dump(innerPrefix, writer);
5433
5434        mChoreographer.dump(prefix, writer);
5435
5436        writer.print(prefix); writer.println("View Hierarchy:");
5437        dumpViewHierarchy(innerPrefix, writer, mView);
5438    }
5439
5440    private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5441        writer.print(prefix);
5442        if (view == null) {
5443            writer.println("null");
5444            return;
5445        }
5446        writer.println(view.toString());
5447        if (!(view instanceof ViewGroup)) {
5448            return;
5449        }
5450        ViewGroup grp = (ViewGroup)view;
5451        final int N = grp.getChildCount();
5452        if (N <= 0) {
5453            return;
5454        }
5455        prefix = prefix + "  ";
5456        for (int i=0; i<N; i++) {
5457            dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5458        }
5459    }
5460
5461    public void dumpGfxInfo(int[] info) {
5462        info[0] = info[1] = 0;
5463        if (mView != null) {
5464            getGfxInfo(mView, info);
5465        }
5466    }
5467
5468    private static void getGfxInfo(View view, int[] info) {
5469        RenderNode renderNode = view.mRenderNode;
5470        info[0]++;
5471        if (renderNode != null) {
5472            info[1] += renderNode.getDebugSize();
5473        }
5474
5475        if (view instanceof ViewGroup) {
5476            ViewGroup group = (ViewGroup) view;
5477
5478            int count = group.getChildCount();
5479            for (int i = 0; i < count; i++) {
5480                getGfxInfo(group.getChildAt(i), info);
5481            }
5482        }
5483    }
5484
5485    /**
5486     * @param immediate True, do now if not in traversal. False, put on queue and do later.
5487     * @return True, request has been queued. False, request has been completed.
5488     */
5489    boolean die(boolean immediate) {
5490        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
5491        // done by dispatchDetachedFromWindow will cause havoc on return.
5492        if (immediate && !mIsInTraversal) {
5493            doDie();
5494            return false;
5495        }
5496
5497        if (!mIsDrawing) {
5498            destroyHardwareRenderer();
5499        } else {
5500            Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
5501                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
5502        }
5503        mHandler.sendEmptyMessage(MSG_DIE);
5504        return true;
5505    }
5506
5507    void doDie() {
5508        checkThread();
5509        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
5510        synchronized (this) {
5511            if (mRemoved) {
5512                return;
5513            }
5514            mRemoved = true;
5515            if (mAdded) {
5516                dispatchDetachedFromWindow();
5517            }
5518
5519            if (mAdded && !mFirst) {
5520                destroyHardwareRenderer();
5521
5522                if (mView != null) {
5523                    int viewVisibility = mView.getVisibility();
5524                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
5525                    if (mWindowAttributesChanged || viewVisibilityChanged) {
5526                        // If layout params have been changed, first give them
5527                        // to the window manager to make sure it has the correct
5528                        // animation info.
5529                        try {
5530                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5531                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5532                                mWindowSession.finishDrawing(mWindow);
5533                            }
5534                        } catch (RemoteException e) {
5535                        }
5536                    }
5537
5538                    mSurface.release();
5539                }
5540            }
5541
5542            mAdded = false;
5543        }
5544        WindowManagerGlobal.getInstance().doRemoveView(this);
5545    }
5546
5547    public void requestUpdateConfiguration(Configuration config) {
5548        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5549        mHandler.sendMessage(msg);
5550    }
5551
5552    public void loadSystemProperties() {
5553        mHandler.post(new Runnable() {
5554            @Override
5555            public void run() {
5556                // Profiling
5557                mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5558                profileRendering(mAttachInfo.mHasWindowFocus);
5559
5560                // Media (used by sound effects)
5561                mMediaDisabled = SystemProperties.getBoolean(PROPERTY_MEDIA_DISABLED, false);
5562
5563                // Hardware rendering
5564                if (mAttachInfo.mHardwareRenderer != null) {
5565                    if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
5566                        invalidate();
5567                    }
5568                }
5569
5570                // Layout debugging
5571                boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5572                if (layout != mAttachInfo.mDebugLayout) {
5573                    mAttachInfo.mDebugLayout = layout;
5574                    if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5575                        mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5576                    }
5577                }
5578
5579                // detect emulator
5580                mIsEmulator = Build.HARDWARE.contains("goldfish");
5581                mIsCircularEmulator =
5582                        SystemProperties.getBoolean(PROPERTY_EMULATOR_CIRCULAR, false);
5583            }
5584        });
5585    }
5586
5587    private void destroyHardwareRenderer() {
5588        HardwareRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
5589
5590        if (hardwareRenderer != null) {
5591            if (mView != null) {
5592                hardwareRenderer.destroyHardwareResources(mView);
5593            }
5594            hardwareRenderer.destroy();
5595            hardwareRenderer.setRequested(false);
5596
5597            mAttachInfo.mHardwareRenderer = null;
5598            mAttachInfo.mHardwareAccelerated = false;
5599        }
5600    }
5601
5602    public void dispatchFinishInputConnection(InputConnection connection) {
5603        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
5604        mHandler.sendMessage(msg);
5605    }
5606
5607    public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
5608            Rect visibleInsets, Rect stableInsets, boolean reportDraw, Configuration newConfig) {
5609        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
5610                + " contentInsets=" + contentInsets.toShortString()
5611                + " visibleInsets=" + visibleInsets.toShortString()
5612                + " reportDraw=" + reportDraw);
5613        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
5614        if (mTranslator != null) {
5615            mTranslator.translateRectInScreenToAppWindow(frame);
5616            mTranslator.translateRectInScreenToAppWindow(overscanInsets);
5617            mTranslator.translateRectInScreenToAppWindow(contentInsets);
5618            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
5619        }
5620        SomeArgs args = SomeArgs.obtain();
5621        final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5622        args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5623        args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5624        args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5625        args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
5626        args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
5627        args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets;
5628        msg.obj = args;
5629        mHandler.sendMessage(msg);
5630    }
5631
5632    public void dispatchMoved(int newX, int newY) {
5633        if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
5634        if (mTranslator != null) {
5635            PointF point = new PointF(newX, newY);
5636            mTranslator.translatePointInScreenToAppWindow(point);
5637            newX = (int) (point.x + 0.5);
5638            newY = (int) (point.y + 0.5);
5639        }
5640        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5641        mHandler.sendMessage(msg);
5642    }
5643
5644    /**
5645     * Represents a pending input event that is waiting in a queue.
5646     *
5647     * Input events are processed in serial order by the timestamp specified by
5648     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
5649     * one input event to the application at a time and waits for the application
5650     * to finish handling it before delivering the next one.
5651     *
5652     * However, because the application or IME can synthesize and inject multiple
5653     * key events at a time without going through the input dispatcher, we end up
5654     * needing a queue on the application's side.
5655     */
5656    private static final class QueuedInputEvent {
5657        public static final int FLAG_DELIVER_POST_IME = 1 << 0;
5658        public static final int FLAG_DEFERRED = 1 << 1;
5659        public static final int FLAG_FINISHED = 1 << 2;
5660        public static final int FLAG_FINISHED_HANDLED = 1 << 3;
5661        public static final int FLAG_RESYNTHESIZED = 1 << 4;
5662        public static final int FLAG_UNHANDLED = 1 << 5;
5663
5664        public QueuedInputEvent mNext;
5665
5666        public InputEvent mEvent;
5667        public InputEventReceiver mReceiver;
5668        public int mFlags;
5669
5670        public boolean shouldSkipIme() {
5671            if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5672                return true;
5673            }
5674            return mEvent instanceof MotionEvent
5675                    && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5676        }
5677
5678        public boolean shouldSendToSynthesizer() {
5679            if ((mFlags & FLAG_UNHANDLED) != 0) {
5680                return true;
5681            }
5682
5683            return false;
5684        }
5685
5686        @Override
5687        public String toString() {
5688            StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
5689            boolean hasPrevious = false;
5690            hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
5691            hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
5692            hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
5693            hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
5694            hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
5695            hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
5696            if (!hasPrevious) {
5697                sb.append("0");
5698            }
5699            sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
5700            sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
5701            sb.append(", mEvent=" + mEvent + "}");
5702            return sb.toString();
5703        }
5704
5705        private boolean flagToString(String name, int flag,
5706                boolean hasPrevious, StringBuilder sb) {
5707            if ((mFlags & flag) != 0) {
5708                if (hasPrevious) {
5709                    sb.append("|");
5710                }
5711                sb.append(name);
5712                return true;
5713            }
5714            return hasPrevious;
5715        }
5716    }
5717
5718    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
5719            InputEventReceiver receiver, int flags) {
5720        QueuedInputEvent q = mQueuedInputEventPool;
5721        if (q != null) {
5722            mQueuedInputEventPoolSize -= 1;
5723            mQueuedInputEventPool = q.mNext;
5724            q.mNext = null;
5725        } else {
5726            q = new QueuedInputEvent();
5727        }
5728
5729        q.mEvent = event;
5730        q.mReceiver = receiver;
5731        q.mFlags = flags;
5732        return q;
5733    }
5734
5735    private void recycleQueuedInputEvent(QueuedInputEvent q) {
5736        q.mEvent = null;
5737        q.mReceiver = null;
5738
5739        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
5740            mQueuedInputEventPoolSize += 1;
5741            q.mNext = mQueuedInputEventPool;
5742            mQueuedInputEventPool = q;
5743        }
5744    }
5745
5746    void enqueueInputEvent(InputEvent event) {
5747        enqueueInputEvent(event, null, 0, false);
5748    }
5749
5750    void enqueueInputEvent(InputEvent event,
5751            InputEventReceiver receiver, int flags, boolean processImmediately) {
5752        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
5753
5754        // Always enqueue the input event in order, regardless of its time stamp.
5755        // We do this because the application or the IME may inject key events
5756        // in response to touch events and we want to ensure that the injected keys
5757        // are processed in the order they were received and we cannot trust that
5758        // the time stamp of injected events are monotonic.
5759        QueuedInputEvent last = mPendingInputEventTail;
5760        if (last == null) {
5761            mPendingInputEventHead = q;
5762            mPendingInputEventTail = q;
5763        } else {
5764            last.mNext = q;
5765            mPendingInputEventTail = q;
5766        }
5767        mPendingInputEventCount += 1;
5768        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5769                mPendingInputEventCount);
5770
5771        if (processImmediately) {
5772            doProcessInputEvents();
5773        } else {
5774            scheduleProcessInputEvents();
5775        }
5776    }
5777
5778    private void scheduleProcessInputEvents() {
5779        if (!mProcessInputEventsScheduled) {
5780            mProcessInputEventsScheduled = true;
5781            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
5782            msg.setAsynchronous(true);
5783            mHandler.sendMessage(msg);
5784        }
5785    }
5786
5787    void doProcessInputEvents() {
5788        // Deliver all pending input events in the queue.
5789        while (mPendingInputEventHead != null) {
5790            QueuedInputEvent q = mPendingInputEventHead;
5791            mPendingInputEventHead = q.mNext;
5792            if (mPendingInputEventHead == null) {
5793                mPendingInputEventTail = null;
5794            }
5795            q.mNext = null;
5796
5797            mPendingInputEventCount -= 1;
5798            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5799                    mPendingInputEventCount);
5800
5801            deliverInputEvent(q);
5802        }
5803
5804        // We are done processing all input events that we can process right now
5805        // so we can clear the pending flag immediately.
5806        if (mProcessInputEventsScheduled) {
5807            mProcessInputEventsScheduled = false;
5808            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
5809        }
5810    }
5811
5812    private void deliverInputEvent(QueuedInputEvent q) {
5813        Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5814                q.mEvent.getSequenceNumber());
5815        if (mInputEventConsistencyVerifier != null) {
5816            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
5817        }
5818
5819        InputStage stage;
5820        if (q.shouldSendToSynthesizer()) {
5821            stage = mSyntheticInputStage;
5822        } else {
5823            stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
5824        }
5825
5826        if (stage != null) {
5827            stage.deliver(q);
5828        } else {
5829            finishInputEvent(q);
5830        }
5831    }
5832
5833    private void finishInputEvent(QueuedInputEvent q) {
5834        Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5835                q.mEvent.getSequenceNumber());
5836
5837        if (q.mReceiver != null) {
5838            boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
5839            q.mReceiver.finishInputEvent(q.mEvent, handled);
5840        } else {
5841            q.mEvent.recycleIfNeededAfterDispatch();
5842        }
5843
5844        recycleQueuedInputEvent(q);
5845    }
5846
5847    static boolean isTerminalInputEvent(InputEvent event) {
5848        if (event instanceof KeyEvent) {
5849            final KeyEvent keyEvent = (KeyEvent)event;
5850            return keyEvent.getAction() == KeyEvent.ACTION_UP;
5851        } else {
5852            final MotionEvent motionEvent = (MotionEvent)event;
5853            final int action = motionEvent.getAction();
5854            return action == MotionEvent.ACTION_UP
5855                    || action == MotionEvent.ACTION_CANCEL
5856                    || action == MotionEvent.ACTION_HOVER_EXIT;
5857        }
5858    }
5859
5860    void scheduleConsumeBatchedInput() {
5861        if (!mConsumeBatchedInputScheduled) {
5862            mConsumeBatchedInputScheduled = true;
5863            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
5864                    mConsumedBatchedInputRunnable, null);
5865        }
5866    }
5867
5868    void unscheduleConsumeBatchedInput() {
5869        if (mConsumeBatchedInputScheduled) {
5870            mConsumeBatchedInputScheduled = false;
5871            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
5872                    mConsumedBatchedInputRunnable, null);
5873        }
5874    }
5875
5876    void scheduleConsumeBatchedInputImmediately() {
5877        if (!mConsumeBatchedInputImmediatelyScheduled) {
5878            unscheduleConsumeBatchedInput();
5879            mConsumeBatchedInputImmediatelyScheduled = true;
5880            mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
5881        }
5882    }
5883
5884    void doConsumeBatchedInput(long frameTimeNanos) {
5885        if (mConsumeBatchedInputScheduled) {
5886            mConsumeBatchedInputScheduled = false;
5887            if (mInputEventReceiver != null) {
5888                if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
5889                        && frameTimeNanos != -1) {
5890                    // If we consumed a batch here, we want to go ahead and schedule the
5891                    // consumption of batched input events on the next frame. Otherwise, we would
5892                    // wait until we have more input events pending and might get starved by other
5893                    // things occurring in the process. If the frame time is -1, however, then
5894                    // we're in a non-batching mode, so there's no need to schedule this.
5895                    scheduleConsumeBatchedInput();
5896                }
5897            }
5898            doProcessInputEvents();
5899        }
5900    }
5901
5902    final class TraversalRunnable implements Runnable {
5903        @Override
5904        public void run() {
5905            doTraversal();
5906        }
5907    }
5908    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
5909
5910    final class WindowInputEventReceiver extends InputEventReceiver {
5911        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
5912            super(inputChannel, looper);
5913        }
5914
5915        @Override
5916        public void onInputEvent(InputEvent event) {
5917            enqueueInputEvent(event, this, 0, true);
5918        }
5919
5920        @Override
5921        public void onBatchedInputEventPending() {
5922            if (mUnbufferedInputDispatch) {
5923                super.onBatchedInputEventPending();
5924            } else {
5925                scheduleConsumeBatchedInput();
5926            }
5927        }
5928
5929        @Override
5930        public void dispose() {
5931            unscheduleConsumeBatchedInput();
5932            super.dispose();
5933        }
5934    }
5935    WindowInputEventReceiver mInputEventReceiver;
5936
5937    final class ConsumeBatchedInputRunnable implements Runnable {
5938        @Override
5939        public void run() {
5940            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
5941        }
5942    }
5943    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
5944            new ConsumeBatchedInputRunnable();
5945    boolean mConsumeBatchedInputScheduled;
5946
5947    final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
5948        @Override
5949        public void run() {
5950            doConsumeBatchedInput(-1);
5951        }
5952    }
5953    final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
5954            new ConsumeBatchedInputImmediatelyRunnable();
5955    boolean mConsumeBatchedInputImmediatelyScheduled;
5956
5957    final class InvalidateOnAnimationRunnable implements Runnable {
5958        private boolean mPosted;
5959        private final ArrayList<View> mViews = new ArrayList<View>();
5960        private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
5961                new ArrayList<AttachInfo.InvalidateInfo>();
5962        private View[] mTempViews;
5963        private AttachInfo.InvalidateInfo[] mTempViewRects;
5964
5965        public void addView(View view) {
5966            synchronized (this) {
5967                mViews.add(view);
5968                postIfNeededLocked();
5969            }
5970        }
5971
5972        public void addViewRect(AttachInfo.InvalidateInfo info) {
5973            synchronized (this) {
5974                mViewRects.add(info);
5975                postIfNeededLocked();
5976            }
5977        }
5978
5979        public void removeView(View view) {
5980            synchronized (this) {
5981                mViews.remove(view);
5982
5983                for (int i = mViewRects.size(); i-- > 0; ) {
5984                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
5985                    if (info.target == view) {
5986                        mViewRects.remove(i);
5987                        info.recycle();
5988                    }
5989                }
5990
5991                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
5992                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
5993                    mPosted = false;
5994                }
5995            }
5996        }
5997
5998        @Override
5999        public void run() {
6000            final int viewCount;
6001            final int viewRectCount;
6002            synchronized (this) {
6003                mPosted = false;
6004
6005                viewCount = mViews.size();
6006                if (viewCount != 0) {
6007                    mTempViews = mViews.toArray(mTempViews != null
6008                            ? mTempViews : new View[viewCount]);
6009                    mViews.clear();
6010                }
6011
6012                viewRectCount = mViewRects.size();
6013                if (viewRectCount != 0) {
6014                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
6015                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6016                    mViewRects.clear();
6017                }
6018            }
6019
6020            for (int i = 0; i < viewCount; i++) {
6021                mTempViews[i].invalidate();
6022                mTempViews[i] = null;
6023            }
6024
6025            for (int i = 0; i < viewRectCount; i++) {
6026                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
6027                info.target.invalidate(info.left, info.top, info.right, info.bottom);
6028                info.recycle();
6029            }
6030        }
6031
6032        private void postIfNeededLocked() {
6033            if (!mPosted) {
6034                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
6035                mPosted = true;
6036            }
6037        }
6038    }
6039    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6040            new InvalidateOnAnimationRunnable();
6041
6042    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6043        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6044        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6045    }
6046
6047    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
6048            long delayMilliseconds) {
6049        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
6050        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6051    }
6052
6053    public void dispatchInvalidateOnAnimation(View view) {
6054        mInvalidateOnAnimationRunnable.addView(view);
6055    }
6056
6057    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6058        mInvalidateOnAnimationRunnable.addViewRect(info);
6059    }
6060
6061    public void cancelInvalidate(View view) {
6062        mHandler.removeMessages(MSG_INVALIDATE, view);
6063        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6064        // them to the pool
6065        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6066        mInvalidateOnAnimationRunnable.removeView(view);
6067    }
6068
6069    public void dispatchInputEvent(InputEvent event) {
6070        dispatchInputEvent(event, null);
6071    }
6072
6073    public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6074        SomeArgs args = SomeArgs.obtain();
6075        args.arg1 = event;
6076        args.arg2 = receiver;
6077        Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
6078        msg.setAsynchronous(true);
6079        mHandler.sendMessage(msg);
6080    }
6081
6082    public void synthesizeInputEvent(InputEvent event) {
6083        Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6084        msg.setAsynchronous(true);
6085        mHandler.sendMessage(msg);
6086    }
6087
6088    public void dispatchKeyFromIme(KeyEvent event) {
6089        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
6090        msg.setAsynchronous(true);
6091        mHandler.sendMessage(msg);
6092    }
6093
6094    /**
6095     * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6096     *
6097     * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6098     * passes in.
6099     */
6100    public void dispatchUnhandledInputEvent(InputEvent event) {
6101        if (event instanceof MotionEvent) {
6102            event = MotionEvent.obtain((MotionEvent) event);
6103        }
6104        synthesizeInputEvent(event);
6105    }
6106
6107    public void dispatchAppVisibility(boolean visible) {
6108        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
6109        msg.arg1 = visible ? 1 : 0;
6110        mHandler.sendMessage(msg);
6111    }
6112
6113    public void dispatchGetNewSurface() {
6114        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6115        mHandler.sendMessage(msg);
6116    }
6117
6118    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6119        Message msg = Message.obtain();
6120        msg.what = MSG_WINDOW_FOCUS_CHANGED;
6121        msg.arg1 = hasFocus ? 1 : 0;
6122        msg.arg2 = inTouchMode ? 1 : 0;
6123        mHandler.sendMessage(msg);
6124    }
6125
6126    public void dispatchWindowShown() {
6127        mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6128    }
6129
6130    public void dispatchCloseSystemDialogs(String reason) {
6131        Message msg = Message.obtain();
6132        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
6133        msg.obj = reason;
6134        mHandler.sendMessage(msg);
6135    }
6136
6137    public void dispatchDragEvent(DragEvent event) {
6138        final int what;
6139        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
6140            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6141            mHandler.removeMessages(what);
6142        } else {
6143            what = MSG_DISPATCH_DRAG_EVENT;
6144        }
6145        Message msg = mHandler.obtainMessage(what, event);
6146        mHandler.sendMessage(msg);
6147    }
6148
6149    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6150            int localValue, int localChanges) {
6151        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6152        args.seq = seq;
6153        args.globalVisibility = globalVisibility;
6154        args.localValue = localValue;
6155        args.localChanges = localChanges;
6156        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6157    }
6158
6159    public void dispatchDoneAnimating() {
6160        mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
6161    }
6162
6163    public void dispatchCheckFocus() {
6164        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
6165            // This will result in a call to checkFocus() below.
6166            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
6167        }
6168    }
6169
6170    /**
6171     * Post a callback to send a
6172     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6173     * This event is send at most once every
6174     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
6175     */
6176    private void postSendWindowContentChangedCallback(View source, int changeType) {
6177        if (mSendWindowContentChangedAccessibilityEvent == null) {
6178            mSendWindowContentChangedAccessibilityEvent =
6179                new SendWindowContentChangedAccessibilityEvent();
6180        }
6181        mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
6182    }
6183
6184    /**
6185     * Remove a posted callback to send a
6186     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6187     */
6188    private void removeSendWindowContentChangedCallback() {
6189        if (mSendWindowContentChangedAccessibilityEvent != null) {
6190            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
6191        }
6192    }
6193
6194    @Override
6195    public boolean showContextMenuForChild(View originalView) {
6196        return false;
6197    }
6198
6199    @Override
6200    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6201        return null;
6202    }
6203
6204    @Override
6205    public void createContextMenu(ContextMenu menu) {
6206    }
6207
6208    @Override
6209    public void childDrawableStateChanged(View child) {
6210    }
6211
6212    @Override
6213    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
6214        if (mView == null) {
6215            return false;
6216        }
6217        // Intercept accessibility focus events fired by virtual nodes to keep
6218        // track of accessibility focus position in such nodes.
6219        final int eventType = event.getEventType();
6220        switch (eventType) {
6221            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
6222                final long sourceNodeId = event.getSourceNodeId();
6223                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6224                        sourceNodeId);
6225                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6226                if (source != null) {
6227                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6228                    if (provider != null) {
6229                        final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
6230                                sourceNodeId);
6231                        final AccessibilityNodeInfo node;
6232                        if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6233                            node = provider.createAccessibilityNodeInfo(
6234                                    AccessibilityNodeProvider.HOST_VIEW_ID);
6235                        } else {
6236                            node = provider.createAccessibilityNodeInfo(virtualNodeId);
6237                        }
6238                        setAccessibilityFocus(source, node);
6239                    }
6240                }
6241            } break;
6242            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
6243                final long sourceNodeId = event.getSourceNodeId();
6244                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6245                        sourceNodeId);
6246                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6247                if (source != null) {
6248                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6249                    if (provider != null) {
6250                        setAccessibilityFocus(null, null);
6251                    }
6252                }
6253            } break;
6254
6255
6256            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
6257                if (mAccessibilityFocusedHost != null && mAccessibilityFocusedVirtualView != null) {
6258                    // We care only for changes rooted in the focused host.
6259                    final long eventSourceId = event.getSourceNodeId();
6260                    final int hostViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6261                            eventSourceId);
6262                    if (hostViewId != mAccessibilityFocusedHost.getAccessibilityViewId()) {
6263                        break;
6264                    }
6265
6266                    // We only care about changes that may change the virtual focused view bounds.
6267                    final int changes = event.getContentChangeTypes();
6268                    if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) != 0
6269                            || changes == AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
6270                        AccessibilityNodeProvider provider = mAccessibilityFocusedHost
6271                                .getAccessibilityNodeProvider();
6272                        if (provider != null) {
6273                            final int virtualChildId = AccessibilityNodeInfo.getVirtualDescendantId(
6274                                    mAccessibilityFocusedVirtualView.getSourceNodeId());
6275                            if (virtualChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6276                                mAccessibilityFocusedVirtualView = provider
6277                                        .createAccessibilityNodeInfo(
6278                                                AccessibilityNodeProvider.HOST_VIEW_ID);
6279                            } else {
6280                                mAccessibilityFocusedVirtualView = provider
6281                                        .createAccessibilityNodeInfo(virtualChildId);
6282                            }
6283                        }
6284                    }
6285                }
6286            } break;
6287        }
6288        mAccessibilityManager.sendAccessibilityEvent(event);
6289        return true;
6290    }
6291
6292    @Override
6293    public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6294        postSendWindowContentChangedCallback(source, changeType);
6295    }
6296
6297    @Override
6298    public boolean canResolveLayoutDirection() {
6299        return true;
6300    }
6301
6302    @Override
6303    public boolean isLayoutDirectionResolved() {
6304        return true;
6305    }
6306
6307    @Override
6308    public int getLayoutDirection() {
6309        return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6310    }
6311
6312    @Override
6313    public boolean canResolveTextDirection() {
6314        return true;
6315    }
6316
6317    @Override
6318    public boolean isTextDirectionResolved() {
6319        return true;
6320    }
6321
6322    @Override
6323    public int getTextDirection() {
6324        return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6325    }
6326
6327    @Override
6328    public boolean canResolveTextAlignment() {
6329        return true;
6330    }
6331
6332    @Override
6333    public boolean isTextAlignmentResolved() {
6334        return true;
6335    }
6336
6337    @Override
6338    public int getTextAlignment() {
6339        return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6340    }
6341
6342    private View getCommonPredecessor(View first, View second) {
6343        if (mTempHashSet == null) {
6344            mTempHashSet = new HashSet<View>();
6345        }
6346        HashSet<View> seen = mTempHashSet;
6347        seen.clear();
6348        View firstCurrent = first;
6349        while (firstCurrent != null) {
6350            seen.add(firstCurrent);
6351            ViewParent firstCurrentParent = firstCurrent.mParent;
6352            if (firstCurrentParent instanceof View) {
6353                firstCurrent = (View) firstCurrentParent;
6354            } else {
6355                firstCurrent = null;
6356            }
6357        }
6358        View secondCurrent = second;
6359        while (secondCurrent != null) {
6360            if (seen.contains(secondCurrent)) {
6361                seen.clear();
6362                return secondCurrent;
6363            }
6364            ViewParent secondCurrentParent = secondCurrent.mParent;
6365            if (secondCurrentParent instanceof View) {
6366                secondCurrent = (View) secondCurrentParent;
6367            } else {
6368                secondCurrent = null;
6369            }
6370        }
6371        seen.clear();
6372        return null;
6373    }
6374
6375    void checkThread() {
6376        if (mThread != Thread.currentThread()) {
6377            throw new CalledFromWrongThreadException(
6378                    "Only the original thread that created a view hierarchy can touch its views.");
6379        }
6380    }
6381
6382    @Override
6383    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
6384        // ViewAncestor never intercepts touch event, so this can be a no-op
6385    }
6386
6387    @Override
6388    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
6389        final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
6390        if (rectangle != null) {
6391            mTempRect.set(rectangle);
6392            mTempRect.offset(0, -mCurScrollY);
6393            mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6394            try {
6395                mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6396            } catch (RemoteException re) {
6397                /* ignore */
6398            }
6399        }
6400        return scrolled;
6401    }
6402
6403    @Override
6404    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6405        // Do nothing.
6406    }
6407
6408    @Override
6409    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6410        return false;
6411    }
6412
6413    @Override
6414    public void onStopNestedScroll(View target) {
6415    }
6416
6417    @Override
6418    public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6419    }
6420
6421    @Override
6422    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6423            int dxUnconsumed, int dyUnconsumed) {
6424    }
6425
6426    @Override
6427    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6428    }
6429
6430    @Override
6431    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6432        return false;
6433    }
6434
6435    @Override
6436    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6437        return false;
6438    }
6439
6440    @Override
6441    public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6442        return false;
6443    }
6444
6445    void changeCanvasOpacity(boolean opaque) {
6446        Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque);
6447        if (mAttachInfo.mHardwareRenderer != null) {
6448            mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6449        }
6450    }
6451
6452    class TakenSurfaceHolder extends BaseSurfaceHolder {
6453        @Override
6454        public boolean onAllowLockCanvas() {
6455            return mDrawingAllowed;
6456        }
6457
6458        @Override
6459        public void onRelayoutContainer() {
6460            // Not currently interesting -- from changing between fixed and layout size.
6461        }
6462
6463        @Override
6464        public void setFormat(int format) {
6465            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6466        }
6467
6468        @Override
6469        public void setType(int type) {
6470            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6471        }
6472
6473        @Override
6474        public void onUpdateSurface() {
6475            // We take care of format and type changes on our own.
6476            throw new IllegalStateException("Shouldn't be here");
6477        }
6478
6479        @Override
6480        public boolean isCreating() {
6481            return mIsCreating;
6482        }
6483
6484        @Override
6485        public void setFixedSize(int width, int height) {
6486            throw new UnsupportedOperationException(
6487                    "Currently only support sizing from layout");
6488        }
6489
6490        @Override
6491        public void setKeepScreenOn(boolean screenOn) {
6492            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6493        }
6494    }
6495
6496    static class W extends IWindow.Stub {
6497        private final WeakReference<ViewRootImpl> mViewAncestor;
6498        private final IWindowSession mWindowSession;
6499
6500        W(ViewRootImpl viewAncestor) {
6501            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
6502            mWindowSession = viewAncestor.mWindowSession;
6503        }
6504
6505        @Override
6506        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
6507                Rect visibleInsets, Rect stableInsets, boolean reportDraw,
6508                Configuration newConfig) {
6509            final ViewRootImpl viewAncestor = mViewAncestor.get();
6510            if (viewAncestor != null) {
6511                viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
6512                        visibleInsets, stableInsets, reportDraw, newConfig);
6513            }
6514        }
6515
6516        @Override
6517        public void moved(int newX, int newY) {
6518            final ViewRootImpl viewAncestor = mViewAncestor.get();
6519            if (viewAncestor != null) {
6520                viewAncestor.dispatchMoved(newX, newY);
6521            }
6522        }
6523
6524        @Override
6525        public void dispatchAppVisibility(boolean visible) {
6526            final ViewRootImpl viewAncestor = mViewAncestor.get();
6527            if (viewAncestor != null) {
6528                viewAncestor.dispatchAppVisibility(visible);
6529            }
6530        }
6531
6532        @Override
6533        public void dispatchGetNewSurface() {
6534            final ViewRootImpl viewAncestor = mViewAncestor.get();
6535            if (viewAncestor != null) {
6536                viewAncestor.dispatchGetNewSurface();
6537            }
6538        }
6539
6540        @Override
6541        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6542            final ViewRootImpl viewAncestor = mViewAncestor.get();
6543            if (viewAncestor != null) {
6544                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
6545            }
6546        }
6547
6548        private static int checkCallingPermission(String permission) {
6549            try {
6550                return ActivityManagerNative.getDefault().checkPermission(
6551                        permission, Binder.getCallingPid(), Binder.getCallingUid());
6552            } catch (RemoteException e) {
6553                return PackageManager.PERMISSION_DENIED;
6554            }
6555        }
6556
6557        @Override
6558        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
6559            final ViewRootImpl viewAncestor = mViewAncestor.get();
6560            if (viewAncestor != null) {
6561                final View view = viewAncestor.mView;
6562                if (view != null) {
6563                    if (checkCallingPermission(Manifest.permission.DUMP) !=
6564                            PackageManager.PERMISSION_GRANTED) {
6565                        throw new SecurityException("Insufficient permissions to invoke"
6566                                + " executeCommand() from pid=" + Binder.getCallingPid()
6567                                + ", uid=" + Binder.getCallingUid());
6568                    }
6569
6570                    OutputStream clientStream = null;
6571                    try {
6572                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
6573                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
6574                    } catch (IOException e) {
6575                        e.printStackTrace();
6576                    } finally {
6577                        if (clientStream != null) {
6578                            try {
6579                                clientStream.close();
6580                            } catch (IOException e) {
6581                                e.printStackTrace();
6582                            }
6583                        }
6584                    }
6585                }
6586            }
6587        }
6588
6589        @Override
6590        public void closeSystemDialogs(String reason) {
6591            final ViewRootImpl viewAncestor = mViewAncestor.get();
6592            if (viewAncestor != null) {
6593                viewAncestor.dispatchCloseSystemDialogs(reason);
6594            }
6595        }
6596
6597        @Override
6598        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
6599                boolean sync) {
6600            if (sync) {
6601                try {
6602                    mWindowSession.wallpaperOffsetsComplete(asBinder());
6603                } catch (RemoteException e) {
6604                }
6605            }
6606        }
6607
6608        @Override
6609        public void dispatchWallpaperCommand(String action, int x, int y,
6610                int z, Bundle extras, boolean sync) {
6611            if (sync) {
6612                try {
6613                    mWindowSession.wallpaperCommandComplete(asBinder(), null);
6614                } catch (RemoteException e) {
6615                }
6616            }
6617        }
6618
6619        /* Drag/drop */
6620        @Override
6621        public void dispatchDragEvent(DragEvent event) {
6622            final ViewRootImpl viewAncestor = mViewAncestor.get();
6623            if (viewAncestor != null) {
6624                viewAncestor.dispatchDragEvent(event);
6625            }
6626        }
6627
6628        @Override
6629        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6630                int localValue, int localChanges) {
6631            final ViewRootImpl viewAncestor = mViewAncestor.get();
6632            if (viewAncestor != null) {
6633                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
6634                        localValue, localChanges);
6635            }
6636        }
6637
6638        @Override
6639        public void doneAnimating() {
6640            final ViewRootImpl viewAncestor = mViewAncestor.get();
6641            if (viewAncestor != null) {
6642                viewAncestor.dispatchDoneAnimating();
6643            }
6644        }
6645
6646        @Override
6647        public void dispatchWindowShown() {
6648            final ViewRootImpl viewAncestor = mViewAncestor.get();
6649            if (viewAncestor != null) {
6650                viewAncestor.dispatchWindowShown();
6651            }
6652        }
6653    }
6654
6655    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
6656        public CalledFromWrongThreadException(String msg) {
6657            super(msg);
6658        }
6659    }
6660
6661    static RunQueue getRunQueue() {
6662        RunQueue rq = sRunQueues.get();
6663        if (rq != null) {
6664            return rq;
6665        }
6666        rq = new RunQueue();
6667        sRunQueues.set(rq);
6668        return rq;
6669    }
6670
6671    /**
6672     * The run queue is used to enqueue pending work from Views when no Handler is
6673     * attached.  The work is executed during the next call to performTraversals on
6674     * the thread.
6675     * @hide
6676     */
6677    static final class RunQueue {
6678        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
6679
6680        void post(Runnable action) {
6681            postDelayed(action, 0);
6682        }
6683
6684        void postDelayed(Runnable action, long delayMillis) {
6685            HandlerAction handlerAction = new HandlerAction();
6686            handlerAction.action = action;
6687            handlerAction.delay = delayMillis;
6688
6689            synchronized (mActions) {
6690                mActions.add(handlerAction);
6691            }
6692        }
6693
6694        void removeCallbacks(Runnable action) {
6695            final HandlerAction handlerAction = new HandlerAction();
6696            handlerAction.action = action;
6697
6698            synchronized (mActions) {
6699                final ArrayList<HandlerAction> actions = mActions;
6700
6701                while (actions.remove(handlerAction)) {
6702                    // Keep going
6703                }
6704            }
6705        }
6706
6707        void executeActions(Handler handler) {
6708            synchronized (mActions) {
6709                final ArrayList<HandlerAction> actions = mActions;
6710                final int count = actions.size();
6711
6712                for (int i = 0; i < count; i++) {
6713                    final HandlerAction handlerAction = actions.get(i);
6714                    handler.postDelayed(handlerAction.action, handlerAction.delay);
6715                }
6716
6717                actions.clear();
6718            }
6719        }
6720
6721        private static class HandlerAction {
6722            Runnable action;
6723            long delay;
6724
6725            @Override
6726            public boolean equals(Object o) {
6727                if (this == o) return true;
6728                if (o == null || getClass() != o.getClass()) return false;
6729
6730                HandlerAction that = (HandlerAction) o;
6731                return !(action != null ? !action.equals(that.action) : that.action != null);
6732
6733            }
6734
6735            @Override
6736            public int hashCode() {
6737                int result = action != null ? action.hashCode() : 0;
6738                result = 31 * result + (int) (delay ^ (delay >>> 32));
6739                return result;
6740            }
6741        }
6742    }
6743
6744    /**
6745     * Class for managing the accessibility interaction connection
6746     * based on the global accessibility state.
6747     */
6748    final class AccessibilityInteractionConnectionManager
6749            implements AccessibilityStateChangeListener {
6750        @Override
6751        public void onAccessibilityStateChanged(boolean enabled) {
6752            if (enabled) {
6753                ensureConnection();
6754                if (mAttachInfo.mHasWindowFocus) {
6755                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
6756                    View focusedView = mView.findFocus();
6757                    if (focusedView != null && focusedView != mView) {
6758                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6759                    }
6760                }
6761            } else {
6762                ensureNoConnection();
6763                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
6764            }
6765        }
6766
6767        public void ensureConnection() {
6768            final boolean registered =
6769                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6770            if (!registered) {
6771                mAttachInfo.mAccessibilityWindowId =
6772                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
6773                                new AccessibilityInteractionConnection(ViewRootImpl.this));
6774            }
6775        }
6776
6777        public void ensureNoConnection() {
6778            final boolean registered =
6779                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6780            if (registered) {
6781                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6782                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
6783            }
6784        }
6785    }
6786
6787    final class HighContrastTextManager implements HighTextContrastChangeListener {
6788        HighContrastTextManager() {
6789            mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
6790        }
6791        @Override
6792        public void onHighTextContrastStateChanged(boolean enabled) {
6793            mAttachInfo.mHighContrastText = enabled;
6794
6795            // Destroy Displaylists so they can be recreated with high contrast recordings
6796            destroyHardwareResources();
6797
6798            // Schedule redraw, which will rerecord + redraw all text
6799            invalidate();
6800        }
6801    }
6802
6803    /**
6804     * This class is an interface this ViewAncestor provides to the
6805     * AccessibilityManagerService to the latter can interact with
6806     * the view hierarchy in this ViewAncestor.
6807     */
6808    static final class AccessibilityInteractionConnection
6809            extends IAccessibilityInteractionConnection.Stub {
6810        private final WeakReference<ViewRootImpl> mViewRootImpl;
6811
6812        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
6813            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
6814        }
6815
6816        @Override
6817        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
6818                Region interactiveRegion, int interactionId,
6819                IAccessibilityInteractionConnectionCallback callback, int flags,
6820                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6821            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6822            if (viewRootImpl != null && viewRootImpl.mView != null) {
6823                viewRootImpl.getAccessibilityInteractionController()
6824                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
6825                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
6826                            interrogatingTid, spec);
6827            } else {
6828                // We cannot make the call and notify the caller so it does not wait.
6829                try {
6830                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6831                } catch (RemoteException re) {
6832                    /* best effort - ignore */
6833                }
6834            }
6835        }
6836
6837        @Override
6838        public void performAccessibilityAction(long accessibilityNodeId, int action,
6839                Bundle arguments, int interactionId,
6840                IAccessibilityInteractionConnectionCallback callback, int flags,
6841                int interrogatingPid, long interrogatingTid) {
6842            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6843            if (viewRootImpl != null && viewRootImpl.mView != null) {
6844                viewRootImpl.getAccessibilityInteractionController()
6845                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
6846                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
6847            } else {
6848                // We cannot make the call and notify the caller so it does not wait.
6849                try {
6850                    callback.setPerformAccessibilityActionResult(false, interactionId);
6851                } catch (RemoteException re) {
6852                    /* best effort - ignore */
6853                }
6854            }
6855        }
6856
6857        @Override
6858        public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
6859                String viewId, Region interactiveRegion, int interactionId,
6860                IAccessibilityInteractionConnectionCallback callback, int flags,
6861                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6862            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6863            if (viewRootImpl != null && viewRootImpl.mView != null) {
6864                viewRootImpl.getAccessibilityInteractionController()
6865                    .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
6866                            viewId, interactiveRegion, interactionId, callback, flags,
6867                            interrogatingPid, interrogatingTid, spec);
6868            } else {
6869                // We cannot make the call and notify the caller so it does not wait.
6870                try {
6871                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6872                } catch (RemoteException re) {
6873                    /* best effort - ignore */
6874                }
6875            }
6876        }
6877
6878        @Override
6879        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
6880                Region interactiveRegion, int interactionId,
6881                IAccessibilityInteractionConnectionCallback callback, int flags,
6882                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6883            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6884            if (viewRootImpl != null && viewRootImpl.mView != null) {
6885                viewRootImpl.getAccessibilityInteractionController()
6886                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
6887                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
6888                            interrogatingTid, spec);
6889            } else {
6890                // We cannot make the call and notify the caller so it does not wait.
6891                try {
6892                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6893                } catch (RemoteException re) {
6894                    /* best effort - ignore */
6895                }
6896            }
6897        }
6898
6899        @Override
6900        public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
6901                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6902                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6903            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6904            if (viewRootImpl != null && viewRootImpl.mView != null) {
6905                viewRootImpl.getAccessibilityInteractionController()
6906                    .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
6907                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
6908                            spec);
6909            } else {
6910                // We cannot make the call and notify the caller so it does not wait.
6911                try {
6912                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6913                } catch (RemoteException re) {
6914                    /* best effort - ignore */
6915                }
6916            }
6917        }
6918
6919        @Override
6920        public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
6921                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6922                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6923            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6924            if (viewRootImpl != null && viewRootImpl.mView != null) {
6925                viewRootImpl.getAccessibilityInteractionController()
6926                    .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
6927                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
6928                            spec);
6929            } else {
6930                // We cannot make the call and notify the caller so it does not wait.
6931                try {
6932                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6933                } catch (RemoteException re) {
6934                    /* best effort - ignore */
6935                }
6936            }
6937        }
6938    }
6939
6940    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
6941        private int mChangeTypes = 0;
6942
6943        public View mSource;
6944        public long mLastEventTimeMillis;
6945
6946        @Override
6947        public void run() {
6948            // The accessibility may be turned off while we were waiting so check again.
6949            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6950                mLastEventTimeMillis = SystemClock.uptimeMillis();
6951                AccessibilityEvent event = AccessibilityEvent.obtain();
6952                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
6953                event.setContentChangeTypes(mChangeTypes);
6954                mSource.sendAccessibilityEventUnchecked(event);
6955            } else {
6956                mLastEventTimeMillis = 0;
6957            }
6958            // In any case reset to initial state.
6959            mSource.resetSubtreeAccessibilityStateChanged();
6960            mSource = null;
6961            mChangeTypes = 0;
6962        }
6963
6964        public void runOrPost(View source, int changeType) {
6965            if (mSource != null) {
6966                // If there is no common predecessor, then mSource points to
6967                // a removed view, hence in this case always prefer the source.
6968                View predecessor = getCommonPredecessor(mSource, source);
6969                mSource = (predecessor != null) ? predecessor : source;
6970                mChangeTypes |= changeType;
6971                return;
6972            }
6973            mSource = source;
6974            mChangeTypes = changeType;
6975            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
6976            final long minEventIntevalMillis =
6977                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
6978            if (timeSinceLastMillis >= minEventIntevalMillis) {
6979                mSource.removeCallbacks(this);
6980                run();
6981            } else {
6982                mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
6983            }
6984        }
6985    }
6986}
6987