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