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