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