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