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