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