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