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