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