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