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