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