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