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