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