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