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