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