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