ViewRootImpl.java revision ae4f3204ec2c9251e0e408816e74502079cd1a6c
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
2107            if (mRenderProfiler != null) {
2108                mChoreographer.removeFrameCallback(mRenderProfiler);
2109            }
2110            if (mRenderProfilingEnabled) {
2111                if (mRenderProfiler == null) {
2112                    mRenderProfiler = new Choreographer.FrameCallback() {
2113                        @Override
2114                        public void doFrame(long frameTimeNanos) {
2115                            mDirty.set(0, 0, mWidth, mHeight);
2116                            scheduleTraversals();
2117                            if (mRenderProfilingEnabled) {
2118                                mChoreographer.postFrameCallback(mRenderProfiler);
2119                            }
2120                        }
2121                    };
2122                }
2123                mChoreographer.postFrameCallback(mRenderProfiler);
2124            } else {
2125                mRenderProfiler = null;
2126            }
2127        }
2128    }
2129
2130    /**
2131     * Called from draw() when DEBUG_FPS is enabled
2132     */
2133    private void trackFPS() {
2134        // Tracks frames per second drawn. First value in a series of draws may be bogus
2135        // because it down not account for the intervening idle time
2136        long nowTime = System.currentTimeMillis();
2137        if (mFpsStartTime < 0) {
2138            mFpsStartTime = mFpsPrevTime = nowTime;
2139            mFpsNumFrames = 0;
2140        } else {
2141            ++mFpsNumFrames;
2142            String thisHash = Integer.toHexString(System.identityHashCode(this));
2143            long frameTime = nowTime - mFpsPrevTime;
2144            long totalTime = nowTime - mFpsStartTime;
2145            Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime);
2146            mFpsPrevTime = nowTime;
2147            if (totalTime > 1000) {
2148                float fps = (float) mFpsNumFrames * 1000 / totalTime;
2149                Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps);
2150                mFpsStartTime = nowTime;
2151                mFpsNumFrames = 0;
2152            }
2153        }
2154    }
2155
2156    private void performDraw() {
2157        if (!mAttachInfo.mScreenOn && !mReportNextDraw) {
2158            return;
2159        }
2160
2161        final boolean fullRedrawNeeded = mFullRedrawNeeded;
2162        mFullRedrawNeeded = false;
2163
2164        mIsDrawing = true;
2165        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2166        try {
2167            draw(fullRedrawNeeded);
2168        } finally {
2169            mIsDrawing = false;
2170            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2171        }
2172
2173        if (mReportNextDraw) {
2174            mReportNextDraw = false;
2175
2176            if (LOCAL_LOGV) {
2177                Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2178            }
2179            if (mSurfaceHolder != null && mSurface.isValid()) {
2180                mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2181                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2182                if (callbacks != null) {
2183                    for (SurfaceHolder.Callback c : callbacks) {
2184                        if (c instanceof SurfaceHolder.Callback2) {
2185                            ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
2186                                    mSurfaceHolder);
2187                        }
2188                    }
2189                }
2190            }
2191            try {
2192                mWindowSession.finishDrawing(mWindow);
2193            } catch (RemoteException e) {
2194            }
2195        }
2196    }
2197
2198    private void draw(boolean fullRedrawNeeded) {
2199        Surface surface = mSurface;
2200        if (!surface.isValid()) {
2201            return;
2202        }
2203
2204        if (DEBUG_FPS) {
2205            trackFPS();
2206        }
2207
2208        if (!sFirstDrawComplete) {
2209            synchronized (sFirstDrawHandlers) {
2210                sFirstDrawComplete = true;
2211                final int count = sFirstDrawHandlers.size();
2212                for (int i = 0; i< count; i++) {
2213                    mHandler.post(sFirstDrawHandlers.get(i));
2214                }
2215            }
2216        }
2217
2218        scrollToRectOrFocus(null, false);
2219
2220        final AttachInfo attachInfo = mAttachInfo;
2221        if (attachInfo.mViewScrollChanged) {
2222            attachInfo.mViewScrollChanged = false;
2223            attachInfo.mTreeObserver.dispatchOnScrollChanged();
2224        }
2225
2226        int yoff;
2227        boolean animating = mScroller != null && mScroller.computeScrollOffset();
2228        if (animating) {
2229            yoff = mScroller.getCurrY();
2230        } else {
2231            yoff = mScrollY;
2232        }
2233        if (mCurScrollY != yoff) {
2234            mCurScrollY = yoff;
2235            fullRedrawNeeded = true;
2236        }
2237
2238        final float appScale = attachInfo.mApplicationScale;
2239        final boolean scalingRequired = attachInfo.mScalingRequired;
2240
2241        int resizeAlpha = 0;
2242        if (mResizeBuffer != null) {
2243            long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
2244            if (deltaTime < mResizeBufferDuration) {
2245                float amt = deltaTime/(float) mResizeBufferDuration;
2246                amt = mResizeInterpolator.getInterpolation(amt);
2247                animating = true;
2248                resizeAlpha = 255 - (int)(amt*255);
2249            } else {
2250                disposeResizeBuffer();
2251            }
2252        }
2253
2254        final Rect dirty = mDirty;
2255        if (mSurfaceHolder != null) {
2256            // The app owns the surface, we won't draw.
2257            dirty.setEmpty();
2258            if (animating) {
2259                if (mScroller != null) {
2260                    mScroller.abortAnimation();
2261                }
2262                disposeResizeBuffer();
2263            }
2264            return;
2265        }
2266
2267        if (fullRedrawNeeded) {
2268            attachInfo.mIgnoreDirtyState = true;
2269            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2270        }
2271
2272        if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2273            Log.v(TAG, "Draw " + mView + "/"
2274                    + mWindowAttributes.getTitle()
2275                    + ": dirty={" + dirty.left + "," + dirty.top
2276                    + "," + dirty.right + "," + dirty.bottom + "} surface="
2277                    + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2278                    appScale + ", width=" + mWidth + ", height=" + mHeight);
2279        }
2280
2281        invalidateDisplayLists();
2282
2283        attachInfo.mTreeObserver.dispatchOnDraw();
2284
2285        if (!dirty.isEmpty() || mIsAnimating) {
2286            if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) {
2287                // Draw with hardware renderer.
2288                mIsAnimating = false;
2289                mHardwareYOffset = yoff;
2290                mResizeAlpha = resizeAlpha;
2291
2292                mCurrentDirty.set(dirty);
2293                mCurrentDirty.union(mPreviousDirty);
2294                mPreviousDirty.set(dirty);
2295                dirty.setEmpty();
2296
2297                if (attachInfo.mHardwareRenderer.draw(mView, attachInfo, this,
2298                        animating ? null : mCurrentDirty)) {
2299                    mPreviousDirty.set(0, 0, mWidth, mHeight);
2300                }
2301            } else {
2302                // If we get here with a disabled & requested hardware renderer, something went
2303                // wrong (an invalidate posted right before we destroyed the hardware surface
2304                // for instance) so we should just bail out. Locking the surface with software
2305                // rendering at this point would lock it forever and prevent hardware renderer
2306                // from doing its job when it comes back.
2307                // Before we request a new frame we must however attempt to reinitiliaze the
2308                // hardware renderer if it's in requested state. This would happen after an
2309                // eglTerminate() for instance.
2310                if (attachInfo.mHardwareRenderer != null &&
2311                        !attachInfo.mHardwareRenderer.isEnabled() &&
2312                        attachInfo.mHardwareRenderer.isRequested()) {
2313
2314                    try {
2315                        attachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2316                                mHolder.getSurface());
2317                    } catch (Surface.OutOfResourcesException e) {
2318                        handleOutOfResourcesException(e);
2319                        return;
2320                    }
2321
2322                    mFullRedrawNeeded = true;
2323                    scheduleTraversals();
2324                    return;
2325                }
2326
2327                if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) {
2328                    return;
2329                }
2330            }
2331        }
2332
2333        if (animating) {
2334            mFullRedrawNeeded = true;
2335            scheduleTraversals();
2336        }
2337    }
2338
2339    /**
2340     * @return true if drawing was succesfull, false if an error occurred
2341     */
2342    private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff,
2343            boolean scalingRequired, Rect dirty) {
2344
2345        // Draw with software renderer.
2346        Canvas canvas;
2347        try {
2348            int left = dirty.left;
2349            int top = dirty.top;
2350            int right = dirty.right;
2351            int bottom = dirty.bottom;
2352
2353            canvas = mSurface.lockCanvas(dirty);
2354
2355            if (left != dirty.left || top != dirty.top || right != dirty.right ||
2356                    bottom != dirty.bottom) {
2357                attachInfo.mIgnoreDirtyState = true;
2358            }
2359
2360            // TODO: Do this in native
2361            canvas.setDensity(mDensity);
2362        } catch (Surface.OutOfResourcesException e) {
2363            handleOutOfResourcesException(e);
2364            return false;
2365        } catch (IllegalArgumentException e) {
2366            Log.e(TAG, "Could not lock surface", e);
2367            // Don't assume this is due to out of memory, it could be
2368            // something else, and if it is something else then we could
2369            // kill stuff (or ourself) for no reason.
2370            mLayoutRequested = true;    // ask wm for a new surface next time.
2371            return false;
2372        }
2373
2374        try {
2375            if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2376                Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
2377                        + canvas.getWidth() + ", h=" + canvas.getHeight());
2378                //canvas.drawARGB(255, 255, 0, 0);
2379            }
2380
2381            // If this bitmap's format includes an alpha channel, we
2382            // need to clear it before drawing so that the child will
2383            // properly re-composite its drawing on a transparent
2384            // background. This automatically respects the clip/dirty region
2385            // or
2386            // If we are applying an offset, we need to clear the area
2387            // where the offset doesn't appear to avoid having garbage
2388            // left in the blank areas.
2389            if (!canvas.isOpaque() || yoff != 0) {
2390                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2391            }
2392
2393            dirty.setEmpty();
2394            mIsAnimating = false;
2395            attachInfo.mDrawingTime = SystemClock.uptimeMillis();
2396            mView.mPrivateFlags |= View.PFLAG_DRAWN;
2397
2398            if (DEBUG_DRAW) {
2399                Context cxt = mView.getContext();
2400                Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
2401                        ", metrics=" + cxt.getResources().getDisplayMetrics() +
2402                        ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2403            }
2404            try {
2405                canvas.translate(0, -yoff);
2406                if (mTranslator != null) {
2407                    mTranslator.translateCanvas(canvas);
2408                }
2409                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2410                attachInfo.mSetIgnoreDirtyState = false;
2411
2412                mView.draw(canvas);
2413
2414                drawAccessibilityFocusedDrawableIfNeeded(canvas);
2415            } finally {
2416                if (!attachInfo.mSetIgnoreDirtyState) {
2417                    // Only clear the flag if it was not set during the mView.draw() call
2418                    attachInfo.mIgnoreDirtyState = false;
2419                }
2420            }
2421        } finally {
2422            try {
2423                surface.unlockCanvasAndPost(canvas);
2424            } catch (IllegalArgumentException e) {
2425                Log.e(TAG, "Could not unlock surface", e);
2426                mLayoutRequested = true;    // ask wm for a new surface next time.
2427                //noinspection ReturnInsideFinallyBlock
2428                return false;
2429            }
2430
2431            if (LOCAL_LOGV) {
2432                Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
2433            }
2434        }
2435        return true;
2436    }
2437
2438    /**
2439     * We want to draw a highlight around the current accessibility focused.
2440     * Since adding a style for all possible view is not a viable option we
2441     * have this specialized drawing method.
2442     *
2443     * Note: We are doing this here to be able to draw the highlight for
2444     *       virtual views in addition to real ones.
2445     *
2446     * @param canvas The canvas on which to draw.
2447     */
2448    private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2449        AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2450        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2451            return;
2452        }
2453        if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) {
2454            return;
2455        }
2456        Drawable drawable = getAccessibilityFocusedDrawable();
2457        if (drawable == null) {
2458            return;
2459        }
2460        AccessibilityNodeProvider provider =
2461            mAccessibilityFocusedHost.getAccessibilityNodeProvider();
2462        Rect bounds = mView.mAttachInfo.mTmpInvalRect;
2463        if (provider == null) {
2464            mAccessibilityFocusedHost.getBoundsOnScreen(bounds);
2465        } else {
2466            if (mAccessibilityFocusedVirtualView == null) {
2467                return;
2468            }
2469            mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2470        }
2471        bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
2472        bounds.intersect(0, 0, mAttachInfo.mViewRootImpl.mWidth, mAttachInfo.mViewRootImpl.mHeight);
2473        drawable.setBounds(bounds);
2474        drawable.draw(canvas);
2475    }
2476
2477    private Drawable getAccessibilityFocusedDrawable() {
2478        if (mAttachInfo != null) {
2479            // Lazily load the accessibility focus drawable.
2480            if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2481                TypedValue value = new TypedValue();
2482                final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2483                        R.attr.accessibilityFocusedDrawable, value, true);
2484                if (resolved) {
2485                    mAttachInfo.mAccessibilityFocusDrawable =
2486                        mView.mContext.getResources().getDrawable(value.resourceId);
2487                }
2488            }
2489            return mAttachInfo.mAccessibilityFocusDrawable;
2490        }
2491        return null;
2492    }
2493
2494    void invalidateDisplayLists() {
2495        final ArrayList<DisplayList> displayLists = mDisplayLists;
2496        final int count = displayLists.size();
2497
2498        for (int i = 0; i < count; i++) {
2499            final DisplayList displayList = displayLists.get(i);
2500            if (displayList.isDirty()) {
2501                displayList.invalidate();
2502                displayList.clear();
2503                displayList.setDirty(false);
2504            }
2505        }
2506
2507        displayLists.clear();
2508    }
2509
2510    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2511        final View.AttachInfo attachInfo = mAttachInfo;
2512        final Rect ci = attachInfo.mContentInsets;
2513        final Rect vi = attachInfo.mVisibleInsets;
2514        int scrollY = 0;
2515        boolean handled = false;
2516
2517        if (vi.left > ci.left || vi.top > ci.top
2518                || vi.right > ci.right || vi.bottom > ci.bottom) {
2519            // We'll assume that we aren't going to change the scroll
2520            // offset, since we want to avoid that unless it is actually
2521            // going to make the focus visible...  otherwise we scroll
2522            // all over the place.
2523            scrollY = mScrollY;
2524            // We can be called for two different situations: during a draw,
2525            // to update the scroll position if the focus has changed (in which
2526            // case 'rectangle' is null), or in response to a
2527            // requestChildRectangleOnScreen() call (in which case 'rectangle'
2528            // is non-null and we just want to scroll to whatever that
2529            // rectangle is).
2530            View focus = mView.findFocus();
2531            if (focus == null) {
2532                return false;
2533            }
2534            View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
2535            if (lastScrolledFocus != null && focus != lastScrolledFocus) {
2536                // If the focus has changed, then ignore any requests to scroll
2537                // to a rectangle; first we want to make sure the entire focus
2538                // view is visible.
2539                rectangle = null;
2540            }
2541            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2542                    + " rectangle=" + rectangle + " ci=" + ci
2543                    + " vi=" + vi);
2544            if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) {
2545                // Optimization: if the focus hasn't changed since last
2546                // time, and no layout has happened, then just leave things
2547                // as they are.
2548                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2549                        + mScrollY + " vi=" + vi.toShortString());
2550            } else if (focus != null) {
2551                // We need to determine if the currently focused view is
2552                // within the visible part of the window and, if not, apply
2553                // a pan so it can be seen.
2554                mLastScrolledFocus = new WeakReference<View>(focus);
2555                mScrollMayChange = false;
2556                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2557                // Try to find the rectangle from the focus view.
2558                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2559                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2560                            + mView.getWidth() + " h=" + mView.getHeight()
2561                            + " ci=" + ci.toShortString()
2562                            + " vi=" + vi.toShortString());
2563                    if (rectangle == null) {
2564                        focus.getFocusedRect(mTempRect);
2565                        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2566                                + ": focusRect=" + mTempRect.toShortString());
2567                        if (mView instanceof ViewGroup) {
2568                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2569                                    focus, mTempRect);
2570                        }
2571                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2572                                "Focus in window: focusRect="
2573                                + mTempRect.toShortString()
2574                                + " visRect=" + mVisRect.toShortString());
2575                    } else {
2576                        mTempRect.set(rectangle);
2577                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2578                                "Request scroll to rect: "
2579                                + mTempRect.toShortString()
2580                                + " visRect=" + mVisRect.toShortString());
2581                    }
2582                    if (mTempRect.intersect(mVisRect)) {
2583                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2584                                "Focus window visible rect: "
2585                                + mTempRect.toShortString());
2586                        if (mTempRect.height() >
2587                                (mView.getHeight()-vi.top-vi.bottom)) {
2588                            // If the focus simply is not going to fit, then
2589                            // best is probably just to leave things as-is.
2590                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2591                                    "Too tall; leaving scrollY=" + scrollY);
2592                        } else if ((mTempRect.top-scrollY) < vi.top) {
2593                            scrollY -= vi.top - (mTempRect.top-scrollY);
2594                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2595                                    "Top covered; scrollY=" + scrollY);
2596                        } else if ((mTempRect.bottom-scrollY)
2597                                > (mView.getHeight()-vi.bottom)) {
2598                            scrollY += (mTempRect.bottom-scrollY)
2599                                    - (mView.getHeight()-vi.bottom);
2600                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2601                                    "Bottom covered; scrollY=" + scrollY);
2602                        }
2603                        handled = true;
2604                    }
2605                }
2606            }
2607        }
2608
2609        if (scrollY != mScrollY) {
2610            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2611                    + mScrollY + " , new=" + scrollY);
2612            if (!immediate && mResizeBuffer == null) {
2613                if (mScroller == null) {
2614                    mScroller = new Scroller(mView.getContext());
2615                }
2616                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2617            } else if (mScroller != null) {
2618                mScroller.abortAnimation();
2619            }
2620            mScrollY = scrollY;
2621        }
2622
2623        return handled;
2624    }
2625
2626    /**
2627     * @hide
2628     */
2629    public View getAccessibilityFocusedHost() {
2630        return mAccessibilityFocusedHost;
2631    }
2632
2633    /**
2634     * @hide
2635     */
2636    public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
2637        return mAccessibilityFocusedVirtualView;
2638    }
2639
2640    void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
2641        // If we have a virtual view with accessibility focus we need
2642        // to clear the focus and invalidate the virtual view bounds.
2643        if (mAccessibilityFocusedVirtualView != null) {
2644
2645            AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
2646            View focusHost = mAccessibilityFocusedHost;
2647            focusHost.clearAccessibilityFocusNoCallbacks();
2648
2649            // Wipe the state of the current accessibility focus since
2650            // the call into the provider to clear accessibility focus
2651            // will fire an accessibility event which will end up calling
2652            // this method and we want to have clean state when this
2653            // invocation happens.
2654            mAccessibilityFocusedHost = null;
2655            mAccessibilityFocusedVirtualView = null;
2656
2657            AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
2658            if (provider != null) {
2659                // Invalidate the area of the cleared accessibility focus.
2660                focusNode.getBoundsInParent(mTempRect);
2661                focusHost.invalidate(mTempRect);
2662                // Clear accessibility focus in the virtual node.
2663                final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
2664                        focusNode.getSourceNodeId());
2665                provider.performAction(virtualNodeId,
2666                        AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
2667            }
2668            focusNode.recycle();
2669        }
2670        if (mAccessibilityFocusedHost != null) {
2671            // Clear accessibility focus in the view.
2672            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2673        }
2674
2675        // Set the new focus host and node.
2676        mAccessibilityFocusedHost = view;
2677        mAccessibilityFocusedVirtualView = node;
2678    }
2679
2680    public void requestChildFocus(View child, View focused) {
2681        if (DEBUG_INPUT_RESIZE) {
2682            Log.v(TAG, "Request child focus: focus now " + focused);
2683        }
2684        checkThread();
2685        scheduleTraversals();
2686    }
2687
2688    public void clearChildFocus(View child) {
2689        if (DEBUG_INPUT_RESIZE) {
2690            Log.v(TAG, "Clearing child focus");
2691        }
2692        checkThread();
2693        scheduleTraversals();
2694    }
2695
2696    @Override
2697    public ViewParent getParentForAccessibility() {
2698        return null;
2699    }
2700
2701    public void focusableViewAvailable(View v) {
2702        checkThread();
2703        if (mView != null) {
2704            if (!mView.hasFocus()) {
2705                v.requestFocus();
2706            } else {
2707                // the one case where will transfer focus away from the current one
2708                // is if the current view is a view group that prefers to give focus
2709                // to its children first AND the view is a descendant of it.
2710                View focused = mView.findFocus();
2711                if (focused instanceof ViewGroup) {
2712                    ViewGroup group = (ViewGroup) focused;
2713                    if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2714                            && isViewDescendantOf(v, focused)) {
2715                        v.requestFocus();
2716                    }
2717                }
2718            }
2719        }
2720    }
2721
2722    public void recomputeViewAttributes(View child) {
2723        checkThread();
2724        if (mView == child) {
2725            mAttachInfo.mRecomputeGlobalAttributes = true;
2726            if (!mWillDrawSoon) {
2727                scheduleTraversals();
2728            }
2729        }
2730    }
2731
2732    void dispatchDetachedFromWindow() {
2733        if (mView != null && mView.mAttachInfo != null) {
2734            if (mAttachInfo.mHardwareRenderer != null &&
2735                    mAttachInfo.mHardwareRenderer.isEnabled()) {
2736                mAttachInfo.mHardwareRenderer.validate();
2737            }
2738            mView.dispatchDetachedFromWindow();
2739        }
2740
2741        mAccessibilityInteractionConnectionManager.ensureNoConnection();
2742        mAccessibilityManager.removeAccessibilityStateChangeListener(
2743                mAccessibilityInteractionConnectionManager);
2744        removeSendWindowContentChangedCallback();
2745
2746        destroyHardwareRenderer();
2747
2748        setAccessibilityFocus(null, null);
2749
2750        mView = null;
2751        mAttachInfo.mRootView = null;
2752        mAttachInfo.mSurface = null;
2753
2754        mSurface.release();
2755
2756        if (mInputQueueCallback != null && mInputQueue != null) {
2757            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2758            mInputQueueCallback = null;
2759            mInputQueue = null;
2760        } else if (mInputEventReceiver != null) {
2761            mInputEventReceiver.dispose();
2762            mInputEventReceiver = null;
2763        }
2764        try {
2765            mWindowSession.remove(mWindow);
2766        } catch (RemoteException e) {
2767        }
2768
2769        // Dispose the input channel after removing the window so the Window Manager
2770        // doesn't interpret the input channel being closed as an abnormal termination.
2771        if (mInputChannel != null) {
2772            mInputChannel.dispose();
2773            mInputChannel = null;
2774        }
2775
2776        unscheduleTraversals();
2777    }
2778
2779    void updateConfiguration(Configuration config, boolean force) {
2780        if (DEBUG_CONFIGURATION) Log.v(TAG,
2781                "Applying new config to window "
2782                + mWindowAttributes.getTitle()
2783                + ": " + config);
2784
2785        CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2786        if (ci != null) {
2787            config = new Configuration(config);
2788            ci.applyToConfiguration(mNoncompatDensity, config);
2789        }
2790
2791        synchronized (sConfigCallbacks) {
2792            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2793                sConfigCallbacks.get(i).onConfigurationChanged(config);
2794            }
2795        }
2796        if (mView != null) {
2797            // At this point the resources have been updated to
2798            // have the most recent config, whatever that is.  Use
2799            // the one in them which may be newer.
2800            config = mView.getResources().getConfiguration();
2801            if (force || mLastConfiguration.diff(config) != 0) {
2802                final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
2803                final int currentLayoutDirection = config.getLayoutDirection();
2804                mLastConfiguration.setTo(config);
2805                if (lastLayoutDirection != currentLayoutDirection &&
2806                        mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
2807                    mView.setLayoutDirection(currentLayoutDirection);
2808                }
2809                mView.dispatchConfigurationChanged(config);
2810            }
2811        }
2812    }
2813
2814    /**
2815     * Return true if child is an ancestor of parent, (or equal to the parent).
2816     */
2817    public static boolean isViewDescendantOf(View child, View parent) {
2818        if (child == parent) {
2819            return true;
2820        }
2821
2822        final ViewParent theParent = child.getParent();
2823        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2824    }
2825
2826    private static void forceLayout(View view) {
2827        view.forceLayout();
2828        if (view instanceof ViewGroup) {
2829            ViewGroup group = (ViewGroup) view;
2830            final int count = group.getChildCount();
2831            for (int i = 0; i < count; i++) {
2832                forceLayout(group.getChildAt(i));
2833            }
2834        }
2835    }
2836
2837    private final static int MSG_INVALIDATE = 1;
2838    private final static int MSG_INVALIDATE_RECT = 2;
2839    private final static int MSG_DIE = 3;
2840    private final static int MSG_RESIZED = 4;
2841    private final static int MSG_RESIZED_REPORT = 5;
2842    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
2843    private final static int MSG_DISPATCH_KEY = 7;
2844    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
2845    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
2846    private final static int MSG_IME_FINISHED_EVENT = 10;
2847    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
2848    private final static int MSG_FINISH_INPUT_CONNECTION = 12;
2849    private final static int MSG_CHECK_FOCUS = 13;
2850    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
2851    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
2852    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
2853    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
2854    private final static int MSG_UPDATE_CONFIGURATION = 18;
2855    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
2856    private final static int MSG_DISPATCH_SCREEN_STATE = 20;
2857    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
2858    private final static int MSG_DISPATCH_DONE_ANIMATING = 22;
2859    private final static int MSG_INVALIDATE_WORLD = 23;
2860    private final static int MSG_WINDOW_MOVED = 24;
2861
2862    final class ViewRootHandler extends Handler {
2863        @Override
2864        public String getMessageName(Message message) {
2865            switch (message.what) {
2866                case MSG_INVALIDATE:
2867                    return "MSG_INVALIDATE";
2868                case MSG_INVALIDATE_RECT:
2869                    return "MSG_INVALIDATE_RECT";
2870                case MSG_DIE:
2871                    return "MSG_DIE";
2872                case MSG_RESIZED:
2873                    return "MSG_RESIZED";
2874                case MSG_RESIZED_REPORT:
2875                    return "MSG_RESIZED_REPORT";
2876                case MSG_WINDOW_FOCUS_CHANGED:
2877                    return "MSG_WINDOW_FOCUS_CHANGED";
2878                case MSG_DISPATCH_KEY:
2879                    return "MSG_DISPATCH_KEY";
2880                case MSG_DISPATCH_APP_VISIBILITY:
2881                    return "MSG_DISPATCH_APP_VISIBILITY";
2882                case MSG_DISPATCH_GET_NEW_SURFACE:
2883                    return "MSG_DISPATCH_GET_NEW_SURFACE";
2884                case MSG_IME_FINISHED_EVENT:
2885                    return "MSG_IME_FINISHED_EVENT";
2886                case MSG_DISPATCH_KEY_FROM_IME:
2887                    return "MSG_DISPATCH_KEY_FROM_IME";
2888                case MSG_FINISH_INPUT_CONNECTION:
2889                    return "MSG_FINISH_INPUT_CONNECTION";
2890                case MSG_CHECK_FOCUS:
2891                    return "MSG_CHECK_FOCUS";
2892                case MSG_CLOSE_SYSTEM_DIALOGS:
2893                    return "MSG_CLOSE_SYSTEM_DIALOGS";
2894                case MSG_DISPATCH_DRAG_EVENT:
2895                    return "MSG_DISPATCH_DRAG_EVENT";
2896                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
2897                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
2898                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
2899                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
2900                case MSG_UPDATE_CONFIGURATION:
2901                    return "MSG_UPDATE_CONFIGURATION";
2902                case MSG_PROCESS_INPUT_EVENTS:
2903                    return "MSG_PROCESS_INPUT_EVENTS";
2904                case MSG_DISPATCH_SCREEN_STATE:
2905                    return "MSG_DISPATCH_SCREEN_STATE";
2906                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
2907                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
2908                case MSG_DISPATCH_DONE_ANIMATING:
2909                    return "MSG_DISPATCH_DONE_ANIMATING";
2910                case MSG_WINDOW_MOVED:
2911                    return "MSG_WINDOW_MOVED";
2912            }
2913            return super.getMessageName(message);
2914        }
2915
2916        @Override
2917        public void handleMessage(Message msg) {
2918            switch (msg.what) {
2919            case MSG_INVALIDATE:
2920                ((View) msg.obj).invalidate();
2921                break;
2922            case MSG_INVALIDATE_RECT:
2923                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2924                info.target.invalidate(info.left, info.top, info.right, info.bottom);
2925                info.recycle();
2926                break;
2927            case MSG_IME_FINISHED_EVENT:
2928                handleImeFinishedEvent(msg.arg1, msg.arg2 != 0);
2929                break;
2930            case MSG_PROCESS_INPUT_EVENTS:
2931                mProcessInputEventsScheduled = false;
2932                doProcessInputEvents();
2933                break;
2934            case MSG_DISPATCH_APP_VISIBILITY:
2935                handleAppVisibility(msg.arg1 != 0);
2936                break;
2937            case MSG_DISPATCH_GET_NEW_SURFACE:
2938                handleGetNewSurface();
2939                break;
2940            case MSG_RESIZED: {
2941                // Recycled in the fall through...
2942                SomeArgs args = (SomeArgs) msg.obj;
2943                if (mWinFrame.equals(args.arg1)
2944                        && mPendingContentInsets.equals(args.arg2)
2945                        && mPendingVisibleInsets.equals(args.arg3)
2946                        && args.arg4 == null) {
2947                    break;
2948                }
2949                } // fall through...
2950            case MSG_RESIZED_REPORT:
2951                if (mAdded) {
2952                    SomeArgs args = (SomeArgs) msg.obj;
2953
2954                    Configuration config = (Configuration) args.arg4;
2955                    if (config != null) {
2956                        updateConfiguration(config, false);
2957                    }
2958
2959                    mWinFrame.set((Rect) args.arg1);
2960                    mPendingContentInsets.set((Rect) args.arg2);
2961                    mPendingVisibleInsets.set((Rect) args.arg3);
2962
2963                    args.recycle();
2964
2965                    if (msg.what == MSG_RESIZED_REPORT) {
2966                        mReportNextDraw = true;
2967                    }
2968
2969                    if (mView != null) {
2970                        forceLayout(mView);
2971                    }
2972
2973                    requestLayout();
2974                }
2975                break;
2976            case MSG_WINDOW_MOVED:
2977                if (mAdded) {
2978                    final int w = mWinFrame.width();
2979                    final int h = mWinFrame.height();
2980                    final int l = msg.arg1;
2981                    final int t = msg.arg2;
2982                    mWinFrame.left = l;
2983                    mWinFrame.right = l + w;
2984                    mWinFrame.top = t;
2985                    mWinFrame.bottom = t + h;
2986
2987                    if (mView != null) {
2988                        forceLayout(mView);
2989                    }
2990                    requestLayout();
2991                }
2992                break;
2993            case MSG_WINDOW_FOCUS_CHANGED: {
2994                if (mAdded) {
2995                    boolean hasWindowFocus = msg.arg1 != 0;
2996                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
2997
2998                    profileRendering(hasWindowFocus);
2999
3000                    if (hasWindowFocus) {
3001                        boolean inTouchMode = msg.arg2 != 0;
3002                        ensureTouchModeLocally(inTouchMode);
3003
3004                        if (mAttachInfo.mHardwareRenderer != null &&
3005                                mSurface != null && mSurface.isValid()) {
3006                            mFullRedrawNeeded = true;
3007                            try {
3008                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3009                                        mWidth, mHeight, mHolder.getSurface());
3010                            } catch (Surface.OutOfResourcesException e) {
3011                                Log.e(TAG, "OutOfResourcesException locking surface", e);
3012                                try {
3013                                    if (!mWindowSession.outOfMemory(mWindow)) {
3014                                        Slog.w(TAG, "No processes killed for memory; killing self");
3015                                        Process.killProcess(Process.myPid());
3016                                    }
3017                                } catch (RemoteException ex) {
3018                                }
3019                                // Retry in a bit.
3020                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3021                                return;
3022                            }
3023                        }
3024                    }
3025
3026                    mLastWasImTarget = WindowManager.LayoutParams
3027                            .mayUseInputMethod(mWindowAttributes.flags);
3028
3029                    InputMethodManager imm = InputMethodManager.peekInstance();
3030                    if (mView != null) {
3031                        if (hasWindowFocus && imm != null && mLastWasImTarget) {
3032                            imm.startGettingWindowFocus(mView);
3033                        }
3034                        mAttachInfo.mKeyDispatchState.reset();
3035                        mView.dispatchWindowFocusChanged(hasWindowFocus);
3036                    }
3037
3038                    // Note: must be done after the focus change callbacks,
3039                    // so all of the view state is set up correctly.
3040                    if (hasWindowFocus) {
3041                        if (imm != null && mLastWasImTarget) {
3042                            imm.onWindowFocus(mView, mView.findFocus(),
3043                                    mWindowAttributes.softInputMode,
3044                                    !mHasHadWindowFocus, mWindowAttributes.flags);
3045                        }
3046                        // Clear the forward bit.  We can just do this directly, since
3047                        // the window manager doesn't care about it.
3048                        mWindowAttributes.softInputMode &=
3049                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3050                        ((WindowManager.LayoutParams)mView.getLayoutParams())
3051                                .softInputMode &=
3052                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3053                        mHasHadWindowFocus = true;
3054                    }
3055
3056                    setAccessibilityFocus(null, null);
3057
3058                    if (mView != null && mAccessibilityManager.isEnabled()) {
3059                        if (hasWindowFocus) {
3060                            mView.sendAccessibilityEvent(
3061                                    AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3062                        }
3063                    }
3064                }
3065            } break;
3066            case MSG_DIE:
3067                doDie();
3068                break;
3069            case MSG_DISPATCH_KEY: {
3070                KeyEvent event = (KeyEvent)msg.obj;
3071                enqueueInputEvent(event, null, 0, true);
3072            } break;
3073            case MSG_DISPATCH_KEY_FROM_IME: {
3074                if (LOCAL_LOGV) Log.v(
3075                    TAG, "Dispatching key "
3076                    + msg.obj + " from IME to " + mView);
3077                KeyEvent event = (KeyEvent)msg.obj;
3078                if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3079                    // The IME is trying to say this event is from the
3080                    // system!  Bad bad bad!
3081                    //noinspection UnusedAssignment
3082                    event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
3083                }
3084                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3085            } break;
3086            case MSG_FINISH_INPUT_CONNECTION: {
3087                InputMethodManager imm = InputMethodManager.peekInstance();
3088                if (imm != null) {
3089                    imm.reportFinishInputConnection((InputConnection)msg.obj);
3090                }
3091            } break;
3092            case MSG_CHECK_FOCUS: {
3093                InputMethodManager imm = InputMethodManager.peekInstance();
3094                if (imm != null) {
3095                    imm.checkFocus();
3096                }
3097            } break;
3098            case MSG_CLOSE_SYSTEM_DIALOGS: {
3099                if (mView != null) {
3100                    mView.onCloseSystemDialogs((String)msg.obj);
3101                }
3102            } break;
3103            case MSG_DISPATCH_DRAG_EVENT:
3104            case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3105                DragEvent event = (DragEvent)msg.obj;
3106                event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
3107                handleDragEvent(event);
3108            } break;
3109            case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3110                handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3111            } break;
3112            case MSG_UPDATE_CONFIGURATION: {
3113                Configuration config = (Configuration)msg.obj;
3114                if (config.isOtherSeqNewer(mLastConfiguration)) {
3115                    config = mLastConfiguration;
3116                }
3117                updateConfiguration(config, false);
3118            } break;
3119            case MSG_DISPATCH_SCREEN_STATE: {
3120                if (mView != null) {
3121                    handleScreenStateChange(msg.arg1 == 1);
3122                }
3123            } break;
3124            case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3125                setAccessibilityFocus(null, null);
3126            } break;
3127            case MSG_DISPATCH_DONE_ANIMATING: {
3128                handleDispatchDoneAnimating();
3129            } break;
3130            case MSG_INVALIDATE_WORLD: {
3131                if (mView != null) {
3132                    invalidateWorld(mView);
3133                }
3134            } break;
3135            }
3136        }
3137    }
3138
3139    final ViewRootHandler mHandler = new ViewRootHandler();
3140
3141    /**
3142     * Something in the current window tells us we need to change the touch mode.  For
3143     * example, we are not in touch mode, and the user touches the screen.
3144     *
3145     * If the touch mode has changed, tell the window manager, and handle it locally.
3146     *
3147     * @param inTouchMode Whether we want to be in touch mode.
3148     * @return True if the touch mode changed and focus changed was changed as a result
3149     */
3150    boolean ensureTouchMode(boolean inTouchMode) {
3151        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3152                + "touch mode is " + mAttachInfo.mInTouchMode);
3153        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3154
3155        // tell the window manager
3156        try {
3157            mWindowSession.setInTouchMode(inTouchMode);
3158        } catch (RemoteException e) {
3159            throw new RuntimeException(e);
3160        }
3161
3162        // handle the change
3163        return ensureTouchModeLocally(inTouchMode);
3164    }
3165
3166    /**
3167     * Ensure that the touch mode for this window is set, and if it is changing,
3168     * take the appropriate action.
3169     * @param inTouchMode Whether we want to be in touch mode.
3170     * @return True if the touch mode changed and focus changed was changed as a result
3171     */
3172    private boolean ensureTouchModeLocally(boolean inTouchMode) {
3173        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3174                + "touch mode is " + mAttachInfo.mInTouchMode);
3175
3176        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3177
3178        mAttachInfo.mInTouchMode = inTouchMode;
3179        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3180
3181        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3182    }
3183
3184    private boolean enterTouchMode() {
3185        if (mView != null) {
3186            if (mView.hasFocus()) {
3187                // note: not relying on mFocusedView here because this could
3188                // be when the window is first being added, and mFocused isn't
3189                // set yet.
3190                final View focused = mView.findFocus();
3191                if (focused != null && !focused.isFocusableInTouchMode()) {
3192                    final ViewGroup ancestorToTakeFocus =
3193                            findAncestorToTakeFocusInTouchMode(focused);
3194                    if (ancestorToTakeFocus != null) {
3195                        // there is an ancestor that wants focus after its descendants that
3196                        // is focusable in touch mode.. give it focus
3197                        return ancestorToTakeFocus.requestFocus();
3198                    } else {
3199                        // nothing appropriate to have focus in touch mode, clear it out
3200                        focused.unFocus();
3201                        return true;
3202                    }
3203                }
3204            }
3205        }
3206        return false;
3207    }
3208
3209    /**
3210     * Find an ancestor of focused that wants focus after its descendants and is
3211     * focusable in touch mode.
3212     * @param focused The currently focused view.
3213     * @return An appropriate view, or null if no such view exists.
3214     */
3215    private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3216        ViewParent parent = focused.getParent();
3217        while (parent instanceof ViewGroup) {
3218            final ViewGroup vgParent = (ViewGroup) parent;
3219            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3220                    && vgParent.isFocusableInTouchMode()) {
3221                return vgParent;
3222            }
3223            if (vgParent.isRootNamespace()) {
3224                return null;
3225            } else {
3226                parent = vgParent.getParent();
3227            }
3228        }
3229        return null;
3230    }
3231
3232    private boolean leaveTouchMode() {
3233        if (mView != null) {
3234            if (mView.hasFocus()) {
3235                View focusedView = mView.findFocus();
3236                if (!(focusedView instanceof ViewGroup)) {
3237                    // some view has focus, let it keep it
3238                    return false;
3239                } else if (((ViewGroup) focusedView).getDescendantFocusability() !=
3240                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3241                    // some view group has focus, and doesn't prefer its children
3242                    // over itself for focus, so let them keep it.
3243                    return false;
3244                }
3245            }
3246
3247            // find the best view to give focus to in this brave new non-touch-mode
3248            // world
3249            final View focused = focusSearch(null, View.FOCUS_DOWN);
3250            if (focused != null) {
3251                return focused.requestFocus(View.FOCUS_DOWN);
3252            }
3253        }
3254        return false;
3255    }
3256
3257    private int deliverInputEvent(QueuedInputEvent q) {
3258        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
3259        try {
3260            if (q.mEvent instanceof KeyEvent) {
3261                return deliverKeyEvent(q);
3262            } else {
3263                final int source = q.mEvent.getSource();
3264                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3265                    return deliverPointerEvent(q);
3266                } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3267                    return deliverTrackballEvent(q);
3268                } else {
3269                    return deliverGenericMotionEvent(q);
3270                }
3271            }
3272        } finally {
3273            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3274        }
3275    }
3276
3277    private int deliverInputEventPostIme(QueuedInputEvent q) {
3278        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEventPostIme");
3279        try {
3280            if (q.mEvent instanceof KeyEvent) {
3281                return deliverKeyEventPostIme(q);
3282            } else {
3283                final int source = q.mEvent.getSource();
3284                if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3285                    return deliverTrackballEventPostIme(q);
3286                } else {
3287                    return deliverGenericMotionEventPostIme(q);
3288                }
3289            }
3290        } finally {
3291            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3292        }
3293    }
3294
3295    private int deliverPointerEvent(QueuedInputEvent q) {
3296        final MotionEvent event = (MotionEvent)q.mEvent;
3297        final boolean isTouchEvent = event.isTouchEvent();
3298        if (mInputEventConsistencyVerifier != null) {
3299            if (isTouchEvent) {
3300                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
3301            } else {
3302                mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3303            }
3304        }
3305
3306        // If there is no view, then the event will not be handled.
3307        if (mView == null || !mAdded) {
3308            return EVENT_NOT_HANDLED;
3309        }
3310
3311        // Translate the pointer event for compatibility, if needed.
3312        if (mTranslator != null) {
3313            mTranslator.translateEventInScreenToAppWindow(event);
3314        }
3315
3316        // Enter touch mode on down or scroll.
3317        final int action = event.getAction();
3318        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3319            ensureTouchMode(true);
3320        }
3321
3322        // Offset the scroll position.
3323        if (mCurScrollY != 0) {
3324            event.offsetLocation(0, mCurScrollY);
3325        }
3326        if (MEASURE_LATENCY) {
3327            lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
3328        }
3329
3330        // Remember the touch position for possible drag-initiation.
3331        if (isTouchEvent) {
3332            mLastTouchPoint.x = event.getRawX();
3333            mLastTouchPoint.y = event.getRawY();
3334        }
3335
3336        // Dispatch touch to view hierarchy.
3337        boolean handled = mView.dispatchPointerEvent(event);
3338        if (MEASURE_LATENCY) {
3339            lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
3340        }
3341        return handled ? EVENT_HANDLED : EVENT_NOT_HANDLED;
3342    }
3343
3344    private int deliverTrackballEvent(QueuedInputEvent q) {
3345        final MotionEvent event = (MotionEvent)q.mEvent;
3346        if (mInputEventConsistencyVerifier != null) {
3347            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
3348        }
3349
3350        if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3351            if (LOCAL_LOGV)
3352                Log.v(TAG, "Dispatching trackball " + event + " to " + mView);
3353
3354            // Dispatch to the IME before propagating down the view hierarchy.
3355            // The IME will eventually call back into handleImeFinishedEvent.
3356            if (mLastWasImTarget) {
3357                InputMethodManager imm = InputMethodManager.peekInstance();
3358                if (imm != null) {
3359                    final int seq = event.getSequenceNumber();
3360                    if (DEBUG_IMF)
3361                        Log.v(TAG, "Sending trackball event to IME: seq="
3362                                + seq + " event=" + event);
3363                    int result = imm.dispatchTrackballEvent(mView.getContext(), seq, event,
3364                            mInputMethodCallback);
3365                    if (result != EVENT_NOT_HANDLED) {
3366                        return result;
3367                    }
3368                }
3369            }
3370        }
3371
3372        // Not dispatching to IME, continue with post IME actions.
3373        return deliverTrackballEventPostIme(q);
3374    }
3375
3376    private int deliverTrackballEventPostIme(QueuedInputEvent q) {
3377        final MotionEvent event = (MotionEvent) q.mEvent;
3378
3379        // If there is no view, then the event will not be handled.
3380        if (mView == null || !mAdded) {
3381            return EVENT_NOT_HANDLED;
3382        }
3383
3384        // Deliver the trackball event to the view.
3385        if (mView.dispatchTrackballEvent(event)) {
3386            // If we reach this, we delivered a trackball event to mView and
3387            // mView consumed it. Because we will not translate the trackball
3388            // event into a key event, touch mode will not exit, so we exit
3389            // touch mode here.
3390            ensureTouchMode(false);
3391            mLastTrackballTime = Integer.MIN_VALUE;
3392            return EVENT_HANDLED;
3393        }
3394
3395        // Translate the trackball event into DPAD keys and try to deliver those.
3396        final TrackballAxis x = mTrackballAxisX;
3397        final TrackballAxis y = mTrackballAxisY;
3398
3399        long curTime = SystemClock.uptimeMillis();
3400        if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
3401            // It has been too long since the last movement,
3402            // so restart at the beginning.
3403            x.reset(0);
3404            y.reset(0);
3405            mLastTrackballTime = curTime;
3406        }
3407
3408        final int action = event.getAction();
3409        final int metaState = event.getMetaState();
3410        switch (action) {
3411            case MotionEvent.ACTION_DOWN:
3412                x.reset(2);
3413                y.reset(2);
3414                enqueueInputEvent(new KeyEvent(curTime, curTime,
3415                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3416                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3417                        InputDevice.SOURCE_KEYBOARD));
3418                break;
3419            case MotionEvent.ACTION_UP:
3420                x.reset(2);
3421                y.reset(2);
3422                enqueueInputEvent(new KeyEvent(curTime, curTime,
3423                        KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3424                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3425                        InputDevice.SOURCE_KEYBOARD));
3426                break;
3427        }
3428
3429        if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
3430                + x.step + " dir=" + x.dir + " acc=" + x.acceleration
3431                + " move=" + event.getX()
3432                + " / Y=" + y.position + " step="
3433                + y.step + " dir=" + y.dir + " acc=" + y.acceleration
3434                + " move=" + event.getY());
3435        final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
3436        final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
3437
3438        // Generate DPAD events based on the trackball movement.
3439        // We pick the axis that has moved the most as the direction of
3440        // the DPAD.  When we generate DPAD events for one axis, then the
3441        // other axis is reset -- we don't want to perform DPAD jumps due
3442        // to slight movements in the trackball when making major movements
3443        // along the other axis.
3444        int keycode = 0;
3445        int movement = 0;
3446        float accel = 1;
3447        if (xOff > yOff) {
3448            movement = x.generate((2/event.getXPrecision()));
3449            if (movement != 0) {
3450                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
3451                        : KeyEvent.KEYCODE_DPAD_LEFT;
3452                accel = x.acceleration;
3453                y.reset(2);
3454            }
3455        } else if (yOff > 0) {
3456            movement = y.generate((2/event.getYPrecision()));
3457            if (movement != 0) {
3458                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
3459                        : KeyEvent.KEYCODE_DPAD_UP;
3460                accel = y.acceleration;
3461                x.reset(2);
3462            }
3463        }
3464
3465        if (keycode != 0) {
3466            if (movement < 0) movement = -movement;
3467            int accelMovement = (int)(movement * accel);
3468            if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
3469                    + " accelMovement=" + accelMovement
3470                    + " accel=" + accel);
3471            if (accelMovement > movement) {
3472                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3473                        + keycode);
3474                movement--;
3475                int repeatCount = accelMovement - movement;
3476                enqueueInputEvent(new KeyEvent(curTime, curTime,
3477                        KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
3478                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3479                        InputDevice.SOURCE_KEYBOARD));
3480            }
3481            while (movement > 0) {
3482                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3483                        + keycode);
3484                movement--;
3485                curTime = SystemClock.uptimeMillis();
3486                enqueueInputEvent(new KeyEvent(curTime, curTime,
3487                        KeyEvent.ACTION_DOWN, keycode, 0, metaState,
3488                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3489                        InputDevice.SOURCE_KEYBOARD));
3490                enqueueInputEvent(new KeyEvent(curTime, curTime,
3491                        KeyEvent.ACTION_UP, keycode, 0, metaState,
3492                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3493                        InputDevice.SOURCE_KEYBOARD));
3494            }
3495            mLastTrackballTime = curTime;
3496        }
3497
3498        // Unfortunately we can't tell whether the application consumed the keys, so
3499        // we always consider the trackball event handled.
3500        return EVENT_HANDLED;
3501    }
3502
3503    private int deliverGenericMotionEvent(QueuedInputEvent q) {
3504        final MotionEvent event = (MotionEvent)q.mEvent;
3505        if (mInputEventConsistencyVerifier != null) {
3506            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3507        }
3508        if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3509            if (LOCAL_LOGV)
3510                Log.v(TAG, "Dispatching generic motion " + event + " to " + mView);
3511
3512            // Dispatch to the IME before propagating down the view hierarchy.
3513            // The IME will eventually call back into handleImeFinishedEvent.
3514            if (mLastWasImTarget) {
3515                InputMethodManager imm = InputMethodManager.peekInstance();
3516                if (imm != null) {
3517                    final int seq = event.getSequenceNumber();
3518                    if (DEBUG_IMF)
3519                        Log.v(TAG, "Sending generic motion event to IME: seq="
3520                                + seq + " event=" + event);
3521                    int result = imm.dispatchGenericMotionEvent(mView.getContext(), seq, event,
3522                            mInputMethodCallback);
3523                    if (result != EVENT_NOT_HANDLED) {
3524                        return result;
3525                    }
3526                }
3527            }
3528        }
3529
3530        // Not dispatching to IME, continue with post IME actions.
3531        return deliverGenericMotionEventPostIme(q);
3532    }
3533
3534    private int deliverGenericMotionEventPostIme(QueuedInputEvent q) {
3535        final MotionEvent event = (MotionEvent) q.mEvent;
3536        final int source = event.getSource();
3537        final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
3538        final boolean isTouchPad = (source & InputDevice.SOURCE_CLASS_POSITION) != 0;
3539
3540        // If there is no view, then the event will not be handled.
3541        if (mView == null || !mAdded) {
3542            if (isJoystick) {
3543                updateJoystickDirection(event, false);
3544            } else if (isTouchPad) {
3545              mSimulatedDpad.updateTouchPad(this, event, false);
3546            }
3547            return EVENT_NOT_HANDLED;
3548        }
3549
3550        // Deliver the event to the view.
3551        if (mView.dispatchGenericMotionEvent(event)) {
3552            if (isJoystick) {
3553                updateJoystickDirection(event, false);
3554            } else if (isTouchPad) {
3555              mSimulatedDpad.updateTouchPad(this, event, false);
3556            }
3557            return EVENT_HANDLED;
3558        }
3559
3560        if (isJoystick) {
3561            // Translate the joystick event into DPAD keys and try to deliver
3562            // those.
3563            updateJoystickDirection(event, true);
3564            return EVENT_HANDLED;
3565        }
3566        if (isTouchPad) {
3567            mSimulatedDpad.updateTouchPad(this, event, true);
3568            return EVENT_HANDLED;
3569        }
3570        return EVENT_NOT_HANDLED;
3571    }
3572
3573    private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
3574        final long time = event.getEventTime();
3575        final int metaState = event.getMetaState();
3576        final int deviceId = event.getDeviceId();
3577        final int source = event.getSource();
3578
3579        int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
3580        if (xDirection == 0) {
3581            xDirection = joystickAxisValueToDirection(event.getX());
3582        }
3583
3584        int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
3585        if (yDirection == 0) {
3586            yDirection = joystickAxisValueToDirection(event.getY());
3587        }
3588
3589        if (xDirection != mLastJoystickXDirection) {
3590            if (mLastJoystickXKeyCode != 0) {
3591                enqueueInputEvent(new KeyEvent(time, time,
3592                        KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
3593                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3594                mLastJoystickXKeyCode = 0;
3595            }
3596
3597            mLastJoystickXDirection = xDirection;
3598
3599            if (xDirection != 0 && synthesizeNewKeys) {
3600                mLastJoystickXKeyCode = xDirection > 0
3601                        ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3602                enqueueInputEvent(new KeyEvent(time, time,
3603                        KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3604                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3605            }
3606        }
3607
3608        if (yDirection != mLastJoystickYDirection) {
3609            if (mLastJoystickYKeyCode != 0) {
3610                enqueueInputEvent(new KeyEvent(time, time,
3611                        KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3612                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3613                mLastJoystickYKeyCode = 0;
3614            }
3615
3616            mLastJoystickYDirection = yDirection;
3617
3618            if (yDirection != 0 && synthesizeNewKeys) {
3619                mLastJoystickYKeyCode = yDirection > 0
3620                        ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3621                enqueueInputEvent(new KeyEvent(time, time,
3622                        KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3623                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3624            }
3625        }
3626    }
3627
3628    private static int joystickAxisValueToDirection(float value) {
3629        if (value >= 0.5f) {
3630            return 1;
3631        } else if (value <= -0.5f) {
3632            return -1;
3633        } else {
3634            return 0;
3635        }
3636    }
3637
3638    /**
3639     * Returns true if the key is used for keyboard navigation.
3640     * @param keyEvent The key event.
3641     * @return True if the key is used for keyboard navigation.
3642     */
3643    private static boolean isNavigationKey(KeyEvent keyEvent) {
3644        switch (keyEvent.getKeyCode()) {
3645        case KeyEvent.KEYCODE_DPAD_LEFT:
3646        case KeyEvent.KEYCODE_DPAD_RIGHT:
3647        case KeyEvent.KEYCODE_DPAD_UP:
3648        case KeyEvent.KEYCODE_DPAD_DOWN:
3649        case KeyEvent.KEYCODE_DPAD_CENTER:
3650        case KeyEvent.KEYCODE_PAGE_UP:
3651        case KeyEvent.KEYCODE_PAGE_DOWN:
3652        case KeyEvent.KEYCODE_MOVE_HOME:
3653        case KeyEvent.KEYCODE_MOVE_END:
3654        case KeyEvent.KEYCODE_TAB:
3655        case KeyEvent.KEYCODE_SPACE:
3656        case KeyEvent.KEYCODE_ENTER:
3657            return true;
3658        }
3659        return false;
3660    }
3661
3662    /**
3663     * Returns true if the key is used for typing.
3664     * @param keyEvent The key event.
3665     * @return True if the key is used for typing.
3666     */
3667    private static boolean isTypingKey(KeyEvent keyEvent) {
3668        return keyEvent.getUnicodeChar() > 0;
3669    }
3670
3671    /**
3672     * See if the key event means we should leave touch mode (and leave touch mode if so).
3673     * @param event The key event.
3674     * @return Whether this key event should be consumed (meaning the act of
3675     *   leaving touch mode alone is considered the event).
3676     */
3677    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3678        // Only relevant in touch mode.
3679        if (!mAttachInfo.mInTouchMode) {
3680            return false;
3681        }
3682
3683        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3684        final int action = event.getAction();
3685        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3686            return false;
3687        }
3688
3689        // Don't leave touch mode if the IME told us not to.
3690        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3691            return false;
3692        }
3693
3694        // If the key can be used for keyboard navigation then leave touch mode
3695        // and select a focused view if needed (in ensureTouchMode).
3696        // When a new focused view is selected, we consume the navigation key because
3697        // navigation doesn't make much sense unless a view already has focus so
3698        // the key's purpose is to set focus.
3699        if (isNavigationKey(event)) {
3700            return ensureTouchMode(false);
3701        }
3702
3703        // If the key can be used for typing then leave touch mode
3704        // and select a focused view if needed (in ensureTouchMode).
3705        // Always allow the view to process the typing key.
3706        if (isTypingKey(event)) {
3707            ensureTouchMode(false);
3708            return false;
3709        }
3710
3711        return false;
3712    }
3713
3714    private int deliverKeyEvent(QueuedInputEvent q) {
3715        final KeyEvent event = (KeyEvent)q.mEvent;
3716        if (mInputEventConsistencyVerifier != null) {
3717            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3718        }
3719
3720        if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3721            if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3722
3723            // Perform predispatching before the IME.
3724            if (mView.dispatchKeyEventPreIme(event)) {
3725                return EVENT_HANDLED;
3726            }
3727
3728            // Dispatch to the IME before propagating down the view hierarchy.
3729            // The IME will eventually call back into handleImeFinishedEvent.
3730            if (mLastWasImTarget) {
3731                InputMethodManager imm = InputMethodManager.peekInstance();
3732                if (imm != null) {
3733                    final int seq = event.getSequenceNumber();
3734                    if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3735                            + seq + " event=" + event);
3736                    int result = imm.dispatchKeyEvent(mView.getContext(), seq, event,
3737                            mInputMethodCallback);
3738                    if (result != EVENT_NOT_HANDLED) {
3739                        return result;
3740                    }
3741                }
3742            }
3743        }
3744
3745        // Not dispatching to IME, continue with post IME actions.
3746        return deliverKeyEventPostIme(q);
3747    }
3748
3749    private int deliverKeyEventPostIme(QueuedInputEvent q) {
3750        final KeyEvent event = (KeyEvent)q.mEvent;
3751
3752        // If the view went away, then the event will not be handled.
3753        if (mView == null || !mAdded) {
3754            return EVENT_NOT_HANDLED;
3755        }
3756
3757        // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3758        if (checkForLeavingTouchModeAndConsume(event)) {
3759            return EVENT_HANDLED;
3760        }
3761
3762        // Make sure the fallback event policy sees all keys that will be delivered to the
3763        // view hierarchy.
3764        mFallbackEventHandler.preDispatchKeyEvent(event);
3765
3766        // Deliver the key to the view hierarchy.
3767        if (mView.dispatchKeyEvent(event)) {
3768            return EVENT_HANDLED;
3769        }
3770
3771        // If the Control modifier is held, try to interpret the key as a shortcut.
3772        if (event.getAction() == KeyEvent.ACTION_DOWN
3773                && event.isCtrlPressed()
3774                && event.getRepeatCount() == 0
3775                && !KeyEvent.isModifierKey(event.getKeyCode())) {
3776            if (mView.dispatchKeyShortcutEvent(event)) {
3777                return EVENT_HANDLED;
3778            }
3779        }
3780
3781        // Apply the fallback event policy.
3782        if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3783            return EVENT_HANDLED;
3784        }
3785
3786        // Handle automatic focus changes.
3787        if (event.getAction() == KeyEvent.ACTION_DOWN) {
3788            int direction = 0;
3789            switch (event.getKeyCode()) {
3790                case KeyEvent.KEYCODE_DPAD_LEFT:
3791                    if (event.hasNoModifiers()) {
3792                        direction = View.FOCUS_LEFT;
3793                    }
3794                    break;
3795                case KeyEvent.KEYCODE_DPAD_RIGHT:
3796                    if (event.hasNoModifiers()) {
3797                        direction = View.FOCUS_RIGHT;
3798                    }
3799                    break;
3800                case KeyEvent.KEYCODE_DPAD_UP:
3801                    if (event.hasNoModifiers()) {
3802                        direction = View.FOCUS_UP;
3803                    }
3804                    break;
3805                case KeyEvent.KEYCODE_DPAD_DOWN:
3806                    if (event.hasNoModifiers()) {
3807                        direction = View.FOCUS_DOWN;
3808                    }
3809                    break;
3810                case KeyEvent.KEYCODE_TAB:
3811                    if (event.hasNoModifiers()) {
3812                        direction = View.FOCUS_FORWARD;
3813                    } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3814                        direction = View.FOCUS_BACKWARD;
3815                    }
3816                    break;
3817            }
3818            if (direction != 0) {
3819                View focused = mView.findFocus();
3820                if (focused != null) {
3821                    View v = focused.focusSearch(direction);
3822                    if (v != null && v != focused) {
3823                        // do the math the get the interesting rect
3824                        // of previous focused into the coord system of
3825                        // newly focused view
3826                        focused.getFocusedRect(mTempRect);
3827                        if (mView instanceof ViewGroup) {
3828                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3829                                    focused, mTempRect);
3830                            ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3831                                    v, mTempRect);
3832                        }
3833                        if (v.requestFocus(direction, mTempRect)) {
3834                            playSoundEffect(SoundEffectConstants
3835                                    .getContantForFocusDirection(direction));
3836                            return EVENT_HANDLED;
3837                        }
3838                    }
3839
3840                    // Give the focused view a last chance to handle the dpad key.
3841                    if (mView.dispatchUnhandledMove(focused, direction)) {
3842                        return EVENT_HANDLED;
3843                    }
3844                }
3845            }
3846        }
3847
3848        // Key was unhandled.
3849        return EVENT_NOT_HANDLED;
3850    }
3851
3852    /* drag/drop */
3853    void setLocalDragState(Object obj) {
3854        mLocalDragState = obj;
3855    }
3856
3857    private void handleDragEvent(DragEvent event) {
3858        // From the root, only drag start/end/location are dispatched.  entered/exited
3859        // are determined and dispatched by the viewgroup hierarchy, who then report
3860        // that back here for ultimate reporting back to the framework.
3861        if (mView != null && mAdded) {
3862            final int what = event.mAction;
3863
3864            if (what == DragEvent.ACTION_DRAG_EXITED) {
3865                // A direct EXITED event means that the window manager knows we've just crossed
3866                // a window boundary, so the current drag target within this one must have
3867                // just been exited.  Send it the usual notifications and then we're done
3868                // for now.
3869                mView.dispatchDragEvent(event);
3870            } else {
3871                // Cache the drag description when the operation starts, then fill it in
3872                // on subsequent calls as a convenience
3873                if (what == DragEvent.ACTION_DRAG_STARTED) {
3874                    mCurrentDragView = null;    // Start the current-recipient tracking
3875                    mDragDescription = event.mClipDescription;
3876                } else {
3877                    event.mClipDescription = mDragDescription;
3878                }
3879
3880                // For events with a [screen] location, translate into window coordinates
3881                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3882                    mDragPoint.set(event.mX, event.mY);
3883                    if (mTranslator != null) {
3884                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3885                    }
3886
3887                    if (mCurScrollY != 0) {
3888                        mDragPoint.offset(0, mCurScrollY);
3889                    }
3890
3891                    event.mX = mDragPoint.x;
3892                    event.mY = mDragPoint.y;
3893                }
3894
3895                // Remember who the current drag target is pre-dispatch
3896                final View prevDragView = mCurrentDragView;
3897
3898                // Now dispatch the drag/drop event
3899                boolean result = mView.dispatchDragEvent(event);
3900
3901                // If we changed apparent drag target, tell the OS about it
3902                if (prevDragView != mCurrentDragView) {
3903                    try {
3904                        if (prevDragView != null) {
3905                            mWindowSession.dragRecipientExited(mWindow);
3906                        }
3907                        if (mCurrentDragView != null) {
3908                            mWindowSession.dragRecipientEntered(mWindow);
3909                        }
3910                    } catch (RemoteException e) {
3911                        Slog.e(TAG, "Unable to note drag target change");
3912                    }
3913                }
3914
3915                // Report the drop result when we're done
3916                if (what == DragEvent.ACTION_DROP) {
3917                    mDragDescription = null;
3918                    try {
3919                        Log.i(TAG, "Reporting drop result: " + result);
3920                        mWindowSession.reportDropResult(mWindow, result);
3921                    } catch (RemoteException e) {
3922                        Log.e(TAG, "Unable to report drop result");
3923                    }
3924                }
3925
3926                // When the drag operation ends, release any local state object
3927                // that may have been in use
3928                if (what == DragEvent.ACTION_DRAG_ENDED) {
3929                    setLocalDragState(null);
3930                }
3931            }
3932        }
3933        event.recycle();
3934    }
3935
3936    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
3937        if (mSeq != args.seq) {
3938            // The sequence has changed, so we need to update our value and make
3939            // sure to do a traversal afterward so the window manager is given our
3940            // most recent data.
3941            mSeq = args.seq;
3942            mAttachInfo.mForceReportNewAttributes = true;
3943            scheduleTraversals();
3944        }
3945        if (mView == null) return;
3946        if (args.localChanges != 0) {
3947            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
3948        }
3949        if (mAttachInfo != null) {
3950            int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
3951            if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
3952                mAttachInfo.mGlobalSystemUiVisibility = visibility;
3953                mView.dispatchSystemUiVisibilityChanged(visibility);
3954            }
3955        }
3956    }
3957
3958    public void handleDispatchDoneAnimating() {
3959        if (mWindowsAnimating) {
3960            mWindowsAnimating = false;
3961            if (!mDirty.isEmpty() || mIsAnimating)  {
3962                scheduleTraversals();
3963            }
3964        }
3965    }
3966
3967    public void getLastTouchPoint(Point outLocation) {
3968        outLocation.x = (int) mLastTouchPoint.x;
3969        outLocation.y = (int) mLastTouchPoint.y;
3970    }
3971
3972    public void setDragFocus(View newDragTarget) {
3973        if (mCurrentDragView != newDragTarget) {
3974            mCurrentDragView = newDragTarget;
3975        }
3976    }
3977
3978    private AudioManager getAudioManager() {
3979        if (mView == null) {
3980            throw new IllegalStateException("getAudioManager called when there is no mView");
3981        }
3982        if (mAudioManager == null) {
3983            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3984        }
3985        return mAudioManager;
3986    }
3987
3988    public AccessibilityInteractionController getAccessibilityInteractionController() {
3989        if (mView == null) {
3990            throw new IllegalStateException("getAccessibilityInteractionController"
3991                    + " called when there is no mView");
3992        }
3993        if (mAccessibilityInteractionController == null) {
3994            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
3995        }
3996        return mAccessibilityInteractionController;
3997    }
3998
3999    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
4000            boolean insetsPending) throws RemoteException {
4001
4002        float appScale = mAttachInfo.mApplicationScale;
4003        boolean restore = false;
4004        if (params != null && mTranslator != null) {
4005            restore = true;
4006            params.backup();
4007            mTranslator.translateWindowLayout(params);
4008        }
4009        if (params != null) {
4010            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
4011        }
4012        mPendingConfiguration.seq = 0;
4013        //Log.d(TAG, ">>>>>> CALLING relayout");
4014        if (params != null && mOrigWindowType != params.type) {
4015            // For compatibility with old apps, don't crash here.
4016            if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4017                Slog.w(TAG, "Window type can not be changed after "
4018                        + "the window is added; ignoring change of " + mView);
4019                params.type = mOrigWindowType;
4020            }
4021        }
4022        int relayoutResult = mWindowSession.relayout(
4023                mWindow, mSeq, params,
4024                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
4025                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
4026                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
4027                mWinFrame, mPendingContentInsets, mPendingVisibleInsets,
4028                mPendingConfiguration, mSurface);
4029        //Log.d(TAG, "<<<<<< BACK FROM relayout");
4030        if (restore) {
4031            params.restore();
4032        }
4033
4034        if (mTranslator != null) {
4035            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
4036            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
4037            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
4038        }
4039        return relayoutResult;
4040    }
4041
4042    /**
4043     * {@inheritDoc}
4044     */
4045    public void playSoundEffect(int effectId) {
4046        checkThread();
4047
4048        try {
4049            final AudioManager audioManager = getAudioManager();
4050
4051            switch (effectId) {
4052                case SoundEffectConstants.CLICK:
4053                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
4054                    return;
4055                case SoundEffectConstants.NAVIGATION_DOWN:
4056                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
4057                    return;
4058                case SoundEffectConstants.NAVIGATION_LEFT:
4059                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
4060                    return;
4061                case SoundEffectConstants.NAVIGATION_RIGHT:
4062                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
4063                    return;
4064                case SoundEffectConstants.NAVIGATION_UP:
4065                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
4066                    return;
4067                default:
4068                    throw new IllegalArgumentException("unknown effect id " + effectId +
4069                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
4070            }
4071        } catch (IllegalStateException e) {
4072            // Exception thrown by getAudioManager() when mView is null
4073            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
4074            e.printStackTrace();
4075        }
4076    }
4077
4078    /**
4079     * {@inheritDoc}
4080     */
4081    public boolean performHapticFeedback(int effectId, boolean always) {
4082        try {
4083            return mWindowSession.performHapticFeedback(mWindow, effectId, always);
4084        } catch (RemoteException e) {
4085            return false;
4086        }
4087    }
4088
4089    /**
4090     * {@inheritDoc}
4091     */
4092    public View focusSearch(View focused, int direction) {
4093        checkThread();
4094        if (!(mView instanceof ViewGroup)) {
4095            return null;
4096        }
4097        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
4098    }
4099
4100    public void debug() {
4101        mView.debug();
4102    }
4103
4104    public void dumpGfxInfo(int[] info) {
4105        info[0] = info[1] = 0;
4106        if (mView != null) {
4107            getGfxInfo(mView, info);
4108        }
4109    }
4110
4111    private static void getGfxInfo(View view, int[] info) {
4112        DisplayList displayList = view.mDisplayList;
4113        info[0]++;
4114        if (displayList != null) {
4115            info[1] += displayList.getSize();
4116        }
4117
4118        if (view instanceof ViewGroup) {
4119            ViewGroup group = (ViewGroup) view;
4120
4121            int count = group.getChildCount();
4122            for (int i = 0; i < count; i++) {
4123                getGfxInfo(group.getChildAt(i), info);
4124            }
4125        }
4126    }
4127
4128    public void die(boolean immediate) {
4129        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
4130        // done by dispatchDetachedFromWindow will cause havoc on return.
4131        if (immediate && !mIsInTraversal) {
4132            doDie();
4133        } else {
4134            if (!mIsDrawing) {
4135                destroyHardwareRenderer();
4136            } else {
4137                Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
4138                        "  window=" + this + ", title=" + mWindowAttributes.getTitle());
4139            }
4140            mHandler.sendEmptyMessage(MSG_DIE);
4141        }
4142    }
4143
4144    void doDie() {
4145        checkThread();
4146        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
4147        synchronized (this) {
4148            if (mAdded) {
4149                dispatchDetachedFromWindow();
4150            }
4151
4152            if (mAdded && !mFirst) {
4153                invalidateDisplayLists();
4154                destroyHardwareRenderer();
4155
4156                if (mView != null) {
4157                    int viewVisibility = mView.getVisibility();
4158                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
4159                    if (mWindowAttributesChanged || viewVisibilityChanged) {
4160                        // If layout params have been changed, first give them
4161                        // to the window manager to make sure it has the correct
4162                        // animation info.
4163                        try {
4164                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
4165                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
4166                                mWindowSession.finishDrawing(mWindow);
4167                            }
4168                        } catch (RemoteException e) {
4169                        }
4170                    }
4171
4172                    mSurface.release();
4173                }
4174            }
4175
4176            mAdded = false;
4177        }
4178    }
4179
4180    public void requestUpdateConfiguration(Configuration config) {
4181        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
4182        mHandler.sendMessage(msg);
4183    }
4184
4185    public void loadSystemProperties() {
4186        mHandler.post(new Runnable() {
4187            @Override
4188            public void run() {
4189                // Profiling
4190                mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
4191                profileRendering(mAttachInfo.mHasWindowFocus);
4192
4193                // Hardware rendering
4194                if (mAttachInfo.mHardwareRenderer != null) {
4195                    if (mAttachInfo.mHardwareRenderer.loadSystemProperties(mHolder.getSurface())) {
4196                        invalidate();
4197                    }
4198                }
4199
4200                // Layout debugging
4201                boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
4202                if (layout != mAttachInfo.mDebugLayout) {
4203                    mAttachInfo.mDebugLayout = layout;
4204                    if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
4205                        mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
4206                    }
4207                }
4208            }
4209        });
4210    }
4211
4212    private void destroyHardwareRenderer() {
4213        AttachInfo attachInfo = mAttachInfo;
4214        HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer;
4215
4216        if (hardwareRenderer != null) {
4217            if (mView != null) {
4218                hardwareRenderer.destroyHardwareResources(mView);
4219            }
4220            hardwareRenderer.destroy(true);
4221            hardwareRenderer.setRequested(false);
4222
4223            attachInfo.mHardwareRenderer = null;
4224            attachInfo.mHardwareAccelerated = false;
4225        }
4226    }
4227
4228    void dispatchImeFinishedEvent(int seq, boolean handled) {
4229        Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT);
4230        msg.arg1 = seq;
4231        msg.arg2 = handled ? 1 : 0;
4232        msg.setAsynchronous(true);
4233        mHandler.sendMessage(msg);
4234    }
4235
4236    public void dispatchFinishInputConnection(InputConnection connection) {
4237        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
4238        mHandler.sendMessage(msg);
4239    }
4240
4241    public void dispatchResized(Rect frame, Rect contentInsets,
4242            Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4243        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
4244                + " contentInsets=" + contentInsets.toShortString()
4245                + " visibleInsets=" + visibleInsets.toShortString()
4246                + " reportDraw=" + reportDraw);
4247        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
4248        if (mTranslator != null) {
4249            mTranslator.translateRectInScreenToAppWindow(frame);
4250            mTranslator.translateRectInScreenToAppWindow(contentInsets);
4251            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
4252        }
4253        SomeArgs args = SomeArgs.obtain();
4254        final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
4255        args.arg1 = sameProcessCall ? new Rect(frame) : frame;
4256        args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
4257        args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
4258        args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
4259        msg.obj = args;
4260        mHandler.sendMessage(msg);
4261    }
4262
4263    public void dispatchMoved(int newX, int newY) {
4264        if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
4265        if (mTranslator != null) {
4266            PointF point = new PointF(newX, newY);
4267            mTranslator.translatePointInScreenToAppWindow(point);
4268            newX = (int) (point.x + 0.5);
4269            newY = (int) (point.y + 0.5);
4270        }
4271        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
4272        mHandler.sendMessage(msg);
4273    }
4274
4275    /**
4276     * Represents a pending input event that is waiting in a queue.
4277     *
4278     * Input events are processed in serial order by the timestamp specified by
4279     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
4280     * one input event to the application at a time and waits for the application
4281     * to finish handling it before delivering the next one.
4282     *
4283     * However, because the application or IME can synthesize and inject multiple
4284     * key events at a time without going through the input dispatcher, we end up
4285     * needing a queue on the application's side.
4286     */
4287    private static final class QueuedInputEvent {
4288        public static final int FLAG_DELIVER_POST_IME = 1;
4289
4290        public QueuedInputEvent mNext;
4291
4292        public InputEvent mEvent;
4293        public InputEventReceiver mReceiver;
4294        public int mFlags;
4295    }
4296
4297    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
4298            InputEventReceiver receiver, int flags) {
4299        QueuedInputEvent q = mQueuedInputEventPool;
4300        if (q != null) {
4301            mQueuedInputEventPoolSize -= 1;
4302            mQueuedInputEventPool = q.mNext;
4303            q.mNext = null;
4304        } else {
4305            q = new QueuedInputEvent();
4306        }
4307
4308        q.mEvent = event;
4309        q.mReceiver = receiver;
4310        q.mFlags = flags;
4311        return q;
4312    }
4313
4314    private void recycleQueuedInputEvent(QueuedInputEvent q) {
4315        q.mEvent = null;
4316        q.mReceiver = null;
4317
4318        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
4319            mQueuedInputEventPoolSize += 1;
4320            q.mNext = mQueuedInputEventPool;
4321            mQueuedInputEventPool = q;
4322        }
4323    }
4324
4325    void enqueueInputEvent(InputEvent event) {
4326        enqueueInputEvent(event, null, 0, false);
4327    }
4328
4329    void enqueueInputEvent(InputEvent event,
4330            InputEventReceiver receiver, int flags, boolean processImmediately) {
4331        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
4332
4333        // Always enqueue the input event in order, regardless of its time stamp.
4334        // We do this because the application or the IME may inject key events
4335        // in response to touch events and we want to ensure that the injected keys
4336        // are processed in the order they were received and we cannot trust that
4337        // the time stamp of injected events are monotonic.
4338        QueuedInputEvent last = mFirstPendingInputEvent;
4339        if (last == null) {
4340            mFirstPendingInputEvent = q;
4341        } else {
4342            while (last.mNext != null) {
4343                last = last.mNext;
4344            }
4345            last.mNext = q;
4346        }
4347
4348        if (processImmediately) {
4349            doProcessInputEvents();
4350        } else {
4351            scheduleProcessInputEvents();
4352        }
4353    }
4354
4355    private void scheduleProcessInputEvents() {
4356        if (!mProcessInputEventsScheduled) {
4357            mProcessInputEventsScheduled = true;
4358            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
4359            msg.setAsynchronous(true);
4360            mHandler.sendMessage(msg);
4361        }
4362    }
4363
4364    void doProcessInputEvents() {
4365        while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) {
4366            QueuedInputEvent q = mFirstPendingInputEvent;
4367            mFirstPendingInputEvent = q.mNext;
4368            q.mNext = null;
4369            mCurrentInputEvent = q;
4370
4371            final int result = deliverInputEvent(q);
4372            if (result != EVENT_IN_PROGRESS) {
4373                finishCurrentInputEvent(result == EVENT_HANDLED);
4374            }
4375        }
4376
4377        // We are done processing all input events that we can process right now
4378        // so we can clear the pending flag immediately.
4379        if (mProcessInputEventsScheduled) {
4380            mProcessInputEventsScheduled = false;
4381            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
4382        }
4383    }
4384
4385    void handleImeFinishedEvent(int seq, boolean handled) {
4386        final QueuedInputEvent q = mCurrentInputEvent;
4387        if (q != null && q.mEvent.getSequenceNumber() == seq) {
4388            if (DEBUG_IMF) {
4389                Log.v(TAG, "IME finished event: seq=" + seq
4390                        + " handled=" + handled + " event=" + q);
4391            }
4392
4393            if (!handled) {
4394                // If the window doesn't currently have input focus, then drop
4395                // this event.  This could be an event that came back from the
4396                // IME dispatch but the window has lost focus in the meantime.
4397                if (!mAttachInfo.mHasWindowFocus && !isTerminalInputEvent(q.mEvent)) {
4398                    Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent);
4399                } else {
4400                    final int result = deliverInputEventPostIme(q);
4401                    if (result == EVENT_HANDLED) {
4402                        handled = true;
4403                    }
4404                }
4405            }
4406            finishCurrentInputEvent(handled);
4407
4408            // Immediately start processing the next input event.
4409            doProcessInputEvents();
4410        } else {
4411            if (DEBUG_IMF) {
4412                Log.v(TAG, "IME finished event: seq=" + seq
4413                        + " handled=" + handled + ", event not found!");
4414            }
4415        }
4416    }
4417
4418    private void finishCurrentInputEvent(boolean handled) {
4419        final QueuedInputEvent q = mCurrentInputEvent;
4420        mCurrentInputEvent = null;
4421
4422        if (q.mReceiver != null) {
4423            q.mReceiver.finishInputEvent(q.mEvent, handled);
4424        } else {
4425            q.mEvent.recycleIfNeededAfterDispatch();
4426        }
4427
4428        recycleQueuedInputEvent(q);
4429    }
4430
4431    private static boolean isTerminalInputEvent(InputEvent event) {
4432        if (event instanceof KeyEvent) {
4433            final KeyEvent keyEvent = (KeyEvent)event;
4434            return keyEvent.getAction() == KeyEvent.ACTION_UP;
4435        } else {
4436            final MotionEvent motionEvent = (MotionEvent)event;
4437            final int action = motionEvent.getAction();
4438            return action == MotionEvent.ACTION_UP
4439                    || action == MotionEvent.ACTION_CANCEL
4440                    || action == MotionEvent.ACTION_HOVER_EXIT;
4441        }
4442    }
4443
4444    void scheduleConsumeBatchedInput() {
4445        if (!mConsumeBatchedInputScheduled) {
4446            mConsumeBatchedInputScheduled = true;
4447            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
4448                    mConsumedBatchedInputRunnable, null);
4449        }
4450    }
4451
4452    void unscheduleConsumeBatchedInput() {
4453        if (mConsumeBatchedInputScheduled) {
4454            mConsumeBatchedInputScheduled = false;
4455            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
4456                    mConsumedBatchedInputRunnable, null);
4457        }
4458    }
4459
4460    void doConsumeBatchedInput(long frameTimeNanos) {
4461        if (mConsumeBatchedInputScheduled) {
4462            mConsumeBatchedInputScheduled = false;
4463            if (mInputEventReceiver != null) {
4464                mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos);
4465            }
4466            doProcessInputEvents();
4467        }
4468    }
4469
4470    final class TraversalRunnable implements Runnable {
4471        @Override
4472        public void run() {
4473            doTraversal();
4474        }
4475    }
4476    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
4477
4478    final class WindowInputEventReceiver extends InputEventReceiver {
4479        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
4480            super(inputChannel, looper);
4481        }
4482
4483        @Override
4484        public void onInputEvent(InputEvent event) {
4485            enqueueInputEvent(event, this, 0, true);
4486        }
4487
4488        @Override
4489        public void onBatchedInputEventPending() {
4490            scheduleConsumeBatchedInput();
4491        }
4492
4493        @Override
4494        public void dispose() {
4495            unscheduleConsumeBatchedInput();
4496            super.dispose();
4497        }
4498    }
4499    WindowInputEventReceiver mInputEventReceiver;
4500
4501    final class ConsumeBatchedInputRunnable implements Runnable {
4502        @Override
4503        public void run() {
4504            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
4505        }
4506    }
4507    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
4508            new ConsumeBatchedInputRunnable();
4509    boolean mConsumeBatchedInputScheduled;
4510
4511    final class InvalidateOnAnimationRunnable implements Runnable {
4512        private boolean mPosted;
4513        private ArrayList<View> mViews = new ArrayList<View>();
4514        private ArrayList<AttachInfo.InvalidateInfo> mViewRects =
4515                new ArrayList<AttachInfo.InvalidateInfo>();
4516        private View[] mTempViews;
4517        private AttachInfo.InvalidateInfo[] mTempViewRects;
4518
4519        public void addView(View view) {
4520            synchronized (this) {
4521                mViews.add(view);
4522                postIfNeededLocked();
4523            }
4524        }
4525
4526        public void addViewRect(AttachInfo.InvalidateInfo info) {
4527            synchronized (this) {
4528                mViewRects.add(info);
4529                postIfNeededLocked();
4530            }
4531        }
4532
4533        public void removeView(View view) {
4534            synchronized (this) {
4535                mViews.remove(view);
4536
4537                for (int i = mViewRects.size(); i-- > 0; ) {
4538                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
4539                    if (info.target == view) {
4540                        mViewRects.remove(i);
4541                        info.recycle();
4542                    }
4543                }
4544
4545                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
4546                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
4547                    mPosted = false;
4548                }
4549            }
4550        }
4551
4552        @Override
4553        public void run() {
4554            final int viewCount;
4555            final int viewRectCount;
4556            synchronized (this) {
4557                mPosted = false;
4558
4559                viewCount = mViews.size();
4560                if (viewCount != 0) {
4561                    mTempViews = mViews.toArray(mTempViews != null
4562                            ? mTempViews : new View[viewCount]);
4563                    mViews.clear();
4564                }
4565
4566                viewRectCount = mViewRects.size();
4567                if (viewRectCount != 0) {
4568                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
4569                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
4570                    mViewRects.clear();
4571                }
4572            }
4573
4574            for (int i = 0; i < viewCount; i++) {
4575                mTempViews[i].invalidate();
4576                mTempViews[i] = null;
4577            }
4578
4579            for (int i = 0; i < viewRectCount; i++) {
4580                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
4581                info.target.invalidate(info.left, info.top, info.right, info.bottom);
4582                info.recycle();
4583            }
4584        }
4585
4586        private void postIfNeededLocked() {
4587            if (!mPosted) {
4588                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
4589                mPosted = true;
4590            }
4591        }
4592    }
4593    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
4594            new InvalidateOnAnimationRunnable();
4595
4596    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
4597        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
4598        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4599    }
4600
4601    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
4602            long delayMilliseconds) {
4603        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
4604        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4605    }
4606
4607    public void dispatchInvalidateOnAnimation(View view) {
4608        mInvalidateOnAnimationRunnable.addView(view);
4609    }
4610
4611    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
4612        mInvalidateOnAnimationRunnable.addViewRect(info);
4613    }
4614
4615    public void enqueueDisplayList(DisplayList displayList) {
4616        mDisplayLists.add(displayList);
4617    }
4618
4619    public void cancelInvalidate(View view) {
4620        mHandler.removeMessages(MSG_INVALIDATE, view);
4621        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
4622        // them to the pool
4623        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
4624        mInvalidateOnAnimationRunnable.removeView(view);
4625    }
4626
4627    public void dispatchKey(KeyEvent event) {
4628        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event);
4629        msg.setAsynchronous(true);
4630        mHandler.sendMessage(msg);
4631    }
4632
4633    public void dispatchKeyFromIme(KeyEvent event) {
4634        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
4635        msg.setAsynchronous(true);
4636        mHandler.sendMessage(msg);
4637    }
4638
4639    public void dispatchUnhandledKey(KeyEvent event) {
4640        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4641            final KeyCharacterMap kcm = event.getKeyCharacterMap();
4642            final int keyCode = event.getKeyCode();
4643            final int metaState = event.getMetaState();
4644
4645            // Check for fallback actions specified by the key character map.
4646            KeyCharacterMap.FallbackAction fallbackAction =
4647                    kcm.getFallbackAction(keyCode, metaState);
4648            if (fallbackAction != null) {
4649                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
4650                KeyEvent fallbackEvent = KeyEvent.obtain(
4651                        event.getDownTime(), event.getEventTime(),
4652                        event.getAction(), fallbackAction.keyCode,
4653                        event.getRepeatCount(), fallbackAction.metaState,
4654                        event.getDeviceId(), event.getScanCode(),
4655                        flags, event.getSource(), null);
4656                fallbackAction.recycle();
4657
4658                dispatchKey(fallbackEvent);
4659            }
4660        }
4661    }
4662
4663    public void dispatchAppVisibility(boolean visible) {
4664        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
4665        msg.arg1 = visible ? 1 : 0;
4666        mHandler.sendMessage(msg);
4667    }
4668
4669    public void dispatchScreenStateChange(boolean on) {
4670        Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE);
4671        msg.arg1 = on ? 1 : 0;
4672        mHandler.sendMessage(msg);
4673    }
4674
4675    public void dispatchGetNewSurface() {
4676        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
4677        mHandler.sendMessage(msg);
4678    }
4679
4680    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4681        Message msg = Message.obtain();
4682        msg.what = MSG_WINDOW_FOCUS_CHANGED;
4683        msg.arg1 = hasFocus ? 1 : 0;
4684        msg.arg2 = inTouchMode ? 1 : 0;
4685        mHandler.sendMessage(msg);
4686    }
4687
4688    public void dispatchCloseSystemDialogs(String reason) {
4689        Message msg = Message.obtain();
4690        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
4691        msg.obj = reason;
4692        mHandler.sendMessage(msg);
4693    }
4694
4695    public void dispatchDragEvent(DragEvent event) {
4696        final int what;
4697        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
4698            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
4699            mHandler.removeMessages(what);
4700        } else {
4701            what = MSG_DISPATCH_DRAG_EVENT;
4702        }
4703        Message msg = mHandler.obtainMessage(what, event);
4704        mHandler.sendMessage(msg);
4705    }
4706
4707    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4708            int localValue, int localChanges) {
4709        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
4710        args.seq = seq;
4711        args.globalVisibility = globalVisibility;
4712        args.localValue = localValue;
4713        args.localChanges = localChanges;
4714        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
4715    }
4716
4717    public void dispatchDoneAnimating() {
4718        mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
4719    }
4720
4721    public void dispatchCheckFocus() {
4722        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
4723            // This will result in a call to checkFocus() below.
4724            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
4725        }
4726    }
4727
4728    /**
4729     * Post a callback to send a
4730     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4731     * This event is send at most once every
4732     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
4733     */
4734    private void postSendWindowContentChangedCallback(View source) {
4735        if (mSendWindowContentChangedAccessibilityEvent == null) {
4736            mSendWindowContentChangedAccessibilityEvent =
4737                new SendWindowContentChangedAccessibilityEvent();
4738        }
4739        View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource;
4740        if (oldSource == null) {
4741            mSendWindowContentChangedAccessibilityEvent.mSource = source;
4742            mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent,
4743                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
4744        } else {
4745            mSendWindowContentChangedAccessibilityEvent.mSource =
4746                    getCommonPredecessor(oldSource, source);
4747        }
4748    }
4749
4750    /**
4751     * Remove a posted callback to send a
4752     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4753     */
4754    private void removeSendWindowContentChangedCallback() {
4755        if (mSendWindowContentChangedAccessibilityEvent != null) {
4756            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
4757        }
4758    }
4759
4760    public boolean showContextMenuForChild(View originalView) {
4761        return false;
4762    }
4763
4764    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
4765        return null;
4766    }
4767
4768    public void createContextMenu(ContextMenu menu) {
4769    }
4770
4771    public void childDrawableStateChanged(View child) {
4772    }
4773
4774    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
4775        if (mView == null) {
4776            return false;
4777        }
4778        // Intercept accessibility focus events fired by virtual nodes to keep
4779        // track of accessibility focus position in such nodes.
4780        final int eventType = event.getEventType();
4781        switch (eventType) {
4782            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4783                final long sourceNodeId = event.getSourceNodeId();
4784                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4785                        sourceNodeId);
4786                View source = mView.findViewByAccessibilityId(accessibilityViewId);
4787                if (source != null) {
4788                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4789                    if (provider != null) {
4790                        AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(
4791                                AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId));
4792                        setAccessibilityFocus(source, node);
4793                    }
4794                }
4795            } break;
4796            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4797                final long sourceNodeId = event.getSourceNodeId();
4798                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4799                        sourceNodeId);
4800                View source = mView.findViewByAccessibilityId(accessibilityViewId);
4801                if (source != null) {
4802                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4803                    if (provider != null) {
4804                        setAccessibilityFocus(null, null);
4805                    }
4806                }
4807            } break;
4808        }
4809        mAccessibilityManager.sendAccessibilityEvent(event);
4810        return true;
4811    }
4812
4813    @Override
4814    public void childAccessibilityStateChanged(View child) {
4815        postSendWindowContentChangedCallback(child);
4816    }
4817
4818    private View getCommonPredecessor(View first, View second) {
4819        if (mAttachInfo != null) {
4820            if (mTempHashSet == null) {
4821                mTempHashSet = new HashSet<View>();
4822            }
4823            HashSet<View> seen = mTempHashSet;
4824            seen.clear();
4825            View firstCurrent = first;
4826            while (firstCurrent != null) {
4827                seen.add(firstCurrent);
4828                ViewParent firstCurrentParent = firstCurrent.mParent;
4829                if (firstCurrentParent instanceof View) {
4830                    firstCurrent = (View) firstCurrentParent;
4831                } else {
4832                    firstCurrent = null;
4833                }
4834            }
4835            View secondCurrent = second;
4836            while (secondCurrent != null) {
4837                if (seen.contains(secondCurrent)) {
4838                    seen.clear();
4839                    return secondCurrent;
4840                }
4841                ViewParent secondCurrentParent = secondCurrent.mParent;
4842                if (secondCurrentParent instanceof View) {
4843                    secondCurrent = (View) secondCurrentParent;
4844                } else {
4845                    secondCurrent = null;
4846                }
4847            }
4848            seen.clear();
4849        }
4850        return null;
4851    }
4852
4853    void checkThread() {
4854        if (mThread != Thread.currentThread()) {
4855            throw new CalledFromWrongThreadException(
4856                    "Only the original thread that created a view hierarchy can touch its views.");
4857        }
4858    }
4859
4860    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
4861        // ViewAncestor never intercepts touch event, so this can be a no-op
4862    }
4863
4864    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
4865        final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
4866        if (rectangle != null) {
4867            mTempRect.set(rectangle);
4868            mTempRect.offset(0, -mCurScrollY);
4869            mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4870            try {
4871                mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate);
4872            } catch (RemoteException re) {
4873                /* ignore */
4874            }
4875        }
4876        return scrolled;
4877    }
4878
4879    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
4880        // Do nothing.
4881    }
4882
4883    class TakenSurfaceHolder extends BaseSurfaceHolder {
4884        @Override
4885        public boolean onAllowLockCanvas() {
4886            return mDrawingAllowed;
4887        }
4888
4889        @Override
4890        public void onRelayoutContainer() {
4891            // Not currently interesting -- from changing between fixed and layout size.
4892        }
4893
4894        public void setFormat(int format) {
4895            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
4896        }
4897
4898        public void setType(int type) {
4899            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
4900        }
4901
4902        @Override
4903        public void onUpdateSurface() {
4904            // We take care of format and type changes on our own.
4905            throw new IllegalStateException("Shouldn't be here");
4906        }
4907
4908        public boolean isCreating() {
4909            return mIsCreating;
4910        }
4911
4912        @Override
4913        public void setFixedSize(int width, int height) {
4914            throw new UnsupportedOperationException(
4915                    "Currently only support sizing from layout");
4916        }
4917
4918        public void setKeepScreenOn(boolean screenOn) {
4919            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
4920        }
4921    }
4922
4923    static final class InputMethodCallback implements InputMethodManager.FinishedEventCallback {
4924        private WeakReference<ViewRootImpl> mViewAncestor;
4925
4926        public InputMethodCallback(ViewRootImpl viewAncestor) {
4927            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4928        }
4929
4930        @Override
4931        public void finishedEvent(int seq, boolean handled) {
4932            final ViewRootImpl viewAncestor = mViewAncestor.get();
4933            if (viewAncestor != null) {
4934                viewAncestor.dispatchImeFinishedEvent(seq, handled);
4935            }
4936        }
4937    }
4938
4939    static class W extends IWindow.Stub {
4940        private final WeakReference<ViewRootImpl> mViewAncestor;
4941        private final IWindowSession mWindowSession;
4942
4943        W(ViewRootImpl viewAncestor) {
4944            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4945            mWindowSession = viewAncestor.mWindowSession;
4946        }
4947
4948        public void resized(Rect frame, Rect contentInsets,
4949                Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4950            final ViewRootImpl viewAncestor = mViewAncestor.get();
4951            if (viewAncestor != null) {
4952                viewAncestor.dispatchResized(frame, contentInsets,
4953                        visibleInsets, reportDraw, newConfig);
4954            }
4955        }
4956
4957        @Override
4958        public void moved(int newX, int newY) {
4959            final ViewRootImpl viewAncestor = mViewAncestor.get();
4960            if (viewAncestor != null) {
4961                viewAncestor.dispatchMoved(newX, newY);
4962            }
4963        }
4964
4965        public void dispatchAppVisibility(boolean visible) {
4966            final ViewRootImpl viewAncestor = mViewAncestor.get();
4967            if (viewAncestor != null) {
4968                viewAncestor.dispatchAppVisibility(visible);
4969            }
4970        }
4971
4972        public void dispatchScreenState(boolean on) {
4973            final ViewRootImpl viewAncestor = mViewAncestor.get();
4974            if (viewAncestor != null) {
4975                viewAncestor.dispatchScreenStateChange(on);
4976            }
4977        }
4978
4979        public void dispatchGetNewSurface() {
4980            final ViewRootImpl viewAncestor = mViewAncestor.get();
4981            if (viewAncestor != null) {
4982                viewAncestor.dispatchGetNewSurface();
4983            }
4984        }
4985
4986        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4987            final ViewRootImpl viewAncestor = mViewAncestor.get();
4988            if (viewAncestor != null) {
4989                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
4990            }
4991        }
4992
4993        private static int checkCallingPermission(String permission) {
4994            try {
4995                return ActivityManagerNative.getDefault().checkPermission(
4996                        permission, Binder.getCallingPid(), Binder.getCallingUid());
4997            } catch (RemoteException e) {
4998                return PackageManager.PERMISSION_DENIED;
4999            }
5000        }
5001
5002        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
5003            final ViewRootImpl viewAncestor = mViewAncestor.get();
5004            if (viewAncestor != null) {
5005                final View view = viewAncestor.mView;
5006                if (view != null) {
5007                    if (checkCallingPermission(Manifest.permission.DUMP) !=
5008                            PackageManager.PERMISSION_GRANTED) {
5009                        throw new SecurityException("Insufficient permissions to invoke"
5010                                + " executeCommand() from pid=" + Binder.getCallingPid()
5011                                + ", uid=" + Binder.getCallingUid());
5012                    }
5013
5014                    OutputStream clientStream = null;
5015                    try {
5016                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
5017                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
5018                    } catch (IOException e) {
5019                        e.printStackTrace();
5020                    } finally {
5021                        if (clientStream != null) {
5022                            try {
5023                                clientStream.close();
5024                            } catch (IOException e) {
5025                                e.printStackTrace();
5026                            }
5027                        }
5028                    }
5029                }
5030            }
5031        }
5032
5033        public void closeSystemDialogs(String reason) {
5034            final ViewRootImpl viewAncestor = mViewAncestor.get();
5035            if (viewAncestor != null) {
5036                viewAncestor.dispatchCloseSystemDialogs(reason);
5037            }
5038        }
5039
5040        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
5041                boolean sync) {
5042            if (sync) {
5043                try {
5044                    mWindowSession.wallpaperOffsetsComplete(asBinder());
5045                } catch (RemoteException e) {
5046                }
5047            }
5048        }
5049
5050        public void dispatchWallpaperCommand(String action, int x, int y,
5051                int z, Bundle extras, boolean sync) {
5052            if (sync) {
5053                try {
5054                    mWindowSession.wallpaperCommandComplete(asBinder(), null);
5055                } catch (RemoteException e) {
5056                }
5057            }
5058        }
5059
5060        /* Drag/drop */
5061        public void dispatchDragEvent(DragEvent event) {
5062            final ViewRootImpl viewAncestor = mViewAncestor.get();
5063            if (viewAncestor != null) {
5064                viewAncestor.dispatchDragEvent(event);
5065            }
5066        }
5067
5068        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
5069                int localValue, int localChanges) {
5070            final ViewRootImpl viewAncestor = mViewAncestor.get();
5071            if (viewAncestor != null) {
5072                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
5073                        localValue, localChanges);
5074            }
5075        }
5076
5077        public void doneAnimating() {
5078            final ViewRootImpl viewAncestor = mViewAncestor.get();
5079            if (viewAncestor != null) {
5080                viewAncestor.dispatchDoneAnimating();
5081            }
5082        }
5083    }
5084
5085    /**
5086     * Maintains state information for a single trackball axis, generating
5087     * discrete (DPAD) movements based on raw trackball motion.
5088     */
5089    static final class TrackballAxis {
5090        /**
5091         * The maximum amount of acceleration we will apply.
5092         */
5093        static final float MAX_ACCELERATION = 20;
5094
5095        /**
5096         * The maximum amount of time (in milliseconds) between events in order
5097         * for us to consider the user to be doing fast trackball movements,
5098         * and thus apply an acceleration.
5099         */
5100        static final long FAST_MOVE_TIME = 150;
5101
5102        /**
5103         * Scaling factor to the time (in milliseconds) between events to how
5104         * much to multiple/divide the current acceleration.  When movement
5105         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
5106         * FAST_MOVE_TIME it divides it.
5107         */
5108        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
5109
5110        float position;
5111        float absPosition;
5112        float acceleration = 1;
5113        long lastMoveTime = 0;
5114        int step;
5115        int dir;
5116        int nonAccelMovement;
5117
5118        void reset(int _step) {
5119            position = 0;
5120            acceleration = 1;
5121            lastMoveTime = 0;
5122            step = _step;
5123            dir = 0;
5124        }
5125
5126        /**
5127         * Add trackball movement into the state.  If the direction of movement
5128         * has been reversed, the state is reset before adding the
5129         * movement (so that you don't have to compensate for any previously
5130         * collected movement before see the result of the movement in the
5131         * new direction).
5132         *
5133         * @return Returns the absolute value of the amount of movement
5134         * collected so far.
5135         */
5136        float collect(float off, long time, String axis) {
5137            long normTime;
5138            if (off > 0) {
5139                normTime = (long)(off * FAST_MOVE_TIME);
5140                if (dir < 0) {
5141                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
5142                    position = 0;
5143                    step = 0;
5144                    acceleration = 1;
5145                    lastMoveTime = 0;
5146                }
5147                dir = 1;
5148            } else if (off < 0) {
5149                normTime = (long)((-off) * FAST_MOVE_TIME);
5150                if (dir > 0) {
5151                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
5152                    position = 0;
5153                    step = 0;
5154                    acceleration = 1;
5155                    lastMoveTime = 0;
5156                }
5157                dir = -1;
5158            } else {
5159                normTime = 0;
5160            }
5161
5162            // The number of milliseconds between each movement that is
5163            // considered "normal" and will not result in any acceleration
5164            // or deceleration, scaled by the offset we have here.
5165            if (normTime > 0) {
5166                long delta = time - lastMoveTime;
5167                lastMoveTime = time;
5168                float acc = acceleration;
5169                if (delta < normTime) {
5170                    // The user is scrolling rapidly, so increase acceleration.
5171                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
5172                    if (scale > 1) acc *= scale;
5173                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
5174                            + off + " normTime=" + normTime + " delta=" + delta
5175                            + " scale=" + scale + " acc=" + acc);
5176                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
5177                } else {
5178                    // The user is scrolling slowly, so decrease acceleration.
5179                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
5180                    if (scale > 1) acc /= scale;
5181                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
5182                            + off + " normTime=" + normTime + " delta=" + delta
5183                            + " scale=" + scale + " acc=" + acc);
5184                    acceleration = acc > 1 ? acc : 1;
5185                }
5186            }
5187            position += off;
5188            return (absPosition = Math.abs(position));
5189        }
5190
5191        /**
5192         * Generate the number of discrete movement events appropriate for
5193         * the currently collected trackball movement.
5194         *
5195         * @param precision The minimum movement required to generate the
5196         * first discrete movement.
5197         *
5198         * @return Returns the number of discrete movements, either positive
5199         * or negative, or 0 if there is not enough trackball movement yet
5200         * for a discrete movement.
5201         */
5202        int generate(float precision) {
5203            int movement = 0;
5204            nonAccelMovement = 0;
5205            do {
5206                final int dir = position >= 0 ? 1 : -1;
5207                switch (step) {
5208                    // If we are going to execute the first step, then we want
5209                    // to do this as soon as possible instead of waiting for
5210                    // a full movement, in order to make things look responsive.
5211                    case 0:
5212                        if (absPosition < precision) {
5213                            return movement;
5214                        }
5215                        movement += dir;
5216                        nonAccelMovement += dir;
5217                        step = 1;
5218                        break;
5219                    // If we have generated the first movement, then we need
5220                    // to wait for the second complete trackball motion before
5221                    // generating the second discrete movement.
5222                    case 1:
5223                        if (absPosition < 2) {
5224                            return movement;
5225                        }
5226                        movement += dir;
5227                        nonAccelMovement += dir;
5228                        position += dir > 0 ? -2 : 2;
5229                        absPosition = Math.abs(position);
5230                        step = 2;
5231                        break;
5232                    // After the first two, we generate discrete movements
5233                    // consistently with the trackball, applying an acceleration
5234                    // if the trackball is moving quickly.  This is a simple
5235                    // acceleration on top of what we already compute based
5236                    // on how quickly the wheel is being turned, to apply
5237                    // a longer increasing acceleration to continuous movement
5238                    // in one direction.
5239                    default:
5240                        if (absPosition < 1) {
5241                            return movement;
5242                        }
5243                        movement += dir;
5244                        position += dir >= 0 ? -1 : 1;
5245                        absPosition = Math.abs(position);
5246                        float acc = acceleration;
5247                        acc *= 1.1f;
5248                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
5249                        break;
5250                }
5251            } while (true);
5252        }
5253    }
5254
5255    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
5256        public CalledFromWrongThreadException(String msg) {
5257            super(msg);
5258        }
5259    }
5260
5261    private SurfaceHolder mHolder = new SurfaceHolder() {
5262        // we only need a SurfaceHolder for opengl. it would be nice
5263        // to implement everything else though, especially the callback
5264        // support (opengl doesn't make use of it right now, but eventually
5265        // will).
5266        public Surface getSurface() {
5267            return mSurface;
5268        }
5269
5270        public boolean isCreating() {
5271            return false;
5272        }
5273
5274        public void addCallback(Callback callback) {
5275        }
5276
5277        public void removeCallback(Callback callback) {
5278        }
5279
5280        public void setFixedSize(int width, int height) {
5281        }
5282
5283        public void setSizeFromLayout() {
5284        }
5285
5286        public void setFormat(int format) {
5287        }
5288
5289        public void setType(int type) {
5290        }
5291
5292        public void setKeepScreenOn(boolean screenOn) {
5293        }
5294
5295        public Canvas lockCanvas() {
5296            return null;
5297        }
5298
5299        public Canvas lockCanvas(Rect dirty) {
5300            return null;
5301        }
5302
5303        public void unlockCanvasAndPost(Canvas canvas) {
5304        }
5305        public Rect getSurfaceFrame() {
5306            return null;
5307        }
5308    };
5309
5310    static RunQueue getRunQueue() {
5311        RunQueue rq = sRunQueues.get();
5312        if (rq != null) {
5313            return rq;
5314        }
5315        rq = new RunQueue();
5316        sRunQueues.set(rq);
5317        return rq;
5318    }
5319
5320    /**
5321     * The run queue is used to enqueue pending work from Views when no Handler is
5322     * attached.  The work is executed during the next call to performTraversals on
5323     * the thread.
5324     * @hide
5325     */
5326    static final class RunQueue {
5327        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
5328
5329        void post(Runnable action) {
5330            postDelayed(action, 0);
5331        }
5332
5333        void postDelayed(Runnable action, long delayMillis) {
5334            HandlerAction handlerAction = new HandlerAction();
5335            handlerAction.action = action;
5336            handlerAction.delay = delayMillis;
5337
5338            synchronized (mActions) {
5339                mActions.add(handlerAction);
5340            }
5341        }
5342
5343        void removeCallbacks(Runnable action) {
5344            final HandlerAction handlerAction = new HandlerAction();
5345            handlerAction.action = action;
5346
5347            synchronized (mActions) {
5348                final ArrayList<HandlerAction> actions = mActions;
5349
5350                while (actions.remove(handlerAction)) {
5351                    // Keep going
5352                }
5353            }
5354        }
5355
5356        void executeActions(Handler handler) {
5357            synchronized (mActions) {
5358                final ArrayList<HandlerAction> actions = mActions;
5359                final int count = actions.size();
5360
5361                for (int i = 0; i < count; i++) {
5362                    final HandlerAction handlerAction = actions.get(i);
5363                    handler.postDelayed(handlerAction.action, handlerAction.delay);
5364                }
5365
5366                actions.clear();
5367            }
5368        }
5369
5370        private static class HandlerAction {
5371            Runnable action;
5372            long delay;
5373
5374            @Override
5375            public boolean equals(Object o) {
5376                if (this == o) return true;
5377                if (o == null || getClass() != o.getClass()) return false;
5378
5379                HandlerAction that = (HandlerAction) o;
5380                return !(action != null ? !action.equals(that.action) : that.action != null);
5381
5382            }
5383
5384            @Override
5385            public int hashCode() {
5386                int result = action != null ? action.hashCode() : 0;
5387                result = 31 * result + (int) (delay ^ (delay >>> 32));
5388                return result;
5389            }
5390        }
5391    }
5392
5393    /**
5394     * Class for managing the accessibility interaction connection
5395     * based on the global accessibility state.
5396     */
5397    final class AccessibilityInteractionConnectionManager
5398            implements AccessibilityStateChangeListener {
5399        public void onAccessibilityStateChanged(boolean enabled) {
5400            if (enabled) {
5401                ensureConnection();
5402                if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
5403                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
5404                    View focusedView = mView.findFocus();
5405                    if (focusedView != null && focusedView != mView) {
5406                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5407                    }
5408                }
5409            } else {
5410                ensureNoConnection();
5411                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
5412            }
5413        }
5414
5415        public void ensureConnection() {
5416            if (mAttachInfo != null) {
5417                final boolean registered =
5418                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5419                if (!registered) {
5420                    mAttachInfo.mAccessibilityWindowId =
5421                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
5422                                new AccessibilityInteractionConnection(ViewRootImpl.this));
5423                }
5424            }
5425        }
5426
5427        public void ensureNoConnection() {
5428            final boolean registered =
5429                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5430            if (registered) {
5431                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED;
5432                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
5433            }
5434        }
5435    }
5436
5437    /**
5438     * This class is an interface this ViewAncestor provides to the
5439     * AccessibilityManagerService to the latter can interact with
5440     * the view hierarchy in this ViewAncestor.
5441     */
5442    static final class AccessibilityInteractionConnection
5443            extends IAccessibilityInteractionConnection.Stub {
5444        private final WeakReference<ViewRootImpl> mViewRootImpl;
5445
5446        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
5447            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
5448        }
5449
5450        @Override
5451        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
5452                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5453                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5454            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5455            if (viewRootImpl != null && viewRootImpl.mView != null) {
5456                viewRootImpl.getAccessibilityInteractionController()
5457                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
5458                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
5459                            spec);
5460            } else {
5461                // We cannot make the call and notify the caller so it does not wait.
5462                try {
5463                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5464                } catch (RemoteException re) {
5465                    /* best effort - ignore */
5466                }
5467            }
5468        }
5469
5470        @Override
5471        public void performAccessibilityAction(long accessibilityNodeId, int action,
5472                Bundle arguments, int interactionId,
5473                IAccessibilityInteractionConnectionCallback callback, int flags,
5474                int interogatingPid, long interrogatingTid) {
5475            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5476            if (viewRootImpl != null && viewRootImpl.mView != null) {
5477                viewRootImpl.getAccessibilityInteractionController()
5478                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
5479                            interactionId, callback, flags, interogatingPid, interrogatingTid);
5480            } else {
5481                // We cannot make the call and notify the caller so it does not wait.
5482                try {
5483                    callback.setPerformAccessibilityActionResult(false, interactionId);
5484                } catch (RemoteException re) {
5485                    /* best effort - ignore */
5486                }
5487            }
5488        }
5489
5490        @Override
5491        public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
5492                String viewId, int interactionId,
5493                IAccessibilityInteractionConnectionCallback callback, int flags,
5494                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5495            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5496            if (viewRootImpl != null && viewRootImpl.mView != null) {
5497                viewRootImpl.getAccessibilityInteractionController()
5498                    .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
5499                            viewId, interactionId, callback, flags, interrogatingPid,
5500                            interrogatingTid, spec);
5501            } else {
5502                // We cannot make the call and notify the caller so it does not wait.
5503                try {
5504                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5505                } catch (RemoteException re) {
5506                    /* best effort - ignore */
5507                }
5508            }
5509        }
5510
5511        @Override
5512        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
5513                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5514                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5515            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5516            if (viewRootImpl != null && viewRootImpl.mView != null) {
5517                viewRootImpl.getAccessibilityInteractionController()
5518                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
5519                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
5520                            spec);
5521            } else {
5522                // We cannot make the call and notify the caller so it does not wait.
5523                try {
5524                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5525                } catch (RemoteException re) {
5526                    /* best effort - ignore */
5527                }
5528            }
5529        }
5530
5531        @Override
5532        public void findFocus(long accessibilityNodeId, int focusType, int interactionId,
5533                IAccessibilityInteractionConnectionCallback callback, int flags,
5534                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5535            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5536            if (viewRootImpl != null && viewRootImpl.mView != null) {
5537                viewRootImpl.getAccessibilityInteractionController()
5538                    .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback,
5539                            flags, interrogatingPid, interrogatingTid, spec);
5540            } else {
5541                // We cannot make the call and notify the caller so it does not wait.
5542                try {
5543                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5544                } catch (RemoteException re) {
5545                    /* best effort - ignore */
5546                }
5547            }
5548        }
5549
5550        @Override
5551        public void focusSearch(long accessibilityNodeId, int direction, int interactionId,
5552                IAccessibilityInteractionConnectionCallback callback, int flags,
5553                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5554            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5555            if (viewRootImpl != null && viewRootImpl.mView != null) {
5556                viewRootImpl.getAccessibilityInteractionController()
5557                    .focusSearchClientThread(accessibilityNodeId, direction, interactionId,
5558                            callback, flags, interrogatingPid, interrogatingTid, spec);
5559            } else {
5560                // We cannot make the call and notify the caller so it does not wait.
5561                try {
5562                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5563                } catch (RemoteException re) {
5564                    /* best effort - ignore */
5565                }
5566            }
5567        }
5568    }
5569
5570    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
5571        public View mSource;
5572
5573        public void run() {
5574            if (mSource != null) {
5575                mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
5576                mSource.resetAccessibilityStateChanged();
5577                mSource = null;
5578            }
5579        }
5580    }
5581}
5582