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