ViewRootImpl.java revision a7bb6fbeab933326d58aa806d8194b7b13239d34
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 (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4138                mUnbufferedInputDispatch = true;
4139                if (mConsumeBatchedInputScheduled) {
4140                    scheduleConsumeBatchedInputImmediately();
4141                }
4142            }
4143            return handled ? FINISH_HANDLED : FORWARD;
4144        }
4145
4146        private int processTrackballEvent(QueuedInputEvent q) {
4147            final MotionEvent event = (MotionEvent)q.mEvent;
4148
4149            if (mView.dispatchTrackballEvent(event)) {
4150                return FINISH_HANDLED;
4151            }
4152            return FORWARD;
4153        }
4154
4155        private int processGenericMotionEvent(QueuedInputEvent q) {
4156            final MotionEvent event = (MotionEvent)q.mEvent;
4157
4158            // Deliver the event to the view.
4159            if (mView.dispatchGenericMotionEvent(event)) {
4160                return FINISH_HANDLED;
4161            }
4162            return FORWARD;
4163        }
4164    }
4165
4166    /**
4167     * Performs synthesis of new input events from unhandled input events.
4168     */
4169    final class SyntheticInputStage extends InputStage {
4170        private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
4171        private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
4172        private final SyntheticTouchNavigationHandler mTouchNavigation =
4173                new SyntheticTouchNavigationHandler();
4174        private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
4175
4176        public SyntheticInputStage() {
4177            super(null);
4178        }
4179
4180        @Override
4181        protected int onProcess(QueuedInputEvent q) {
4182            q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
4183            if (q.mEvent instanceof MotionEvent) {
4184                final MotionEvent event = (MotionEvent)q.mEvent;
4185                final int source = event.getSource();
4186                if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4187                    mTrackball.process(event);
4188                    return FINISH_HANDLED;
4189                } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4190                    mJoystick.process(event);
4191                    return FINISH_HANDLED;
4192                } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4193                        == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4194                    mTouchNavigation.process(event);
4195                    return FINISH_HANDLED;
4196                }
4197            } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4198                mKeyboard.process((KeyEvent)q.mEvent);
4199                return FINISH_HANDLED;
4200            }
4201
4202            return FORWARD;
4203        }
4204
4205        @Override
4206        protected void onDeliverToNext(QueuedInputEvent q) {
4207            if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
4208                // Cancel related synthetic events if any prior stage has handled the event.
4209                if (q.mEvent instanceof MotionEvent) {
4210                    final MotionEvent event = (MotionEvent)q.mEvent;
4211                    final int source = event.getSource();
4212                    if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4213                        mTrackball.cancel(event);
4214                    } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4215                        mJoystick.cancel(event);
4216                    } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4217                            == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4218                        mTouchNavigation.cancel(event);
4219                    }
4220                }
4221            }
4222            super.onDeliverToNext(q);
4223        }
4224    }
4225
4226    /**
4227     * Creates dpad events from unhandled trackball movements.
4228     */
4229    final class SyntheticTrackballHandler {
4230        private final TrackballAxis mX = new TrackballAxis();
4231        private final TrackballAxis mY = new TrackballAxis();
4232        private long mLastTime;
4233
4234        public void process(MotionEvent event) {
4235            // Translate the trackball event into DPAD keys and try to deliver those.
4236            long curTime = SystemClock.uptimeMillis();
4237            if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
4238                // It has been too long since the last movement,
4239                // so restart at the beginning.
4240                mX.reset(0);
4241                mY.reset(0);
4242                mLastTime = curTime;
4243            }
4244
4245            final int action = event.getAction();
4246            final int metaState = event.getMetaState();
4247            switch (action) {
4248                case MotionEvent.ACTION_DOWN:
4249                    mX.reset(2);
4250                    mY.reset(2);
4251                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4252                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4253                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4254                            InputDevice.SOURCE_KEYBOARD));
4255                    break;
4256                case MotionEvent.ACTION_UP:
4257                    mX.reset(2);
4258                    mY.reset(2);
4259                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4260                            KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4261                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4262                            InputDevice.SOURCE_KEYBOARD));
4263                    break;
4264            }
4265
4266            if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step="
4267                    + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
4268                    + " move=" + event.getX()
4269                    + " / Y=" + mY.position + " step="
4270                    + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
4271                    + " move=" + event.getY());
4272            final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
4273            final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
4274
4275            // Generate DPAD events based on the trackball movement.
4276            // We pick the axis that has moved the most as the direction of
4277            // the DPAD.  When we generate DPAD events for one axis, then the
4278            // other axis is reset -- we don't want to perform DPAD jumps due
4279            // to slight movements in the trackball when making major movements
4280            // along the other axis.
4281            int keycode = 0;
4282            int movement = 0;
4283            float accel = 1;
4284            if (xOff > yOff) {
4285                movement = mX.generate();
4286                if (movement != 0) {
4287                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
4288                            : KeyEvent.KEYCODE_DPAD_LEFT;
4289                    accel = mX.acceleration;
4290                    mY.reset(2);
4291                }
4292            } else if (yOff > 0) {
4293                movement = mY.generate();
4294                if (movement != 0) {
4295                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
4296                            : KeyEvent.KEYCODE_DPAD_UP;
4297                    accel = mY.acceleration;
4298                    mX.reset(2);
4299                }
4300            }
4301
4302            if (keycode != 0) {
4303                if (movement < 0) movement = -movement;
4304                int accelMovement = (int)(movement * accel);
4305                if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
4306                        + " accelMovement=" + accelMovement
4307                        + " accel=" + accel);
4308                if (accelMovement > movement) {
4309                    if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4310                            + keycode);
4311                    movement--;
4312                    int repeatCount = accelMovement - movement;
4313                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4314                            KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
4315                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4316                            InputDevice.SOURCE_KEYBOARD));
4317                }
4318                while (movement > 0) {
4319                    if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4320                            + keycode);
4321                    movement--;
4322                    curTime = SystemClock.uptimeMillis();
4323                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4324                            KeyEvent.ACTION_DOWN, keycode, 0, metaState,
4325                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4326                            InputDevice.SOURCE_KEYBOARD));
4327                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4328                            KeyEvent.ACTION_UP, keycode, 0, metaState,
4329                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4330                            InputDevice.SOURCE_KEYBOARD));
4331                }
4332                mLastTime = curTime;
4333            }
4334        }
4335
4336        public void cancel(MotionEvent event) {
4337            mLastTime = Integer.MIN_VALUE;
4338
4339            // If we reach this, we consumed a trackball event.
4340            // Because we will not translate the trackball event into a key event,
4341            // touch mode will not exit, so we exit touch mode here.
4342            if (mView != null && mAdded) {
4343                ensureTouchMode(false);
4344            }
4345        }
4346    }
4347
4348    /**
4349     * Maintains state information for a single trackball axis, generating
4350     * discrete (DPAD) movements based on raw trackball motion.
4351     */
4352    static final class TrackballAxis {
4353        /**
4354         * The maximum amount of acceleration we will apply.
4355         */
4356        static final float MAX_ACCELERATION = 20;
4357
4358        /**
4359         * The maximum amount of time (in milliseconds) between events in order
4360         * for us to consider the user to be doing fast trackball movements,
4361         * and thus apply an acceleration.
4362         */
4363        static final long FAST_MOVE_TIME = 150;
4364
4365        /**
4366         * Scaling factor to the time (in milliseconds) between events to how
4367         * much to multiple/divide the current acceleration.  When movement
4368         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4369         * FAST_MOVE_TIME it divides it.
4370         */
4371        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4372
4373        static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
4374        static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
4375        static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
4376
4377        float position;
4378        float acceleration = 1;
4379        long lastMoveTime = 0;
4380        int step;
4381        int dir;
4382        int nonAccelMovement;
4383
4384        void reset(int _step) {
4385            position = 0;
4386            acceleration = 1;
4387            lastMoveTime = 0;
4388            step = _step;
4389            dir = 0;
4390        }
4391
4392        /**
4393         * Add trackball movement into the state.  If the direction of movement
4394         * has been reversed, the state is reset before adding the
4395         * movement (so that you don't have to compensate for any previously
4396         * collected movement before see the result of the movement in the
4397         * new direction).
4398         *
4399         * @return Returns the absolute value of the amount of movement
4400         * collected so far.
4401         */
4402        float collect(float off, long time, String axis) {
4403            long normTime;
4404            if (off > 0) {
4405                normTime = (long)(off * FAST_MOVE_TIME);
4406                if (dir < 0) {
4407                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4408                    position = 0;
4409                    step = 0;
4410                    acceleration = 1;
4411                    lastMoveTime = 0;
4412                }
4413                dir = 1;
4414            } else if (off < 0) {
4415                normTime = (long)((-off) * FAST_MOVE_TIME);
4416                if (dir > 0) {
4417                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4418                    position = 0;
4419                    step = 0;
4420                    acceleration = 1;
4421                    lastMoveTime = 0;
4422                }
4423                dir = -1;
4424            } else {
4425                normTime = 0;
4426            }
4427
4428            // The number of milliseconds between each movement that is
4429            // considered "normal" and will not result in any acceleration
4430            // or deceleration, scaled by the offset we have here.
4431            if (normTime > 0) {
4432                long delta = time - lastMoveTime;
4433                lastMoveTime = time;
4434                float acc = acceleration;
4435                if (delta < normTime) {
4436                    // The user is scrolling rapidly, so increase acceleration.
4437                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4438                    if (scale > 1) acc *= scale;
4439                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4440                            + off + " normTime=" + normTime + " delta=" + delta
4441                            + " scale=" + scale + " acc=" + acc);
4442                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4443                } else {
4444                    // The user is scrolling slowly, so decrease acceleration.
4445                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4446                    if (scale > 1) acc /= scale;
4447                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4448                            + off + " normTime=" + normTime + " delta=" + delta
4449                            + " scale=" + scale + " acc=" + acc);
4450                    acceleration = acc > 1 ? acc : 1;
4451                }
4452            }
4453            position += off;
4454            return Math.abs(position);
4455        }
4456
4457        /**
4458         * Generate the number of discrete movement events appropriate for
4459         * the currently collected trackball movement.
4460         *
4461         * @return Returns the number of discrete movements, either positive
4462         * or negative, or 0 if there is not enough trackball movement yet
4463         * for a discrete movement.
4464         */
4465        int generate() {
4466            int movement = 0;
4467            nonAccelMovement = 0;
4468            do {
4469                final int dir = position >= 0 ? 1 : -1;
4470                switch (step) {
4471                    // If we are going to execute the first step, then we want
4472                    // to do this as soon as possible instead of waiting for
4473                    // a full movement, in order to make things look responsive.
4474                    case 0:
4475                        if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4476                            return movement;
4477                        }
4478                        movement += dir;
4479                        nonAccelMovement += dir;
4480                        step = 1;
4481                        break;
4482                    // If we have generated the first movement, then we need
4483                    // to wait for the second complete trackball motion before
4484                    // generating the second discrete movement.
4485                    case 1:
4486                        if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4487                            return movement;
4488                        }
4489                        movement += dir;
4490                        nonAccelMovement += dir;
4491                        position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
4492                        step = 2;
4493                        break;
4494                    // After the first two, we generate discrete movements
4495                    // consistently with the trackball, applying an acceleration
4496                    // if the trackball is moving quickly.  This is a simple
4497                    // acceleration on top of what we already compute based
4498                    // on how quickly the wheel is being turned, to apply
4499                    // a longer increasing acceleration to continuous movement
4500                    // in one direction.
4501                    default:
4502                        if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4503                            return movement;
4504                        }
4505                        movement += dir;
4506                        position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4507                        float acc = acceleration;
4508                        acc *= 1.1f;
4509                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4510                        break;
4511                }
4512            } while (true);
4513        }
4514    }
4515
4516    /**
4517     * Creates dpad events from unhandled joystick movements.
4518     */
4519    final class SyntheticJoystickHandler extends Handler {
4520        private final static String TAG = "SyntheticJoystickHandler";
4521        private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
4522        private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
4523
4524        private int mLastXDirection;
4525        private int mLastYDirection;
4526        private int mLastXKeyCode;
4527        private int mLastYKeyCode;
4528
4529        public SyntheticJoystickHandler() {
4530            super(true);
4531        }
4532
4533        @Override
4534        public void handleMessage(Message msg) {
4535            switch (msg.what) {
4536                case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
4537                case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
4538                    KeyEvent oldEvent = (KeyEvent)msg.obj;
4539                    KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
4540                            SystemClock.uptimeMillis(),
4541                            oldEvent.getRepeatCount() + 1);
4542                    if (mAttachInfo.mHasWindowFocus) {
4543                        enqueueInputEvent(e);
4544                        Message m = obtainMessage(msg.what, e);
4545                        m.setAsynchronous(true);
4546                        sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
4547                    }
4548                } break;
4549            }
4550        }
4551
4552        public void process(MotionEvent event) {
4553            switch(event.getActionMasked()) {
4554            case MotionEvent.ACTION_CANCEL:
4555                cancel(event);
4556                break;
4557            case MotionEvent.ACTION_MOVE:
4558                update(event, true);
4559                break;
4560            default:
4561                Log.w(TAG, "Unexpected action: " + event.getActionMasked());
4562            }
4563        }
4564
4565        private void cancel(MotionEvent event) {
4566            removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4567            removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4568            update(event, false);
4569        }
4570
4571        private void update(MotionEvent event, boolean synthesizeNewKeys) {
4572            final long time = event.getEventTime();
4573            final int metaState = event.getMetaState();
4574            final int deviceId = event.getDeviceId();
4575            final int source = event.getSource();
4576
4577            int xDirection = joystickAxisValueToDirection(
4578                    event.getAxisValue(MotionEvent.AXIS_HAT_X));
4579            if (xDirection == 0) {
4580                xDirection = joystickAxisValueToDirection(event.getX());
4581            }
4582
4583            int yDirection = joystickAxisValueToDirection(
4584                    event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4585            if (yDirection == 0) {
4586                yDirection = joystickAxisValueToDirection(event.getY());
4587            }
4588
4589            if (xDirection != mLastXDirection) {
4590                if (mLastXKeyCode != 0) {
4591                    removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4592                    enqueueInputEvent(new KeyEvent(time, time,
4593                            KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState,
4594                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4595                    mLastXKeyCode = 0;
4596                }
4597
4598                mLastXDirection = xDirection;
4599
4600                if (xDirection != 0 && synthesizeNewKeys) {
4601                    mLastXKeyCode = xDirection > 0
4602                            ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
4603                    final KeyEvent e = new KeyEvent(time, time,
4604                            KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState,
4605                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4606                    enqueueInputEvent(e);
4607                    Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
4608                    m.setAsynchronous(true);
4609                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4610                }
4611            }
4612
4613            if (yDirection != mLastYDirection) {
4614                if (mLastYKeyCode != 0) {
4615                    removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4616                    enqueueInputEvent(new KeyEvent(time, time,
4617                            KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState,
4618                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4619                    mLastYKeyCode = 0;
4620                }
4621
4622                mLastYDirection = yDirection;
4623
4624                if (yDirection != 0 && synthesizeNewKeys) {
4625                    mLastYKeyCode = yDirection > 0
4626                            ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
4627                    final KeyEvent e = new KeyEvent(time, time,
4628                            KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState,
4629                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4630                    enqueueInputEvent(e);
4631                    Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e);
4632                    m.setAsynchronous(true);
4633                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4634                }
4635            }
4636        }
4637
4638        private int joystickAxisValueToDirection(float value) {
4639            if (value >= 0.5f) {
4640                return 1;
4641            } else if (value <= -0.5f) {
4642                return -1;
4643            } else {
4644                return 0;
4645            }
4646        }
4647    }
4648
4649    /**
4650     * Creates dpad events from unhandled touch navigation movements.
4651     */
4652    final class SyntheticTouchNavigationHandler extends Handler {
4653        private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4654        private static final boolean LOCAL_DEBUG = false;
4655
4656        // Assumed nominal width and height in millimeters of a touch navigation pad,
4657        // if no resolution information is available from the input system.
4658        private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
4659        private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
4660
4661        /* TODO: These constants should eventually be moved to ViewConfiguration. */
4662
4663        // The nominal distance traveled to move by one unit.
4664        private static final int TICK_DISTANCE_MILLIMETERS = 12;
4665
4666        // Minimum and maximum fling velocity in ticks per second.
4667        // The minimum velocity should be set such that we perform enough ticks per
4668        // second that the fling appears to be fluid.  For example, if we set the minimum
4669        // to 2 ticks per second, then there may be up to half a second delay between the next
4670        // to last and last ticks which is noticeably discrete and jerky.  This value should
4671        // probably not be set to anything less than about 4.
4672        // If fling accuracy is a problem then consider tuning the tick distance instead.
4673        private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
4674        private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
4675
4676        // Fling velocity decay factor applied after each new key is emitted.
4677        // This parameter controls the deceleration and overall duration of the fling.
4678        // The fling stops automatically when its velocity drops below the minimum
4679        // fling velocity defined above.
4680        private static final float FLING_TICK_DECAY = 0.8f;
4681
4682        /* The input device that we are tracking. */
4683
4684        private int mCurrentDeviceId = -1;
4685        private int mCurrentSource;
4686        private boolean mCurrentDeviceSupported;
4687
4688        /* Configuration for the current input device. */
4689
4690        // The scaled tick distance.  A movement of this amount should generally translate
4691        // into a single dpad event in a given direction.
4692        private float mConfigTickDistance;
4693
4694        // The minimum and maximum scaled fling velocity.
4695        private float mConfigMinFlingVelocity;
4696        private float mConfigMaxFlingVelocity;
4697
4698        /* Tracking state. */
4699
4700        // The velocity tracker for detecting flings.
4701        private VelocityTracker mVelocityTracker;
4702
4703        // The active pointer id, or -1 if none.
4704        private int mActivePointerId = -1;
4705
4706        // Location where tracking started.
4707        private float mStartX;
4708        private float mStartY;
4709
4710        // Most recently observed position.
4711        private float mLastX;
4712        private float mLastY;
4713
4714        // Accumulated movement delta since the last direction key was sent.
4715        private float mAccumulatedX;
4716        private float mAccumulatedY;
4717
4718        // Set to true if any movement was delivered to the app.
4719        // Implies that tap slop was exceeded.
4720        private boolean mConsumedMovement;
4721
4722        // The most recently sent key down event.
4723        // The keycode remains set until the direction changes or a fling ends
4724        // so that repeated key events may be generated as required.
4725        private long mPendingKeyDownTime;
4726        private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4727        private int mPendingKeyRepeatCount;
4728        private int mPendingKeyMetaState;
4729
4730        // The current fling velocity while a fling is in progress.
4731        private boolean mFlinging;
4732        private float mFlingVelocity;
4733
4734        public SyntheticTouchNavigationHandler() {
4735            super(true);
4736        }
4737
4738        public void process(MotionEvent event) {
4739            // Update the current device information.
4740            final long time = event.getEventTime();
4741            final int deviceId = event.getDeviceId();
4742            final int source = event.getSource();
4743            if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
4744                finishKeys(time);
4745                finishTracking(time);
4746                mCurrentDeviceId = deviceId;
4747                mCurrentSource = source;
4748                mCurrentDeviceSupported = false;
4749                InputDevice device = event.getDevice();
4750                if (device != null) {
4751                    // In order to support an input device, we must know certain
4752                    // characteristics about it, such as its size and resolution.
4753                    InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
4754                    InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
4755                    if (xRange != null && yRange != null) {
4756                        mCurrentDeviceSupported = true;
4757
4758                        // Infer the resolution if it not actually known.
4759                        float xRes = xRange.getResolution();
4760                        if (xRes <= 0) {
4761                            xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
4762                        }
4763                        float yRes = yRange.getResolution();
4764                        if (yRes <= 0) {
4765                            yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
4766                        }
4767                        float nominalRes = (xRes + yRes) * 0.5f;
4768
4769                        // Precompute all of the configuration thresholds we will need.
4770                        mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
4771                        mConfigMinFlingVelocity =
4772                                MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4773                        mConfigMaxFlingVelocity =
4774                                MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4775
4776                        if (LOCAL_DEBUG) {
4777                            Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
4778                                    + " (" + Integer.toHexString(mCurrentSource) + "): "
4779                                    + ", mConfigTickDistance=" + mConfigTickDistance
4780                                    + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
4781                                    + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
4782                        }
4783                    }
4784                }
4785            }
4786            if (!mCurrentDeviceSupported) {
4787                return;
4788            }
4789
4790            // Handle the event.
4791            final int action = event.getActionMasked();
4792            switch (action) {
4793                case MotionEvent.ACTION_DOWN: {
4794                    boolean caughtFling = mFlinging;
4795                    finishKeys(time);
4796                    finishTracking(time);
4797                    mActivePointerId = event.getPointerId(0);
4798                    mVelocityTracker = VelocityTracker.obtain();
4799                    mVelocityTracker.addMovement(event);
4800                    mStartX = event.getX();
4801                    mStartY = event.getY();
4802                    mLastX = mStartX;
4803                    mLastY = mStartY;
4804                    mAccumulatedX = 0;
4805                    mAccumulatedY = 0;
4806
4807                    // If we caught a fling, then pretend that the tap slop has already
4808                    // been exceeded to suppress taps whose only purpose is to stop the fling.
4809                    mConsumedMovement = caughtFling;
4810                    break;
4811                }
4812
4813                case MotionEvent.ACTION_MOVE:
4814                case MotionEvent.ACTION_UP: {
4815                    if (mActivePointerId < 0) {
4816                        break;
4817                    }
4818                    final int index = event.findPointerIndex(mActivePointerId);
4819                    if (index < 0) {
4820                        finishKeys(time);
4821                        finishTracking(time);
4822                        break;
4823                    }
4824
4825                    mVelocityTracker.addMovement(event);
4826                    final float x = event.getX(index);
4827                    final float y = event.getY(index);
4828                    mAccumulatedX += x - mLastX;
4829                    mAccumulatedY += y - mLastY;
4830                    mLastX = x;
4831                    mLastY = y;
4832
4833                    // Consume any accumulated movement so far.
4834                    final int metaState = event.getMetaState();
4835                    consumeAccumulatedMovement(time, metaState);
4836
4837                    // Detect taps and flings.
4838                    if (action == MotionEvent.ACTION_UP) {
4839                        if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4840                            // It might be a fling.
4841                            mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
4842                            final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
4843                            final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
4844                            if (!startFling(time, vx, vy)) {
4845                                finishKeys(time);
4846                            }
4847                        }
4848                        finishTracking(time);
4849                    }
4850                    break;
4851                }
4852
4853                case MotionEvent.ACTION_CANCEL: {
4854                    finishKeys(time);
4855                    finishTracking(time);
4856                    break;
4857                }
4858            }
4859        }
4860
4861        public void cancel(MotionEvent event) {
4862            if (mCurrentDeviceId == event.getDeviceId()
4863                    && mCurrentSource == event.getSource()) {
4864                final long time = event.getEventTime();
4865                finishKeys(time);
4866                finishTracking(time);
4867            }
4868        }
4869
4870        private void finishKeys(long time) {
4871            cancelFling();
4872            sendKeyUp(time);
4873        }
4874
4875        private void finishTracking(long time) {
4876            if (mActivePointerId >= 0) {
4877                mActivePointerId = -1;
4878                mVelocityTracker.recycle();
4879                mVelocityTracker = null;
4880            }
4881        }
4882
4883        private void consumeAccumulatedMovement(long time, int metaState) {
4884            final float absX = Math.abs(mAccumulatedX);
4885            final float absY = Math.abs(mAccumulatedY);
4886            if (absX >= absY) {
4887                if (absX >= mConfigTickDistance) {
4888                    mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
4889                            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
4890                    mAccumulatedY = 0;
4891                    mConsumedMovement = true;
4892                }
4893            } else {
4894                if (absY >= mConfigTickDistance) {
4895                    mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
4896                            KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
4897                    mAccumulatedX = 0;
4898                    mConsumedMovement = true;
4899                }
4900            }
4901        }
4902
4903        private float consumeAccumulatedMovement(long time, int metaState,
4904                float accumulator, int negativeKeyCode, int positiveKeyCode) {
4905            while (accumulator <= -mConfigTickDistance) {
4906                sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
4907                accumulator += mConfigTickDistance;
4908            }
4909            while (accumulator >= mConfigTickDistance) {
4910                sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
4911                accumulator -= mConfigTickDistance;
4912            }
4913            return accumulator;
4914        }
4915
4916        private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
4917            if (mPendingKeyCode != keyCode) {
4918                sendKeyUp(time);
4919                mPendingKeyDownTime = time;
4920                mPendingKeyCode = keyCode;
4921                mPendingKeyRepeatCount = 0;
4922            } else {
4923                mPendingKeyRepeatCount += 1;
4924            }
4925            mPendingKeyMetaState = metaState;
4926
4927            // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
4928            // but it doesn't quite make sense when simulating the events in this way.
4929            if (LOCAL_DEBUG) {
4930                Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
4931                        + ", repeatCount=" + mPendingKeyRepeatCount
4932                        + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4933            }
4934            enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4935                    KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
4936                    mPendingKeyMetaState, mCurrentDeviceId,
4937                    KeyEvent.FLAG_FALLBACK, mCurrentSource));
4938        }
4939
4940        private void sendKeyUp(long time) {
4941            if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4942                if (LOCAL_DEBUG) {
4943                    Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
4944                            + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4945                }
4946                enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4947                        KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
4948                        mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
4949                        mCurrentSource));
4950                mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4951            }
4952        }
4953
4954        private boolean startFling(long time, float vx, float vy) {
4955            if (LOCAL_DEBUG) {
4956                Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
4957                        + ", min=" + mConfigMinFlingVelocity);
4958            }
4959
4960            // Flings must be oriented in the same direction as the preceding movements.
4961            switch (mPendingKeyCode) {
4962                case KeyEvent.KEYCODE_DPAD_LEFT:
4963                    if (-vx >= mConfigMinFlingVelocity
4964                            && Math.abs(vy) < mConfigMinFlingVelocity) {
4965                        mFlingVelocity = -vx;
4966                        break;
4967                    }
4968                    return false;
4969
4970                case KeyEvent.KEYCODE_DPAD_RIGHT:
4971                    if (vx >= mConfigMinFlingVelocity
4972                            && Math.abs(vy) < mConfigMinFlingVelocity) {
4973                        mFlingVelocity = vx;
4974                        break;
4975                    }
4976                    return false;
4977
4978                case KeyEvent.KEYCODE_DPAD_UP:
4979                    if (-vy >= mConfigMinFlingVelocity
4980                            && Math.abs(vx) < mConfigMinFlingVelocity) {
4981                        mFlingVelocity = -vy;
4982                        break;
4983                    }
4984                    return false;
4985
4986                case KeyEvent.KEYCODE_DPAD_DOWN:
4987                    if (vy >= mConfigMinFlingVelocity
4988                            && Math.abs(vx) < mConfigMinFlingVelocity) {
4989                        mFlingVelocity = vy;
4990                        break;
4991                    }
4992                    return false;
4993            }
4994
4995            // Post the first fling event.
4996            mFlinging = postFling(time);
4997            return mFlinging;
4998        }
4999
5000        private boolean postFling(long time) {
5001            // The idea here is to estimate the time when the pointer would have
5002            // traveled one tick distance unit given the current fling velocity.
5003            // This effect creates continuity of motion.
5004            if (mFlingVelocity >= mConfigMinFlingVelocity) {
5005                long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
5006                postAtTime(mFlingRunnable, time + delay);
5007                if (LOCAL_DEBUG) {
5008                    Log.d(LOCAL_TAG, "Posted fling: velocity="
5009                            + mFlingVelocity + ", delay=" + delay
5010                            + ", keyCode=" + mPendingKeyCode);
5011                }
5012                return true;
5013            }
5014            return false;
5015        }
5016
5017        private void cancelFling() {
5018            if (mFlinging) {
5019                removeCallbacks(mFlingRunnable);
5020                mFlinging = false;
5021            }
5022        }
5023
5024        private final Runnable mFlingRunnable = new Runnable() {
5025            @Override
5026            public void run() {
5027                final long time = SystemClock.uptimeMillis();
5028                sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5029                mFlingVelocity *= FLING_TICK_DECAY;
5030                if (!postFling(time)) {
5031                    mFlinging = false;
5032                    finishKeys(time);
5033                }
5034            }
5035        };
5036    }
5037
5038    final class SyntheticKeyboardHandler {
5039        public void process(KeyEvent event) {
5040            if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5041                return;
5042            }
5043
5044            final KeyCharacterMap kcm = event.getKeyCharacterMap();
5045            final int keyCode = event.getKeyCode();
5046            final int metaState = event.getMetaState();
5047
5048            // Check for fallback actions specified by the key character map.
5049            KeyCharacterMap.FallbackAction fallbackAction =
5050                    kcm.getFallbackAction(keyCode, metaState);
5051            if (fallbackAction != null) {
5052                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5053                KeyEvent fallbackEvent = KeyEvent.obtain(
5054                        event.getDownTime(), event.getEventTime(),
5055                        event.getAction(), fallbackAction.keyCode,
5056                        event.getRepeatCount(), fallbackAction.metaState,
5057                        event.getDeviceId(), event.getScanCode(),
5058                        flags, event.getSource(), null);
5059                fallbackAction.recycle();
5060                enqueueInputEvent(fallbackEvent);
5061            }
5062        }
5063    }
5064
5065    /**
5066     * Returns true if the key is used for keyboard navigation.
5067     * @param keyEvent The key event.
5068     * @return True if the key is used for keyboard navigation.
5069     */
5070    private static boolean isNavigationKey(KeyEvent keyEvent) {
5071        switch (keyEvent.getKeyCode()) {
5072        case KeyEvent.KEYCODE_DPAD_LEFT:
5073        case KeyEvent.KEYCODE_DPAD_RIGHT:
5074        case KeyEvent.KEYCODE_DPAD_UP:
5075        case KeyEvent.KEYCODE_DPAD_DOWN:
5076        case KeyEvent.KEYCODE_DPAD_CENTER:
5077        case KeyEvent.KEYCODE_PAGE_UP:
5078        case KeyEvent.KEYCODE_PAGE_DOWN:
5079        case KeyEvent.KEYCODE_MOVE_HOME:
5080        case KeyEvent.KEYCODE_MOVE_END:
5081        case KeyEvent.KEYCODE_TAB:
5082        case KeyEvent.KEYCODE_SPACE:
5083        case KeyEvent.KEYCODE_ENTER:
5084            return true;
5085        }
5086        return false;
5087    }
5088
5089    /**
5090     * Returns true if the key is used for typing.
5091     * @param keyEvent The key event.
5092     * @return True if the key is used for typing.
5093     */
5094    private static boolean isTypingKey(KeyEvent keyEvent) {
5095        return keyEvent.getUnicodeChar() > 0;
5096    }
5097
5098    /**
5099     * See if the key event means we should leave touch mode (and leave touch mode if so).
5100     * @param event The key event.
5101     * @return Whether this key event should be consumed (meaning the act of
5102     *   leaving touch mode alone is considered the event).
5103     */
5104    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
5105        // Only relevant in touch mode.
5106        if (!mAttachInfo.mInTouchMode) {
5107            return false;
5108        }
5109
5110        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
5111        final int action = event.getAction();
5112        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
5113            return false;
5114        }
5115
5116        // Don't leave touch mode if the IME told us not to.
5117        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
5118            return false;
5119        }
5120
5121        // If the key can be used for keyboard navigation then leave touch mode
5122        // and select a focused view if needed (in ensureTouchMode).
5123        // When a new focused view is selected, we consume the navigation key because
5124        // navigation doesn't make much sense unless a view already has focus so
5125        // the key's purpose is to set focus.
5126        if (isNavigationKey(event)) {
5127            return ensureTouchMode(false);
5128        }
5129
5130        // If the key can be used for typing then leave touch mode
5131        // and select a focused view if needed (in ensureTouchMode).
5132        // Always allow the view to process the typing key.
5133        if (isTypingKey(event)) {
5134            ensureTouchMode(false);
5135            return false;
5136        }
5137
5138        return false;
5139    }
5140
5141    /* drag/drop */
5142    void setLocalDragState(Object obj) {
5143        mLocalDragState = obj;
5144    }
5145
5146    private void handleDragEvent(DragEvent event) {
5147        // From the root, only drag start/end/location are dispatched.  entered/exited
5148        // are determined and dispatched by the viewgroup hierarchy, who then report
5149        // that back here for ultimate reporting back to the framework.
5150        if (mView != null && mAdded) {
5151            final int what = event.mAction;
5152
5153            if (what == DragEvent.ACTION_DRAG_EXITED) {
5154                // A direct EXITED event means that the window manager knows we've just crossed
5155                // a window boundary, so the current drag target within this one must have
5156                // just been exited.  Send it the usual notifications and then we're done
5157                // for now.
5158                mView.dispatchDragEvent(event);
5159            } else {
5160                // Cache the drag description when the operation starts, then fill it in
5161                // on subsequent calls as a convenience
5162                if (what == DragEvent.ACTION_DRAG_STARTED) {
5163                    mCurrentDragView = null;    // Start the current-recipient tracking
5164                    mDragDescription = event.mClipDescription;
5165                } else {
5166                    event.mClipDescription = mDragDescription;
5167                }
5168
5169                // For events with a [screen] location, translate into window coordinates
5170                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
5171                    mDragPoint.set(event.mX, event.mY);
5172                    if (mTranslator != null) {
5173                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
5174                    }
5175
5176                    if (mCurScrollY != 0) {
5177                        mDragPoint.offset(0, mCurScrollY);
5178                    }
5179
5180                    event.mX = mDragPoint.x;
5181                    event.mY = mDragPoint.y;
5182                }
5183
5184                // Remember who the current drag target is pre-dispatch
5185                final View prevDragView = mCurrentDragView;
5186
5187                // Now dispatch the drag/drop event
5188                boolean result = mView.dispatchDragEvent(event);
5189
5190                // If we changed apparent drag target, tell the OS about it
5191                if (prevDragView != mCurrentDragView) {
5192                    try {
5193                        if (prevDragView != null) {
5194                            mWindowSession.dragRecipientExited(mWindow);
5195                        }
5196                        if (mCurrentDragView != null) {
5197                            mWindowSession.dragRecipientEntered(mWindow);
5198                        }
5199                    } catch (RemoteException e) {
5200                        Slog.e(TAG, "Unable to note drag target change");
5201                    }
5202                }
5203
5204                // Report the drop result when we're done
5205                if (what == DragEvent.ACTION_DROP) {
5206                    mDragDescription = null;
5207                    try {
5208                        Log.i(TAG, "Reporting drop result: " + result);
5209                        mWindowSession.reportDropResult(mWindow, result);
5210                    } catch (RemoteException e) {
5211                        Log.e(TAG, "Unable to report drop result");
5212                    }
5213                }
5214
5215                // When the drag operation ends, release any local state object
5216                // that may have been in use
5217                if (what == DragEvent.ACTION_DRAG_ENDED) {
5218                    setLocalDragState(null);
5219                }
5220            }
5221        }
5222        event.recycle();
5223    }
5224
5225    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
5226        if (mSeq != args.seq) {
5227            // The sequence has changed, so we need to update our value and make
5228            // sure to do a traversal afterward so the window manager is given our
5229            // most recent data.
5230            mSeq = args.seq;
5231            mAttachInfo.mForceReportNewAttributes = true;
5232            scheduleTraversals();
5233        }
5234        if (mView == null) return;
5235        if (args.localChanges != 0) {
5236            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
5237        }
5238
5239        int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5240        if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5241            mAttachInfo.mGlobalSystemUiVisibility = visibility;
5242            mView.dispatchSystemUiVisibilityChanged(visibility);
5243        }
5244    }
5245
5246    public void handleDispatchDoneAnimating() {
5247        if (mWindowsAnimating) {
5248            mWindowsAnimating = false;
5249            if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded)  {
5250                scheduleTraversals();
5251            }
5252        }
5253    }
5254
5255    public void handleDispatchWindowShown() {
5256        mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5257    }
5258
5259    public void getLastTouchPoint(Point outLocation) {
5260        outLocation.x = (int) mLastTouchPoint.x;
5261        outLocation.y = (int) mLastTouchPoint.y;
5262    }
5263
5264    public void setDragFocus(View newDragTarget) {
5265        if (mCurrentDragView != newDragTarget) {
5266            mCurrentDragView = newDragTarget;
5267        }
5268    }
5269
5270    private AudioManager getAudioManager() {
5271        if (mView == null) {
5272            throw new IllegalStateException("getAudioManager called when there is no mView");
5273        }
5274        if (mAudioManager == null) {
5275            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5276        }
5277        return mAudioManager;
5278    }
5279
5280    public AccessibilityInteractionController getAccessibilityInteractionController() {
5281        if (mView == null) {
5282            throw new IllegalStateException("getAccessibilityInteractionController"
5283                    + " called when there is no mView");
5284        }
5285        if (mAccessibilityInteractionController == null) {
5286            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
5287        }
5288        return mAccessibilityInteractionController;
5289    }
5290
5291    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5292            boolean insetsPending) throws RemoteException {
5293
5294        float appScale = mAttachInfo.mApplicationScale;
5295        boolean restore = false;
5296        if (params != null && mTranslator != null) {
5297            restore = true;
5298            params.backup();
5299            mTranslator.translateWindowLayout(params);
5300        }
5301        if (params != null) {
5302            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
5303        }
5304        mPendingConfiguration.seq = 0;
5305        //Log.d(TAG, ">>>>>> CALLING relayout");
5306        if (params != null && mOrigWindowType != params.type) {
5307            // For compatibility with old apps, don't crash here.
5308            if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5309                Slog.w(TAG, "Window type can not be changed after "
5310                        + "the window is added; ignoring change of " + mView);
5311                params.type = mOrigWindowType;
5312            }
5313        }
5314        int relayoutResult = mWindowSession.relayout(
5315                mWindow, mSeq, params,
5316                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
5317                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
5318                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
5319                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
5320                mPendingStableInsets, mPendingConfiguration, mSurface);
5321        //Log.d(TAG, "<<<<<< BACK FROM relayout");
5322        if (restore) {
5323            params.restore();
5324        }
5325
5326        if (mTranslator != null) {
5327            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
5328            mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
5329            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5330            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
5331            mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
5332        }
5333        return relayoutResult;
5334    }
5335
5336    /**
5337     * {@inheritDoc}
5338     */
5339    @Override
5340    public void playSoundEffect(int effectId) {
5341        checkThread();
5342
5343        if (mMediaDisabled) {
5344            return;
5345        }
5346
5347        try {
5348            final AudioManager audioManager = getAudioManager();
5349
5350            switch (effectId) {
5351                case SoundEffectConstants.CLICK:
5352                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5353                    return;
5354                case SoundEffectConstants.NAVIGATION_DOWN:
5355                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5356                    return;
5357                case SoundEffectConstants.NAVIGATION_LEFT:
5358                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5359                    return;
5360                case SoundEffectConstants.NAVIGATION_RIGHT:
5361                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5362                    return;
5363                case SoundEffectConstants.NAVIGATION_UP:
5364                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5365                    return;
5366                default:
5367                    throw new IllegalArgumentException("unknown effect id " + effectId +
5368                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
5369            }
5370        } catch (IllegalStateException e) {
5371            // Exception thrown by getAudioManager() when mView is null
5372            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
5373            e.printStackTrace();
5374        }
5375    }
5376
5377    /**
5378     * {@inheritDoc}
5379     */
5380    @Override
5381    public boolean performHapticFeedback(int effectId, boolean always) {
5382        try {
5383            return mWindowSession.performHapticFeedback(mWindow, effectId, always);
5384        } catch (RemoteException e) {
5385            return false;
5386        }
5387    }
5388
5389    /**
5390     * {@inheritDoc}
5391     */
5392    @Override
5393    public View focusSearch(View focused, int direction) {
5394        checkThread();
5395        if (!(mView instanceof ViewGroup)) {
5396            return null;
5397        }
5398        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5399    }
5400
5401    public void debug() {
5402        mView.debug();
5403    }
5404
5405    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5406        String innerPrefix = prefix + "  ";
5407        writer.print(prefix); writer.println("ViewRoot:");
5408        writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded);
5409                writer.print(" mRemoved="); writer.println(mRemoved);
5410        writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled=");
5411                writer.println(mConsumeBatchedInputScheduled);
5412        writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled=");
5413                writer.println(mConsumeBatchedInputImmediatelyScheduled);
5414        writer.print(innerPrefix); writer.print("mPendingInputEventCount=");
5415                writer.println(mPendingInputEventCount);
5416        writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled=");
5417                writer.println(mProcessInputEventsScheduled);
5418        writer.print(innerPrefix); writer.print("mTraversalScheduled=");
5419                writer.print(mTraversalScheduled);
5420        if (mTraversalScheduled) {
5421            writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")");
5422        } else {
5423            writer.println();
5424        }
5425        mFirstInputStage.dump(innerPrefix, writer);
5426
5427        mChoreographer.dump(prefix, writer);
5428
5429        writer.print(prefix); writer.println("View Hierarchy:");
5430        dumpViewHierarchy(innerPrefix, writer, mView);
5431    }
5432
5433    private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5434        writer.print(prefix);
5435        if (view == null) {
5436            writer.println("null");
5437            return;
5438        }
5439        writer.println(view.toString());
5440        if (!(view instanceof ViewGroup)) {
5441            return;
5442        }
5443        ViewGroup grp = (ViewGroup)view;
5444        final int N = grp.getChildCount();
5445        if (N <= 0) {
5446            return;
5447        }
5448        prefix = prefix + "  ";
5449        for (int i=0; i<N; i++) {
5450            dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5451        }
5452    }
5453
5454    public void dumpGfxInfo(int[] info) {
5455        info[0] = info[1] = 0;
5456        if (mView != null) {
5457            getGfxInfo(mView, info);
5458        }
5459    }
5460
5461    private static void getGfxInfo(View view, int[] info) {
5462        RenderNode renderNode = view.mRenderNode;
5463        info[0]++;
5464        if (renderNode != null) {
5465            info[1] += renderNode.getDebugSize();
5466        }
5467
5468        if (view instanceof ViewGroup) {
5469            ViewGroup group = (ViewGroup) view;
5470
5471            int count = group.getChildCount();
5472            for (int i = 0; i < count; i++) {
5473                getGfxInfo(group.getChildAt(i), info);
5474            }
5475        }
5476    }
5477
5478    /**
5479     * @param immediate True, do now if not in traversal. False, put on queue and do later.
5480     * @return True, request has been queued. False, request has been completed.
5481     */
5482    boolean die(boolean immediate) {
5483        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
5484        // done by dispatchDetachedFromWindow will cause havoc on return.
5485        if (immediate && !mIsInTraversal) {
5486            doDie();
5487            return false;
5488        }
5489
5490        if (!mIsDrawing) {
5491            destroyHardwareRenderer();
5492        } else {
5493            Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
5494                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
5495        }
5496        mHandler.sendEmptyMessage(MSG_DIE);
5497        return true;
5498    }
5499
5500    void doDie() {
5501        checkThread();
5502        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
5503        synchronized (this) {
5504            if (mRemoved) {
5505                return;
5506            }
5507            mRemoved = true;
5508            if (mAdded) {
5509                dispatchDetachedFromWindow();
5510            }
5511
5512            if (mAdded && !mFirst) {
5513                destroyHardwareRenderer();
5514
5515                if (mView != null) {
5516                    int viewVisibility = mView.getVisibility();
5517                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
5518                    if (mWindowAttributesChanged || viewVisibilityChanged) {
5519                        // If layout params have been changed, first give them
5520                        // to the window manager to make sure it has the correct
5521                        // animation info.
5522                        try {
5523                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5524                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5525                                mWindowSession.finishDrawing(mWindow);
5526                            }
5527                        } catch (RemoteException e) {
5528                        }
5529                    }
5530
5531                    mSurface.release();
5532                }
5533            }
5534
5535            mAdded = false;
5536        }
5537        WindowManagerGlobal.getInstance().doRemoveView(this);
5538    }
5539
5540    public void requestUpdateConfiguration(Configuration config) {
5541        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5542        mHandler.sendMessage(msg);
5543    }
5544
5545    public void loadSystemProperties() {
5546        mHandler.post(new Runnable() {
5547            @Override
5548            public void run() {
5549                // Profiling
5550                mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5551                profileRendering(mAttachInfo.mHasWindowFocus);
5552
5553                // Media (used by sound effects)
5554                mMediaDisabled = SystemProperties.getBoolean(PROPERTY_MEDIA_DISABLED, false);
5555
5556                // Hardware rendering
5557                if (mAttachInfo.mHardwareRenderer != null) {
5558                    if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
5559                        invalidate();
5560                    }
5561                }
5562
5563                // Layout debugging
5564                boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5565                if (layout != mAttachInfo.mDebugLayout) {
5566                    mAttachInfo.mDebugLayout = layout;
5567                    if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5568                        mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5569                    }
5570                }
5571
5572                // detect emulator
5573                mIsEmulator = Build.HARDWARE.contains("goldfish");
5574                mIsCircularEmulator =
5575                        SystemProperties.getBoolean(PROPERTY_EMULATOR_CIRCULAR, false);
5576            }
5577        });
5578    }
5579
5580    private void destroyHardwareRenderer() {
5581        HardwareRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
5582
5583        if (hardwareRenderer != null) {
5584            if (mView != null) {
5585                hardwareRenderer.destroyHardwareResources(mView);
5586            }
5587            hardwareRenderer.destroy();
5588            hardwareRenderer.setRequested(false);
5589
5590            mAttachInfo.mHardwareRenderer = null;
5591            mAttachInfo.mHardwareAccelerated = false;
5592        }
5593    }
5594
5595    public void dispatchFinishInputConnection(InputConnection connection) {
5596        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
5597        mHandler.sendMessage(msg);
5598    }
5599
5600    public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
5601            Rect visibleInsets, Rect stableInsets, boolean reportDraw, Configuration newConfig) {
5602        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
5603                + " contentInsets=" + contentInsets.toShortString()
5604                + " visibleInsets=" + visibleInsets.toShortString()
5605                + " reportDraw=" + reportDraw);
5606        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
5607        if (mTranslator != null) {
5608            mTranslator.translateRectInScreenToAppWindow(frame);
5609            mTranslator.translateRectInScreenToAppWindow(overscanInsets);
5610            mTranslator.translateRectInScreenToAppWindow(contentInsets);
5611            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
5612        }
5613        SomeArgs args = SomeArgs.obtain();
5614        final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5615        args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5616        args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5617        args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5618        args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
5619        args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
5620        args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets;
5621        msg.obj = args;
5622        mHandler.sendMessage(msg);
5623    }
5624
5625    public void dispatchMoved(int newX, int newY) {
5626        if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
5627        if (mTranslator != null) {
5628            PointF point = new PointF(newX, newY);
5629            mTranslator.translatePointInScreenToAppWindow(point);
5630            newX = (int) (point.x + 0.5);
5631            newY = (int) (point.y + 0.5);
5632        }
5633        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5634        mHandler.sendMessage(msg);
5635    }
5636
5637    /**
5638     * Represents a pending input event that is waiting in a queue.
5639     *
5640     * Input events are processed in serial order by the timestamp specified by
5641     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
5642     * one input event to the application at a time and waits for the application
5643     * to finish handling it before delivering the next one.
5644     *
5645     * However, because the application or IME can synthesize and inject multiple
5646     * key events at a time without going through the input dispatcher, we end up
5647     * needing a queue on the application's side.
5648     */
5649    private static final class QueuedInputEvent {
5650        public static final int FLAG_DELIVER_POST_IME = 1 << 0;
5651        public static final int FLAG_DEFERRED = 1 << 1;
5652        public static final int FLAG_FINISHED = 1 << 2;
5653        public static final int FLAG_FINISHED_HANDLED = 1 << 3;
5654        public static final int FLAG_RESYNTHESIZED = 1 << 4;
5655        public static final int FLAG_UNHANDLED = 1 << 5;
5656
5657        public QueuedInputEvent mNext;
5658
5659        public InputEvent mEvent;
5660        public InputEventReceiver mReceiver;
5661        public int mFlags;
5662
5663        public boolean shouldSkipIme() {
5664            if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5665                return true;
5666            }
5667            return mEvent instanceof MotionEvent
5668                    && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5669        }
5670
5671        public boolean shouldSendToSynthesizer() {
5672            if ((mFlags & FLAG_UNHANDLED) != 0) {
5673                return true;
5674            }
5675
5676            return false;
5677        }
5678
5679        @Override
5680        public String toString() {
5681            StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
5682            boolean hasPrevious = false;
5683            hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
5684            hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
5685            hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
5686            hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
5687            hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
5688            hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
5689            if (!hasPrevious) {
5690                sb.append("0");
5691            }
5692            sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
5693            sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
5694            sb.append(", mEvent=" + mEvent + "}");
5695            return sb.toString();
5696        }
5697
5698        private boolean flagToString(String name, int flag,
5699                boolean hasPrevious, StringBuilder sb) {
5700            if ((mFlags & flag) != 0) {
5701                if (hasPrevious) {
5702                    sb.append("|");
5703                }
5704                sb.append(name);
5705                return true;
5706            }
5707            return hasPrevious;
5708        }
5709    }
5710
5711    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
5712            InputEventReceiver receiver, int flags) {
5713        QueuedInputEvent q = mQueuedInputEventPool;
5714        if (q != null) {
5715            mQueuedInputEventPoolSize -= 1;
5716            mQueuedInputEventPool = q.mNext;
5717            q.mNext = null;
5718        } else {
5719            q = new QueuedInputEvent();
5720        }
5721
5722        q.mEvent = event;
5723        q.mReceiver = receiver;
5724        q.mFlags = flags;
5725        return q;
5726    }
5727
5728    private void recycleQueuedInputEvent(QueuedInputEvent q) {
5729        q.mEvent = null;
5730        q.mReceiver = null;
5731
5732        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
5733            mQueuedInputEventPoolSize += 1;
5734            q.mNext = mQueuedInputEventPool;
5735            mQueuedInputEventPool = q;
5736        }
5737    }
5738
5739    void enqueueInputEvent(InputEvent event) {
5740        enqueueInputEvent(event, null, 0, false);
5741    }
5742
5743    void enqueueInputEvent(InputEvent event,
5744            InputEventReceiver receiver, int flags, boolean processImmediately) {
5745        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
5746
5747        // Always enqueue the input event in order, regardless of its time stamp.
5748        // We do this because the application or the IME may inject key events
5749        // in response to touch events and we want to ensure that the injected keys
5750        // are processed in the order they were received and we cannot trust that
5751        // the time stamp of injected events are monotonic.
5752        QueuedInputEvent last = mPendingInputEventTail;
5753        if (last == null) {
5754            mPendingInputEventHead = q;
5755            mPendingInputEventTail = q;
5756        } else {
5757            last.mNext = q;
5758            mPendingInputEventTail = q;
5759        }
5760        mPendingInputEventCount += 1;
5761        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5762                mPendingInputEventCount);
5763
5764        if (processImmediately) {
5765            doProcessInputEvents();
5766        } else {
5767            scheduleProcessInputEvents();
5768        }
5769    }
5770
5771    private void scheduleProcessInputEvents() {
5772        if (!mProcessInputEventsScheduled) {
5773            mProcessInputEventsScheduled = true;
5774            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
5775            msg.setAsynchronous(true);
5776            mHandler.sendMessage(msg);
5777        }
5778    }
5779
5780    void doProcessInputEvents() {
5781        // Deliver all pending input events in the queue.
5782        while (mPendingInputEventHead != null) {
5783            QueuedInputEvent q = mPendingInputEventHead;
5784            mPendingInputEventHead = q.mNext;
5785            if (mPendingInputEventHead == null) {
5786                mPendingInputEventTail = null;
5787            }
5788            q.mNext = null;
5789
5790            mPendingInputEventCount -= 1;
5791            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5792                    mPendingInputEventCount);
5793
5794            deliverInputEvent(q);
5795        }
5796
5797        // We are done processing all input events that we can process right now
5798        // so we can clear the pending flag immediately.
5799        if (mProcessInputEventsScheduled) {
5800            mProcessInputEventsScheduled = false;
5801            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
5802        }
5803    }
5804
5805    private void deliverInputEvent(QueuedInputEvent q) {
5806        Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5807                q.mEvent.getSequenceNumber());
5808        if (mInputEventConsistencyVerifier != null) {
5809            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
5810        }
5811
5812        InputStage stage;
5813        if (q.shouldSendToSynthesizer()) {
5814            stage = mSyntheticInputStage;
5815        } else {
5816            stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
5817        }
5818
5819        if (stage != null) {
5820            stage.deliver(q);
5821        } else {
5822            finishInputEvent(q);
5823        }
5824    }
5825
5826    private void finishInputEvent(QueuedInputEvent q) {
5827        Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5828                q.mEvent.getSequenceNumber());
5829
5830        if (q.mReceiver != null) {
5831            boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
5832            q.mReceiver.finishInputEvent(q.mEvent, handled);
5833        } else {
5834            q.mEvent.recycleIfNeededAfterDispatch();
5835        }
5836
5837        recycleQueuedInputEvent(q);
5838    }
5839
5840    static boolean isTerminalInputEvent(InputEvent event) {
5841        if (event instanceof KeyEvent) {
5842            final KeyEvent keyEvent = (KeyEvent)event;
5843            return keyEvent.getAction() == KeyEvent.ACTION_UP;
5844        } else {
5845            final MotionEvent motionEvent = (MotionEvent)event;
5846            final int action = motionEvent.getAction();
5847            return action == MotionEvent.ACTION_UP
5848                    || action == MotionEvent.ACTION_CANCEL
5849                    || action == MotionEvent.ACTION_HOVER_EXIT;
5850        }
5851    }
5852
5853    void scheduleConsumeBatchedInput() {
5854        if (!mConsumeBatchedInputScheduled) {
5855            mConsumeBatchedInputScheduled = true;
5856            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
5857                    mConsumedBatchedInputRunnable, null);
5858        }
5859    }
5860
5861    void unscheduleConsumeBatchedInput() {
5862        if (mConsumeBatchedInputScheduled) {
5863            mConsumeBatchedInputScheduled = false;
5864            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
5865                    mConsumedBatchedInputRunnable, null);
5866        }
5867    }
5868
5869    void scheduleConsumeBatchedInputImmediately() {
5870        if (!mConsumeBatchedInputImmediatelyScheduled) {
5871            unscheduleConsumeBatchedInput();
5872            mConsumeBatchedInputImmediatelyScheduled = true;
5873            mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
5874        }
5875    }
5876
5877    void doConsumeBatchedInput(long frameTimeNanos) {
5878        if (mConsumeBatchedInputScheduled) {
5879            mConsumeBatchedInputScheduled = false;
5880            if (mInputEventReceiver != null) {
5881                if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
5882                        && frameTimeNanos != -1) {
5883                    // If we consumed a batch here, we want to go ahead and schedule the
5884                    // consumption of batched input events on the next frame. Otherwise, we would
5885                    // wait until we have more input events pending and might get starved by other
5886                    // things occurring in the process. If the frame time is -1, however, then
5887                    // we're in a non-batching mode, so there's no need to schedule this.
5888                    scheduleConsumeBatchedInput();
5889                }
5890            }
5891            doProcessInputEvents();
5892        }
5893    }
5894
5895    final class TraversalRunnable implements Runnable {
5896        @Override
5897        public void run() {
5898            doTraversal();
5899        }
5900    }
5901    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
5902
5903    final class WindowInputEventReceiver extends InputEventReceiver {
5904        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
5905            super(inputChannel, looper);
5906        }
5907
5908        @Override
5909        public void onInputEvent(InputEvent event) {
5910            enqueueInputEvent(event, this, 0, true);
5911        }
5912
5913        @Override
5914        public void onBatchedInputEventPending() {
5915            if (mUnbufferedInputDispatch) {
5916                super.onBatchedInputEventPending();
5917            } else {
5918                scheduleConsumeBatchedInput();
5919            }
5920        }
5921
5922        @Override
5923        public void dispose() {
5924            unscheduleConsumeBatchedInput();
5925            super.dispose();
5926        }
5927    }
5928    WindowInputEventReceiver mInputEventReceiver;
5929
5930    final class ConsumeBatchedInputRunnable implements Runnable {
5931        @Override
5932        public void run() {
5933            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
5934        }
5935    }
5936    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
5937            new ConsumeBatchedInputRunnable();
5938    boolean mConsumeBatchedInputScheduled;
5939
5940    final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
5941        @Override
5942        public void run() {
5943            doConsumeBatchedInput(-1);
5944        }
5945    }
5946    final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
5947            new ConsumeBatchedInputImmediatelyRunnable();
5948    boolean mConsumeBatchedInputImmediatelyScheduled;
5949
5950    final class InvalidateOnAnimationRunnable implements Runnable {
5951        private boolean mPosted;
5952        private final ArrayList<View> mViews = new ArrayList<View>();
5953        private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
5954                new ArrayList<AttachInfo.InvalidateInfo>();
5955        private View[] mTempViews;
5956        private AttachInfo.InvalidateInfo[] mTempViewRects;
5957
5958        public void addView(View view) {
5959            synchronized (this) {
5960                mViews.add(view);
5961                postIfNeededLocked();
5962            }
5963        }
5964
5965        public void addViewRect(AttachInfo.InvalidateInfo info) {
5966            synchronized (this) {
5967                mViewRects.add(info);
5968                postIfNeededLocked();
5969            }
5970        }
5971
5972        public void removeView(View view) {
5973            synchronized (this) {
5974                mViews.remove(view);
5975
5976                for (int i = mViewRects.size(); i-- > 0; ) {
5977                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
5978                    if (info.target == view) {
5979                        mViewRects.remove(i);
5980                        info.recycle();
5981                    }
5982                }
5983
5984                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
5985                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
5986                    mPosted = false;
5987                }
5988            }
5989        }
5990
5991        @Override
5992        public void run() {
5993            final int viewCount;
5994            final int viewRectCount;
5995            synchronized (this) {
5996                mPosted = false;
5997
5998                viewCount = mViews.size();
5999                if (viewCount != 0) {
6000                    mTempViews = mViews.toArray(mTempViews != null
6001                            ? mTempViews : new View[viewCount]);
6002                    mViews.clear();
6003                }
6004
6005                viewRectCount = mViewRects.size();
6006                if (viewRectCount != 0) {
6007                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
6008                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6009                    mViewRects.clear();
6010                }
6011            }
6012
6013            for (int i = 0; i < viewCount; i++) {
6014                mTempViews[i].invalidate();
6015                mTempViews[i] = null;
6016            }
6017
6018            for (int i = 0; i < viewRectCount; i++) {
6019                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
6020                info.target.invalidate(info.left, info.top, info.right, info.bottom);
6021                info.recycle();
6022            }
6023        }
6024
6025        private void postIfNeededLocked() {
6026            if (!mPosted) {
6027                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
6028                mPosted = true;
6029            }
6030        }
6031    }
6032    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6033            new InvalidateOnAnimationRunnable();
6034
6035    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6036        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6037        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6038    }
6039
6040    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
6041            long delayMilliseconds) {
6042        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
6043        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6044    }
6045
6046    public void dispatchInvalidateOnAnimation(View view) {
6047        mInvalidateOnAnimationRunnable.addView(view);
6048    }
6049
6050    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6051        mInvalidateOnAnimationRunnable.addViewRect(info);
6052    }
6053
6054    public void cancelInvalidate(View view) {
6055        mHandler.removeMessages(MSG_INVALIDATE, view);
6056        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6057        // them to the pool
6058        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6059        mInvalidateOnAnimationRunnable.removeView(view);
6060    }
6061
6062    public void dispatchInputEvent(InputEvent event) {
6063        dispatchInputEvent(event, null);
6064    }
6065
6066    public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6067        SomeArgs args = SomeArgs.obtain();
6068        args.arg1 = event;
6069        args.arg2 = receiver;
6070        Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
6071        msg.setAsynchronous(true);
6072        mHandler.sendMessage(msg);
6073    }
6074
6075    public void synthesizeInputEvent(InputEvent event) {
6076        Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6077        msg.setAsynchronous(true);
6078        mHandler.sendMessage(msg);
6079    }
6080
6081    public void dispatchKeyFromIme(KeyEvent event) {
6082        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
6083        msg.setAsynchronous(true);
6084        mHandler.sendMessage(msg);
6085    }
6086
6087    /**
6088     * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6089     *
6090     * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6091     * passes in.
6092     */
6093    public void dispatchUnhandledInputEvent(InputEvent event) {
6094        if (event instanceof MotionEvent) {
6095            event = MotionEvent.obtain((MotionEvent) event);
6096        }
6097        synthesizeInputEvent(event);
6098    }
6099
6100    public void dispatchAppVisibility(boolean visible) {
6101        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
6102        msg.arg1 = visible ? 1 : 0;
6103        mHandler.sendMessage(msg);
6104    }
6105
6106    public void dispatchGetNewSurface() {
6107        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6108        mHandler.sendMessage(msg);
6109    }
6110
6111    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6112        Message msg = Message.obtain();
6113        msg.what = MSG_WINDOW_FOCUS_CHANGED;
6114        msg.arg1 = hasFocus ? 1 : 0;
6115        msg.arg2 = inTouchMode ? 1 : 0;
6116        mHandler.sendMessage(msg);
6117    }
6118
6119    public void dispatchWindowShown() {
6120        mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6121    }
6122
6123    public void dispatchCloseSystemDialogs(String reason) {
6124        Message msg = Message.obtain();
6125        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
6126        msg.obj = reason;
6127        mHandler.sendMessage(msg);
6128    }
6129
6130    public void dispatchDragEvent(DragEvent event) {
6131        final int what;
6132        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
6133            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6134            mHandler.removeMessages(what);
6135        } else {
6136            what = MSG_DISPATCH_DRAG_EVENT;
6137        }
6138        Message msg = mHandler.obtainMessage(what, event);
6139        mHandler.sendMessage(msg);
6140    }
6141
6142    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6143            int localValue, int localChanges) {
6144        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6145        args.seq = seq;
6146        args.globalVisibility = globalVisibility;
6147        args.localValue = localValue;
6148        args.localChanges = localChanges;
6149        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6150    }
6151
6152    public void dispatchDoneAnimating() {
6153        mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
6154    }
6155
6156    public void dispatchCheckFocus() {
6157        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
6158            // This will result in a call to checkFocus() below.
6159            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
6160        }
6161    }
6162
6163    /**
6164     * Post a callback to send a
6165     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6166     * This event is send at most once every
6167     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
6168     */
6169    private void postSendWindowContentChangedCallback(View source, int changeType) {
6170        if (mSendWindowContentChangedAccessibilityEvent == null) {
6171            mSendWindowContentChangedAccessibilityEvent =
6172                new SendWindowContentChangedAccessibilityEvent();
6173        }
6174        mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
6175    }
6176
6177    /**
6178     * Remove a posted callback to send a
6179     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6180     */
6181    private void removeSendWindowContentChangedCallback() {
6182        if (mSendWindowContentChangedAccessibilityEvent != null) {
6183            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
6184        }
6185    }
6186
6187    @Override
6188    public boolean showContextMenuForChild(View originalView) {
6189        return false;
6190    }
6191
6192    @Override
6193    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6194        return null;
6195    }
6196
6197    @Override
6198    public void createContextMenu(ContextMenu menu) {
6199    }
6200
6201    @Override
6202    public void childDrawableStateChanged(View child) {
6203    }
6204
6205    @Override
6206    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
6207        if (mView == null) {
6208            return false;
6209        }
6210        // Intercept accessibility focus events fired by virtual nodes to keep
6211        // track of accessibility focus position in such nodes.
6212        final int eventType = event.getEventType();
6213        switch (eventType) {
6214            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
6215                final long sourceNodeId = event.getSourceNodeId();
6216                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6217                        sourceNodeId);
6218                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6219                if (source != null) {
6220                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6221                    if (provider != null) {
6222                        final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
6223                                sourceNodeId);
6224                        final AccessibilityNodeInfo node;
6225                        if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6226                            node = provider.createAccessibilityNodeInfo(
6227                                    AccessibilityNodeProvider.HOST_VIEW_ID);
6228                        } else {
6229                            node = provider.createAccessibilityNodeInfo(virtualNodeId);
6230                        }
6231                        setAccessibilityFocus(source, node);
6232                    }
6233                }
6234            } break;
6235            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
6236                final long sourceNodeId = event.getSourceNodeId();
6237                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6238                        sourceNodeId);
6239                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6240                if (source != null) {
6241                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6242                    if (provider != null) {
6243                        setAccessibilityFocus(null, null);
6244                    }
6245                }
6246            } break;
6247
6248
6249            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
6250                if (mAccessibilityFocusedHost != null && mAccessibilityFocusedVirtualView != null) {
6251                    // We care only for changes rooted in the focused host.
6252                    final long eventSourceId = event.getSourceNodeId();
6253                    final int hostViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6254                            eventSourceId);
6255                    if (hostViewId != mAccessibilityFocusedHost.getAccessibilityViewId()) {
6256                        break;
6257                    }
6258
6259                    // We only care about changes that may change the virtual focused view bounds.
6260                    final int changes = event.getContentChangeTypes();
6261                    if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) != 0
6262                            || changes == AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
6263                        AccessibilityNodeProvider provider = mAccessibilityFocusedHost
6264                                .getAccessibilityNodeProvider();
6265                        if (provider != null) {
6266                            final int virtualChildId = AccessibilityNodeInfo.getVirtualDescendantId(
6267                                    mAccessibilityFocusedVirtualView.getSourceNodeId());
6268                            if (virtualChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6269                                mAccessibilityFocusedVirtualView = provider
6270                                        .createAccessibilityNodeInfo(
6271                                                AccessibilityNodeProvider.HOST_VIEW_ID);
6272                            } else {
6273                                mAccessibilityFocusedVirtualView = provider
6274                                        .createAccessibilityNodeInfo(virtualChildId);
6275                            }
6276                        }
6277                    }
6278                }
6279            } break;
6280        }
6281        mAccessibilityManager.sendAccessibilityEvent(event);
6282        return true;
6283    }
6284
6285    @Override
6286    public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6287        postSendWindowContentChangedCallback(source, changeType);
6288    }
6289
6290    @Override
6291    public boolean canResolveLayoutDirection() {
6292        return true;
6293    }
6294
6295    @Override
6296    public boolean isLayoutDirectionResolved() {
6297        return true;
6298    }
6299
6300    @Override
6301    public int getLayoutDirection() {
6302        return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6303    }
6304
6305    @Override
6306    public boolean canResolveTextDirection() {
6307        return true;
6308    }
6309
6310    @Override
6311    public boolean isTextDirectionResolved() {
6312        return true;
6313    }
6314
6315    @Override
6316    public int getTextDirection() {
6317        return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6318    }
6319
6320    @Override
6321    public boolean canResolveTextAlignment() {
6322        return true;
6323    }
6324
6325    @Override
6326    public boolean isTextAlignmentResolved() {
6327        return true;
6328    }
6329
6330    @Override
6331    public int getTextAlignment() {
6332        return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6333    }
6334
6335    private View getCommonPredecessor(View first, View second) {
6336        if (mTempHashSet == null) {
6337            mTempHashSet = new HashSet<View>();
6338        }
6339        HashSet<View> seen = mTempHashSet;
6340        seen.clear();
6341        View firstCurrent = first;
6342        while (firstCurrent != null) {
6343            seen.add(firstCurrent);
6344            ViewParent firstCurrentParent = firstCurrent.mParent;
6345            if (firstCurrentParent instanceof View) {
6346                firstCurrent = (View) firstCurrentParent;
6347            } else {
6348                firstCurrent = null;
6349            }
6350        }
6351        View secondCurrent = second;
6352        while (secondCurrent != null) {
6353            if (seen.contains(secondCurrent)) {
6354                seen.clear();
6355                return secondCurrent;
6356            }
6357            ViewParent secondCurrentParent = secondCurrent.mParent;
6358            if (secondCurrentParent instanceof View) {
6359                secondCurrent = (View) secondCurrentParent;
6360            } else {
6361                secondCurrent = null;
6362            }
6363        }
6364        seen.clear();
6365        return null;
6366    }
6367
6368    void checkThread() {
6369        if (mThread != Thread.currentThread()) {
6370            throw new CalledFromWrongThreadException(
6371                    "Only the original thread that created a view hierarchy can touch its views.");
6372        }
6373    }
6374
6375    @Override
6376    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
6377        // ViewAncestor never intercepts touch event, so this can be a no-op
6378    }
6379
6380    @Override
6381    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
6382        final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
6383        if (rectangle != null) {
6384            mTempRect.set(rectangle);
6385            mTempRect.offset(0, -mCurScrollY);
6386            mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6387            try {
6388                mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6389            } catch (RemoteException re) {
6390                /* ignore */
6391            }
6392        }
6393        return scrolled;
6394    }
6395
6396    @Override
6397    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6398        // Do nothing.
6399    }
6400
6401    @Override
6402    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6403        return false;
6404    }
6405
6406    @Override
6407    public void onStopNestedScroll(View target) {
6408    }
6409
6410    @Override
6411    public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6412    }
6413
6414    @Override
6415    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6416            int dxUnconsumed, int dyUnconsumed) {
6417    }
6418
6419    @Override
6420    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6421    }
6422
6423    @Override
6424    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6425        return false;
6426    }
6427
6428    @Override
6429    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6430        return false;
6431    }
6432
6433    @Override
6434    public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6435        return false;
6436    }
6437
6438    void changeCanvasOpacity(boolean opaque) {
6439        Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque);
6440        if (mAttachInfo.mHardwareRenderer != null) {
6441            mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6442        }
6443    }
6444
6445    class TakenSurfaceHolder extends BaseSurfaceHolder {
6446        @Override
6447        public boolean onAllowLockCanvas() {
6448            return mDrawingAllowed;
6449        }
6450
6451        @Override
6452        public void onRelayoutContainer() {
6453            // Not currently interesting -- from changing between fixed and layout size.
6454        }
6455
6456        @Override
6457        public void setFormat(int format) {
6458            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6459        }
6460
6461        @Override
6462        public void setType(int type) {
6463            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6464        }
6465
6466        @Override
6467        public void onUpdateSurface() {
6468            // We take care of format and type changes on our own.
6469            throw new IllegalStateException("Shouldn't be here");
6470        }
6471
6472        @Override
6473        public boolean isCreating() {
6474            return mIsCreating;
6475        }
6476
6477        @Override
6478        public void setFixedSize(int width, int height) {
6479            throw new UnsupportedOperationException(
6480                    "Currently only support sizing from layout");
6481        }
6482
6483        @Override
6484        public void setKeepScreenOn(boolean screenOn) {
6485            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6486        }
6487    }
6488
6489    static class W extends IWindow.Stub {
6490        private final WeakReference<ViewRootImpl> mViewAncestor;
6491        private final IWindowSession mWindowSession;
6492
6493        W(ViewRootImpl viewAncestor) {
6494            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
6495            mWindowSession = viewAncestor.mWindowSession;
6496        }
6497
6498        @Override
6499        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
6500                Rect visibleInsets, Rect stableInsets, boolean reportDraw,
6501                Configuration newConfig) {
6502            final ViewRootImpl viewAncestor = mViewAncestor.get();
6503            if (viewAncestor != null) {
6504                viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
6505                        visibleInsets, stableInsets, reportDraw, newConfig);
6506            }
6507        }
6508
6509        @Override
6510        public void moved(int newX, int newY) {
6511            final ViewRootImpl viewAncestor = mViewAncestor.get();
6512            if (viewAncestor != null) {
6513                viewAncestor.dispatchMoved(newX, newY);
6514            }
6515        }
6516
6517        @Override
6518        public void dispatchAppVisibility(boolean visible) {
6519            final ViewRootImpl viewAncestor = mViewAncestor.get();
6520            if (viewAncestor != null) {
6521                viewAncestor.dispatchAppVisibility(visible);
6522            }
6523        }
6524
6525        @Override
6526        public void dispatchGetNewSurface() {
6527            final ViewRootImpl viewAncestor = mViewAncestor.get();
6528            if (viewAncestor != null) {
6529                viewAncestor.dispatchGetNewSurface();
6530            }
6531        }
6532
6533        @Override
6534        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6535            final ViewRootImpl viewAncestor = mViewAncestor.get();
6536            if (viewAncestor != null) {
6537                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
6538            }
6539        }
6540
6541        private static int checkCallingPermission(String permission) {
6542            try {
6543                return ActivityManagerNative.getDefault().checkPermission(
6544                        permission, Binder.getCallingPid(), Binder.getCallingUid());
6545            } catch (RemoteException e) {
6546                return PackageManager.PERMISSION_DENIED;
6547            }
6548        }
6549
6550        @Override
6551        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
6552            final ViewRootImpl viewAncestor = mViewAncestor.get();
6553            if (viewAncestor != null) {
6554                final View view = viewAncestor.mView;
6555                if (view != null) {
6556                    if (checkCallingPermission(Manifest.permission.DUMP) !=
6557                            PackageManager.PERMISSION_GRANTED) {
6558                        throw new SecurityException("Insufficient permissions to invoke"
6559                                + " executeCommand() from pid=" + Binder.getCallingPid()
6560                                + ", uid=" + Binder.getCallingUid());
6561                    }
6562
6563                    OutputStream clientStream = null;
6564                    try {
6565                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
6566                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
6567                    } catch (IOException e) {
6568                        e.printStackTrace();
6569                    } finally {
6570                        if (clientStream != null) {
6571                            try {
6572                                clientStream.close();
6573                            } catch (IOException e) {
6574                                e.printStackTrace();
6575                            }
6576                        }
6577                    }
6578                }
6579            }
6580        }
6581
6582        @Override
6583        public void closeSystemDialogs(String reason) {
6584            final ViewRootImpl viewAncestor = mViewAncestor.get();
6585            if (viewAncestor != null) {
6586                viewAncestor.dispatchCloseSystemDialogs(reason);
6587            }
6588        }
6589
6590        @Override
6591        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
6592                boolean sync) {
6593            if (sync) {
6594                try {
6595                    mWindowSession.wallpaperOffsetsComplete(asBinder());
6596                } catch (RemoteException e) {
6597                }
6598            }
6599        }
6600
6601        @Override
6602        public void dispatchWallpaperCommand(String action, int x, int y,
6603                int z, Bundle extras, boolean sync) {
6604            if (sync) {
6605                try {
6606                    mWindowSession.wallpaperCommandComplete(asBinder(), null);
6607                } catch (RemoteException e) {
6608                }
6609            }
6610        }
6611
6612        /* Drag/drop */
6613        @Override
6614        public void dispatchDragEvent(DragEvent event) {
6615            final ViewRootImpl viewAncestor = mViewAncestor.get();
6616            if (viewAncestor != null) {
6617                viewAncestor.dispatchDragEvent(event);
6618            }
6619        }
6620
6621        @Override
6622        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6623                int localValue, int localChanges) {
6624            final ViewRootImpl viewAncestor = mViewAncestor.get();
6625            if (viewAncestor != null) {
6626                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
6627                        localValue, localChanges);
6628            }
6629        }
6630
6631        @Override
6632        public void doneAnimating() {
6633            final ViewRootImpl viewAncestor = mViewAncestor.get();
6634            if (viewAncestor != null) {
6635                viewAncestor.dispatchDoneAnimating();
6636            }
6637        }
6638
6639        @Override
6640        public void dispatchWindowShown() {
6641            final ViewRootImpl viewAncestor = mViewAncestor.get();
6642            if (viewAncestor != null) {
6643                viewAncestor.dispatchWindowShown();
6644            }
6645        }
6646    }
6647
6648    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
6649        public CalledFromWrongThreadException(String msg) {
6650            super(msg);
6651        }
6652    }
6653
6654    static RunQueue getRunQueue() {
6655        RunQueue rq = sRunQueues.get();
6656        if (rq != null) {
6657            return rq;
6658        }
6659        rq = new RunQueue();
6660        sRunQueues.set(rq);
6661        return rq;
6662    }
6663
6664    /**
6665     * The run queue is used to enqueue pending work from Views when no Handler is
6666     * attached.  The work is executed during the next call to performTraversals on
6667     * the thread.
6668     * @hide
6669     */
6670    static final class RunQueue {
6671        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
6672
6673        void post(Runnable action) {
6674            postDelayed(action, 0);
6675        }
6676
6677        void postDelayed(Runnable action, long delayMillis) {
6678            HandlerAction handlerAction = new HandlerAction();
6679            handlerAction.action = action;
6680            handlerAction.delay = delayMillis;
6681
6682            synchronized (mActions) {
6683                mActions.add(handlerAction);
6684            }
6685        }
6686
6687        void removeCallbacks(Runnable action) {
6688            final HandlerAction handlerAction = new HandlerAction();
6689            handlerAction.action = action;
6690
6691            synchronized (mActions) {
6692                final ArrayList<HandlerAction> actions = mActions;
6693
6694                while (actions.remove(handlerAction)) {
6695                    // Keep going
6696                }
6697            }
6698        }
6699
6700        void executeActions(Handler handler) {
6701            synchronized (mActions) {
6702                final ArrayList<HandlerAction> actions = mActions;
6703                final int count = actions.size();
6704
6705                for (int i = 0; i < count; i++) {
6706                    final HandlerAction handlerAction = actions.get(i);
6707                    handler.postDelayed(handlerAction.action, handlerAction.delay);
6708                }
6709
6710                actions.clear();
6711            }
6712        }
6713
6714        private static class HandlerAction {
6715            Runnable action;
6716            long delay;
6717
6718            @Override
6719            public boolean equals(Object o) {
6720                if (this == o) return true;
6721                if (o == null || getClass() != o.getClass()) return false;
6722
6723                HandlerAction that = (HandlerAction) o;
6724                return !(action != null ? !action.equals(that.action) : that.action != null);
6725
6726            }
6727
6728            @Override
6729            public int hashCode() {
6730                int result = action != null ? action.hashCode() : 0;
6731                result = 31 * result + (int) (delay ^ (delay >>> 32));
6732                return result;
6733            }
6734        }
6735    }
6736
6737    /**
6738     * Class for managing the accessibility interaction connection
6739     * based on the global accessibility state.
6740     */
6741    final class AccessibilityInteractionConnectionManager
6742            implements AccessibilityStateChangeListener {
6743        @Override
6744        public void onAccessibilityStateChanged(boolean enabled) {
6745            if (enabled) {
6746                ensureConnection();
6747                if (mAttachInfo.mHasWindowFocus) {
6748                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
6749                    View focusedView = mView.findFocus();
6750                    if (focusedView != null && focusedView != mView) {
6751                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6752                    }
6753                }
6754            } else {
6755                ensureNoConnection();
6756                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
6757            }
6758        }
6759
6760        public void ensureConnection() {
6761            final boolean registered =
6762                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6763            if (!registered) {
6764                mAttachInfo.mAccessibilityWindowId =
6765                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
6766                                new AccessibilityInteractionConnection(ViewRootImpl.this));
6767            }
6768        }
6769
6770        public void ensureNoConnection() {
6771            final boolean registered =
6772                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6773            if (registered) {
6774                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6775                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
6776            }
6777        }
6778    }
6779
6780    final class HighContrastTextManager implements HighTextContrastChangeListener {
6781        HighContrastTextManager() {
6782            mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
6783        }
6784        @Override
6785        public void onHighTextContrastStateChanged(boolean enabled) {
6786            mAttachInfo.mHighContrastText = enabled;
6787
6788            // Destroy Displaylists so they can be recreated with high contrast recordings
6789            destroyHardwareResources();
6790
6791            // Schedule redraw, which will rerecord + redraw all text
6792            invalidate();
6793        }
6794    }
6795
6796    /**
6797     * This class is an interface this ViewAncestor provides to the
6798     * AccessibilityManagerService to the latter can interact with
6799     * the view hierarchy in this ViewAncestor.
6800     */
6801    static final class AccessibilityInteractionConnection
6802            extends IAccessibilityInteractionConnection.Stub {
6803        private final WeakReference<ViewRootImpl> mViewRootImpl;
6804
6805        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
6806            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
6807        }
6808
6809        @Override
6810        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
6811                Region interactiveRegion, int interactionId,
6812                IAccessibilityInteractionConnectionCallback callback, int flags,
6813                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6814            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6815            if (viewRootImpl != null && viewRootImpl.mView != null) {
6816                viewRootImpl.getAccessibilityInteractionController()
6817                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
6818                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
6819                            interrogatingTid, spec);
6820            } else {
6821                // We cannot make the call and notify the caller so it does not wait.
6822                try {
6823                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6824                } catch (RemoteException re) {
6825                    /* best effort - ignore */
6826                }
6827            }
6828        }
6829
6830        @Override
6831        public void performAccessibilityAction(long accessibilityNodeId, int action,
6832                Bundle arguments, int interactionId,
6833                IAccessibilityInteractionConnectionCallback callback, int flags,
6834                int interrogatingPid, long interrogatingTid) {
6835            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6836            if (viewRootImpl != null && viewRootImpl.mView != null) {
6837                viewRootImpl.getAccessibilityInteractionController()
6838                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
6839                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
6840            } else {
6841                // We cannot make the call and notify the caller so it does not wait.
6842                try {
6843                    callback.setPerformAccessibilityActionResult(false, interactionId);
6844                } catch (RemoteException re) {
6845                    /* best effort - ignore */
6846                }
6847            }
6848        }
6849
6850        @Override
6851        public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
6852                String viewId, Region interactiveRegion, int interactionId,
6853                IAccessibilityInteractionConnectionCallback callback, int flags,
6854                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6855            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6856            if (viewRootImpl != null && viewRootImpl.mView != null) {
6857                viewRootImpl.getAccessibilityInteractionController()
6858                    .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
6859                            viewId, interactiveRegion, interactionId, callback, flags,
6860                            interrogatingPid, interrogatingTid, spec);
6861            } else {
6862                // We cannot make the call and notify the caller so it does not wait.
6863                try {
6864                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6865                } catch (RemoteException re) {
6866                    /* best effort - ignore */
6867                }
6868            }
6869        }
6870
6871        @Override
6872        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
6873                Region interactiveRegion, int interactionId,
6874                IAccessibilityInteractionConnectionCallback callback, int flags,
6875                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6876            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6877            if (viewRootImpl != null && viewRootImpl.mView != null) {
6878                viewRootImpl.getAccessibilityInteractionController()
6879                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
6880                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
6881                            interrogatingTid, spec);
6882            } else {
6883                // We cannot make the call and notify the caller so it does not wait.
6884                try {
6885                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6886                } catch (RemoteException re) {
6887                    /* best effort - ignore */
6888                }
6889            }
6890        }
6891
6892        @Override
6893        public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
6894                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6895                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6896            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6897            if (viewRootImpl != null && viewRootImpl.mView != null) {
6898                viewRootImpl.getAccessibilityInteractionController()
6899                    .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
6900                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
6901                            spec);
6902            } else {
6903                // We cannot make the call and notify the caller so it does not wait.
6904                try {
6905                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6906                } catch (RemoteException re) {
6907                    /* best effort - ignore */
6908                }
6909            }
6910        }
6911
6912        @Override
6913        public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
6914                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6915                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6916            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6917            if (viewRootImpl != null && viewRootImpl.mView != null) {
6918                viewRootImpl.getAccessibilityInteractionController()
6919                    .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
6920                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
6921                            spec);
6922            } else {
6923                // We cannot make the call and notify the caller so it does not wait.
6924                try {
6925                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6926                } catch (RemoteException re) {
6927                    /* best effort - ignore */
6928                }
6929            }
6930        }
6931    }
6932
6933    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
6934        private int mChangeTypes = 0;
6935
6936        public View mSource;
6937        public long mLastEventTimeMillis;
6938
6939        @Override
6940        public void run() {
6941            // The accessibility may be turned off while we were waiting so check again.
6942            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6943                mLastEventTimeMillis = SystemClock.uptimeMillis();
6944                AccessibilityEvent event = AccessibilityEvent.obtain();
6945                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
6946                event.setContentChangeTypes(mChangeTypes);
6947                mSource.sendAccessibilityEventUnchecked(event);
6948            } else {
6949                mLastEventTimeMillis = 0;
6950            }
6951            // In any case reset to initial state.
6952            mSource.resetSubtreeAccessibilityStateChanged();
6953            mSource = null;
6954            mChangeTypes = 0;
6955        }
6956
6957        public void runOrPost(View source, int changeType) {
6958            if (mSource != null) {
6959                // If there is no common predecessor, then mSource points to
6960                // a removed view, hence in this case always prefer the source.
6961                View predecessor = getCommonPredecessor(mSource, source);
6962                mSource = (predecessor != null) ? predecessor : source;
6963                mChangeTypes |= changeType;
6964                return;
6965            }
6966            mSource = source;
6967            mChangeTypes = changeType;
6968            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
6969            final long minEventIntevalMillis =
6970                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
6971            if (timeSinceLastMillis >= minEventIntevalMillis) {
6972                mSource.removeCallbacks(this);
6973                run();
6974            } else {
6975                mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
6976            }
6977        }
6978    }
6979}
6980