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