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