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