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