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