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