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