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