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