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