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