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