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