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