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