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