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