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