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