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