ViewRootImpl.java revision fa6b35be126ffcc3b5818393c26aff724ac65daf
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.PackageManager;
27import android.content.res.CompatibilityInfo;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.graphics.Canvas;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PointF;
35import android.graphics.PorterDuff;
36import android.graphics.Rect;
37import android.graphics.Region;
38import android.media.AudioManager;
39import android.os.Binder;
40import android.os.Bundle;
41import android.os.Debug;
42import android.os.Handler;
43import android.os.LatencyTimer;
44import android.os.Looper;
45import android.os.Message;
46import android.os.ParcelFileDescriptor;
47import android.os.Process;
48import android.os.RemoteException;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.util.AndroidRuntimeException;
52import android.util.DisplayMetrics;
53import android.util.EventLog;
54import android.util.Log;
55import android.util.Pool;
56import android.util.Poolable;
57import android.util.PoolableManager;
58import android.util.Pools;
59import android.util.Slog;
60import android.util.SparseArray;
61import android.util.TypedValue;
62import android.view.View.MeasureSpec;
63import android.view.accessibility.AccessibilityEvent;
64import android.view.accessibility.AccessibilityManager;
65import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
66import android.view.accessibility.AccessibilityNodeInfo;
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.policy.PolicyManager;
76import com.android.internal.util.Predicate;
77import com.android.internal.view.BaseSurfaceHolder;
78import com.android.internal.view.IInputMethodCallback;
79import com.android.internal.view.IInputMethodSession;
80import com.android.internal.view.RootViewSurfaceTaker;
81
82import java.io.IOException;
83import java.io.OutputStream;
84import java.io.PrintWriter;
85import java.lang.ref.WeakReference;
86import java.util.ArrayList;
87import java.util.List;
88
89/**
90 * The top of a view hierarchy, implementing the needed protocol between View
91 * and the WindowManager.  This is for the most part an internal implementation
92 * detail of {@link WindowManagerImpl}.
93 *
94 * {@hide}
95 */
96@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
97public final class ViewRootImpl extends Handler implements ViewParent,
98        View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
99    private static final String TAG = "ViewRootImpl";
100    private static final boolean DBG = false;
101    private static final boolean LOCAL_LOGV = false;
102    /** @noinspection PointlessBooleanExpression*/
103    private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
104    private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
105    private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
106    private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
107    private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
108    private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
109    private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
110    private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
111    private static final boolean WATCH_POINTER = 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 IWindowSession sWindowSession;
129
130    static final Object mStaticInit = new Object();
131    static boolean mInitialized = false;
132
133    static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
134
135    static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
136    static boolean sFirstDrawComplete = false;
137
138    static final ArrayList<ComponentCallbacks> sConfigCallbacks
139            = new ArrayList<ComponentCallbacks>();
140
141    long mLastTrackballTime = 0;
142    final TrackballAxis mTrackballAxisX = new TrackballAxis();
143    final TrackballAxis mTrackballAxisY = new TrackballAxis();
144
145    int mLastJoystickXDirection;
146    int mLastJoystickYDirection;
147    int mLastJoystickXKeyCode;
148    int mLastJoystickYKeyCode;
149
150    final int[] mTmpLocation = new int[2];
151
152    final TypedValue mTmpValue = new TypedValue();
153
154    final InputMethodCallback mInputMethodCallback;
155    final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
156    int mPendingEventSeq = 0;
157
158    final Thread mThread;
159
160    final WindowLeaked mLocation;
161
162    final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
163
164    final W mWindow;
165
166    View mView;
167    View mFocusedView;
168    View mRealFocusedView;  // this is not set to null in touch mode
169    int mViewVisibility;
170    boolean mAppVisible = true;
171
172    // Set to true if the owner of this window is in the stopped state,
173    // so the window should no longer be active.
174    boolean mStopped = false;
175
176    boolean mLastInCompatMode = false;
177
178    SurfaceHolder.Callback2 mSurfaceHolderCallback;
179    BaseSurfaceHolder mSurfaceHolder;
180    boolean mIsCreating;
181    boolean mDrawingAllowed;
182
183    final Region mTransparentRegion;
184    final Region mPreviousTransparentRegion;
185
186    int mWidth;
187    int mHeight;
188    Rect mDirty;
189    final Rect mCurrentDirty = new Rect();
190    final Rect mPreviousDirty = new Rect();
191    boolean mIsAnimating;
192
193    CompatibilityInfo.Translator mTranslator;
194
195    final View.AttachInfo mAttachInfo;
196    InputChannel mInputChannel;
197    InputQueue.Callback mInputQueueCallback;
198    InputQueue mInputQueue;
199    FallbackEventHandler mFallbackEventHandler;
200
201    final Rect mTempRect; // used in the transaction to not thrash the heap.
202    final Rect mVisRect; // used to retrieve visible rect of focused view.
203
204    boolean mTraversalScheduled;
205    long mLastTraversalFinishedTimeNanos;
206    long mLastDrawDurationNanos;
207    boolean mWillDrawSoon;
208    boolean mLayoutRequested;
209    boolean mFirst;
210    boolean mReportNextDraw;
211    boolean mFullRedrawNeeded;
212    boolean mNewSurfaceNeeded;
213    boolean mHasHadWindowFocus;
214    boolean mLastWasImTarget;
215
216    boolean mWindowAttributesChanged = false;
217
218    // These can be accessed by any thread, must be protected with a lock.
219    // Surface can never be reassigned or cleared (use Surface.clear()).
220    private final Surface mSurface = new Surface();
221
222    boolean mAdded;
223    boolean mAddedTouchMode;
224
225    CompatibilityInfoHolder mCompatibilityInfo;
226
227    /*package*/ int mAddNesting;
228
229    // These are accessed by multiple threads.
230    final Rect mWinFrame; // frame given by window manager.
231
232    final Rect mPendingVisibleInsets = new Rect();
233    final Rect mPendingContentInsets = new Rect();
234    final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
235            = new ViewTreeObserver.InternalInsetsInfo();
236
237    final Configuration mLastConfiguration = new Configuration();
238    final Configuration mPendingConfiguration = new Configuration();
239
240    class ResizedInfo {
241        Rect coveredInsets;
242        Rect visibleInsets;
243        Configuration newConfig;
244    }
245
246    boolean mScrollMayChange;
247    int mSoftInputMode;
248    View mLastScrolledFocus;
249    int mScrollY;
250    int mCurScrollY;
251    Scroller mScroller;
252    HardwareLayer mResizeBuffer;
253    long mResizeBufferStartTime;
254    int mResizeBufferDuration;
255    static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
256    private ArrayList<LayoutTransition> mPendingTransitions;
257
258    final ViewConfiguration mViewConfiguration;
259
260    /* Drag/drop */
261    ClipDescription mDragDescription;
262    View mCurrentDragView;
263    volatile Object mLocalDragState;
264    final PointF mDragPoint = new PointF();
265    final PointF mLastTouchPoint = new PointF();
266
267    private boolean mProfileRendering;
268    private Thread mRenderProfiler;
269    private volatile boolean mRenderProfilingEnabled;
270
271    /**
272     * see {@link #playSoundEffect(int)}
273     */
274    AudioManager mAudioManager;
275
276    final AccessibilityManager mAccessibilityManager;
277
278    AccessibilityInteractionController mAccessibilityInteractionContrtoller;
279
280    AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
281
282    SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
283
284    private final int mDensity;
285
286    /**
287     * Consistency verifier for debugging purposes.
288     */
289    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
290            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
291                    new InputEventConsistencyVerifier(this, 0) : null;
292
293    public static IWindowSession getWindowSession(Looper mainLooper) {
294        synchronized (mStaticInit) {
295            if (!mInitialized) {
296                try {
297                    InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
298                    sWindowSession = Display.getWindowManager().openSession(
299                            imm.getClient(), imm.getInputContext());
300                    mInitialized = true;
301                } catch (RemoteException e) {
302                }
303            }
304            return sWindowSession;
305        }
306    }
307
308    public ViewRootImpl(Context context) {
309        super();
310
311        if (MEASURE_LATENCY) {
312            if (lt == null) {
313                lt = new LatencyTimer(100, 1000);
314            }
315        }
316
317        // Initialize the statics when this class is first instantiated. This is
318        // done here instead of in the static block because Zygote does not
319        // allow the spawning of threads.
320        getWindowSession(context.getMainLooper());
321
322        mThread = Thread.currentThread();
323        mLocation = new WindowLeaked(null);
324        mLocation.fillInStackTrace();
325        mWidth = -1;
326        mHeight = -1;
327        mDirty = new Rect();
328        mTempRect = new Rect();
329        mVisRect = new Rect();
330        mWinFrame = new Rect();
331        mWindow = new W(this);
332        mInputMethodCallback = new InputMethodCallback(this);
333        mViewVisibility = View.GONE;
334        mTransparentRegion = new Region();
335        mPreviousTransparentRegion = new Region();
336        mFirst = true; // true for the first time the view is added
337        mAdded = false;
338        mAccessibilityManager = AccessibilityManager.getInstance(context);
339        mAccessibilityInteractionConnectionManager =
340            new AccessibilityInteractionConnectionManager();
341        mAccessibilityManager.addAccessibilityStateChangeListener(
342                mAccessibilityInteractionConnectionManager);
343        mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
344        mViewConfiguration = ViewConfiguration.get(context);
345        mDensity = context.getResources().getDisplayMetrics().densityDpi;
346        mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
347        mProfileRendering = Boolean.parseBoolean(
348                SystemProperties.get(PROPERTY_PROFILE_RENDERING, "false"));
349    }
350
351    public static void addFirstDrawHandler(Runnable callback) {
352        synchronized (sFirstDrawHandlers) {
353            if (!sFirstDrawComplete) {
354                sFirstDrawHandlers.add(callback);
355            }
356        }
357    }
358
359    public static void addConfigCallback(ComponentCallbacks callback) {
360        synchronized (sConfigCallbacks) {
361            sConfigCallbacks.add(callback);
362        }
363    }
364
365    // FIXME for perf testing only
366    private boolean mProfile = false;
367
368    /**
369     * Call this to profile the next traversal call.
370     * FIXME for perf testing only. Remove eventually
371     */
372    public void profile() {
373        mProfile = true;
374    }
375
376    /**
377     * Indicates whether we are in touch mode. Calling this method triggers an IPC
378     * call and should be avoided whenever possible.
379     *
380     * @return True, if the device is in touch mode, false otherwise.
381     *
382     * @hide
383     */
384    static boolean isInTouchMode() {
385        if (mInitialized) {
386            try {
387                return sWindowSession.getInTouchMode();
388            } catch (RemoteException e) {
389            }
390        }
391        return false;
392    }
393
394    /**
395     * We have one child
396     */
397    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
398        synchronized (this) {
399            if (mView == null) {
400                mView = view;
401                mFallbackEventHandler.setView(view);
402                mWindowAttributes.copyFrom(attrs);
403                attrs = mWindowAttributes;
404
405                if (view instanceof RootViewSurfaceTaker) {
406                    mSurfaceHolderCallback =
407                            ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
408                    if (mSurfaceHolderCallback != null) {
409                        mSurfaceHolder = new TakenSurfaceHolder();
410                        mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
411                    }
412                }
413
414                // If the application owns the surface, don't enable hardware acceleration
415                if (mSurfaceHolder == null) {
416                    enableHardwareAcceleration(attrs);
417                }
418
419                CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
420                mTranslator = compatibilityInfo.getTranslator();
421
422                if (mTranslator != null) {
423                    mSurface.setCompatibilityTranslator(mTranslator);
424                }
425
426                boolean restore = false;
427                if (mTranslator != null) {
428                    restore = true;
429                    attrs.backup();
430                    mTranslator.translateWindowLayout(attrs);
431                }
432                if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
433
434                if (!compatibilityInfo.supportsScreen()) {
435                    attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
436                    mLastInCompatMode = true;
437                }
438
439                mSoftInputMode = attrs.softInputMode;
440                mWindowAttributesChanged = true;
441                mAttachInfo.mRootView = view;
442                mAttachInfo.mScalingRequired = mTranslator != null;
443                mAttachInfo.mApplicationScale =
444                        mTranslator == null ? 1.0f : mTranslator.applicationScale;
445                if (panelParentView != null) {
446                    mAttachInfo.mPanelParentWindowToken
447                            = panelParentView.getApplicationWindowToken();
448                }
449                mAdded = true;
450                int res; /* = WindowManagerImpl.ADD_OKAY; */
451
452                // Schedule the first layout -before- adding to the window
453                // manager, to make sure we do the relayout before receiving
454                // any other events from the system.
455                requestLayout();
456                mInputChannel = new InputChannel();
457                try {
458                    res = sWindowSession.add(mWindow, mWindowAttributes,
459                            getHostVisibility(), mAttachInfo.mContentInsets,
460                            mInputChannel);
461                } catch (RemoteException e) {
462                    mAdded = false;
463                    mView = null;
464                    mAttachInfo.mRootView = null;
465                    mInputChannel = null;
466                    mFallbackEventHandler.setView(null);
467                    unscheduleTraversals();
468                    throw new RuntimeException("Adding window failed", e);
469                } finally {
470                    if (restore) {
471                        attrs.restore();
472                    }
473                }
474
475                if (mTranslator != null) {
476                    mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
477                }
478                mPendingContentInsets.set(mAttachInfo.mContentInsets);
479                mPendingVisibleInsets.set(0, 0, 0, 0);
480                if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
481                if (res < WindowManagerImpl.ADD_OKAY) {
482                    mView = null;
483                    mAttachInfo.mRootView = null;
484                    mAdded = false;
485                    mFallbackEventHandler.setView(null);
486                    unscheduleTraversals();
487                    switch (res) {
488                        case WindowManagerImpl.ADD_BAD_APP_TOKEN:
489                        case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
490                            throw new WindowManagerImpl.BadTokenException(
491                                "Unable to add window -- token " + attrs.token
492                                + " is not valid; is your activity running?");
493                        case WindowManagerImpl.ADD_NOT_APP_TOKEN:
494                            throw new WindowManagerImpl.BadTokenException(
495                                "Unable to add window -- token " + attrs.token
496                                + " is not for an application");
497                        case WindowManagerImpl.ADD_APP_EXITING:
498                            throw new WindowManagerImpl.BadTokenException(
499                                "Unable to add window -- app for token " + attrs.token
500                                + " is exiting");
501                        case WindowManagerImpl.ADD_DUPLICATE_ADD:
502                            throw new WindowManagerImpl.BadTokenException(
503                                "Unable to add window -- window " + mWindow
504                                + " has already been added");
505                        case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
506                            // Silently ignore -- we would have just removed it
507                            // right away, anyway.
508                            return;
509                        case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
510                            throw new WindowManagerImpl.BadTokenException(
511                                "Unable to add window " + mWindow +
512                                " -- another window of this type already exists");
513                        case WindowManagerImpl.ADD_PERMISSION_DENIED:
514                            throw new WindowManagerImpl.BadTokenException(
515                                "Unable to add window " + mWindow +
516                                " -- permission denied for this window type");
517                    }
518                    throw new RuntimeException(
519                        "Unable to add window -- unknown error code " + res);
520                }
521
522                if (view instanceof RootViewSurfaceTaker) {
523                    mInputQueueCallback =
524                        ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
525                }
526                if (mInputQueueCallback != null) {
527                    mInputQueue = new InputQueue(mInputChannel);
528                    mInputQueueCallback.onInputQueueCreated(mInputQueue);
529                } else {
530                    InputQueue.registerInputChannel(mInputChannel, mInputHandler,
531                            Looper.myQueue());
532                }
533
534                view.assignParent(this);
535                mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
536                mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
537
538                if (mAccessibilityManager.isEnabled()) {
539                    mAccessibilityInteractionConnectionManager.ensureConnection();
540                }
541            }
542        }
543    }
544
545    private void destroyHardwareResources() {
546        if (mAttachInfo.mHardwareRenderer != null) {
547            if (mAttachInfo.mHardwareRenderer.isEnabled()) {
548                mAttachInfo.mHardwareRenderer.destroyLayers(mView);
549            }
550            mAttachInfo.mHardwareRenderer.destroy(false);
551        }
552    }
553
554    void destroyHardwareLayers() {
555        if (mThread != Thread.currentThread()) {
556            if (mAttachInfo.mHardwareRenderer != null &&
557                    mAttachInfo.mHardwareRenderer.isEnabled()) {
558                HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE);
559            }
560        } else {
561            if (mAttachInfo.mHardwareRenderer != null &&
562                    mAttachInfo.mHardwareRenderer.isEnabled()) {
563                mAttachInfo.mHardwareRenderer.destroyLayers(mView);
564            }
565        }
566    }
567
568    private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
569        mAttachInfo.mHardwareAccelerated = false;
570        mAttachInfo.mHardwareAccelerationRequested = false;
571
572        // Try to enable hardware acceleration if requested
573        final boolean hardwareAccelerated =
574                (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
575
576        if (hardwareAccelerated) {
577            if (!HardwareRenderer.isAvailable()) {
578                mAttachInfo.mHardwareAccelerationRequested = true;
579                return;
580            }
581
582            // Only enable hardware acceleration if we are not in the system process
583            // The window manager creates ViewAncestors to display animated preview windows
584            // of launching apps and we don't want those to be hardware accelerated
585
586            final boolean systemHwAccelerated =
587                (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED_SYSTEM) != 0;
588
589            if (!HardwareRenderer.sRendererDisabled || systemHwAccelerated) {
590                // Don't enable hardware acceleration when we're not on the main thread
591                if (!systemHwAccelerated && Looper.getMainLooper() != Looper.myLooper()) {
592                    Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
593                            + "acceleration outside of the main thread, aborting");
594                    return;
595                }
596
597                final boolean translucent = attrs.format != PixelFormat.OPAQUE;
598                if (mAttachInfo.mHardwareRenderer != null) {
599                    mAttachInfo.mHardwareRenderer.destroy(true);
600                }
601                mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
602                mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
603                        = mAttachInfo.mHardwareRenderer != null;
604            }
605        }
606    }
607
608    public View getView() {
609        return mView;
610    }
611
612    final WindowLeaked getLocation() {
613        return mLocation;
614    }
615
616    void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
617        synchronized (this) {
618            int oldSoftInputMode = mWindowAttributes.softInputMode;
619            // preserve compatible window flag if exists.
620            int compatibleWindowFlag =
621                mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
622            mWindowAttributes.copyFrom(attrs);
623            mWindowAttributes.flags |= compatibleWindowFlag;
624
625            if (newView) {
626                mSoftInputMode = attrs.softInputMode;
627                requestLayout();
628            }
629            // Don't lose the mode we last auto-computed.
630            if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
631                    == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
632                mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
633                        & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
634                        | (oldSoftInputMode
635                                & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
636            }
637            mWindowAttributesChanged = true;
638            scheduleTraversals();
639        }
640    }
641
642    void handleAppVisibility(boolean visible) {
643        if (mAppVisible != visible) {
644            mAppVisible = visible;
645            scheduleTraversals();
646        }
647    }
648
649    void handleGetNewSurface() {
650        mNewSurfaceNeeded = true;
651        mFullRedrawNeeded = true;
652        scheduleTraversals();
653    }
654
655    /**
656     * {@inheritDoc}
657     */
658    public void requestLayout() {
659        checkThread();
660        mLayoutRequested = true;
661        scheduleTraversals();
662    }
663
664    /**
665     * {@inheritDoc}
666     */
667    public boolean isLayoutRequested() {
668        return mLayoutRequested;
669    }
670
671    public void invalidateChild(View child, Rect dirty) {
672        checkThread();
673        if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
674        if (dirty == null) {
675            // Fast invalidation for GL-enabled applications; GL must redraw everything
676            invalidate();
677            return;
678        }
679        if (mCurScrollY != 0 || mTranslator != null) {
680            mTempRect.set(dirty);
681            dirty = mTempRect;
682            if (mCurScrollY != 0) {
683               dirty.offset(0, -mCurScrollY);
684            }
685            if (mTranslator != null) {
686                mTranslator.translateRectInAppWindowToScreen(dirty);
687            }
688            if (mAttachInfo.mScalingRequired) {
689                dirty.inset(-1, -1);
690            }
691        }
692        if (!mDirty.isEmpty() && !mDirty.contains(dirty)) {
693            mAttachInfo.mSetIgnoreDirtyState = true;
694            mAttachInfo.mIgnoreDirtyState = true;
695        }
696        mDirty.union(dirty);
697        if (!mWillDrawSoon) {
698            scheduleTraversals();
699        }
700    }
701
702    void invalidate() {
703        mDirty.set(0, 0, mWidth, mHeight);
704        scheduleTraversals();
705    }
706
707    void setStopped(boolean stopped) {
708        if (mStopped != stopped) {
709            mStopped = stopped;
710            if (!stopped) {
711                scheduleTraversals();
712            }
713        }
714    }
715
716    public ViewParent getParent() {
717        return null;
718    }
719
720    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
721        invalidateChild(null, dirty);
722        return null;
723    }
724
725    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
726        if (child != mView) {
727            throw new RuntimeException("child is not mine, honest!");
728        }
729        // Note: don't apply scroll offset, because we want to know its
730        // visibility in the virtual canvas being given to the view hierarchy.
731        return r.intersect(0, 0, mWidth, mHeight);
732    }
733
734    public void bringChildToFront(View child) {
735    }
736
737    public void scheduleTraversals() {
738        if (!mTraversalScheduled) {
739            mTraversalScheduled = true;
740
741            //noinspection ConstantConditions
742            if (ViewDebug.DEBUG_LATENCY && mLastTraversalFinishedTimeNanos != 0) {
743                final long now = System.nanoTime();
744                Log.d(TAG, "Latency: Scheduled traversal, it has been "
745                        + ((now - mLastTraversalFinishedTimeNanos) * 0.000001f)
746                        + "ms since the last traversal finished.");
747            }
748
749            sendEmptyMessage(DO_TRAVERSAL);
750        }
751    }
752
753    public void unscheduleTraversals() {
754        if (mTraversalScheduled) {
755            mTraversalScheduled = false;
756            removeMessages(DO_TRAVERSAL);
757        }
758    }
759
760    int getHostVisibility() {
761        return mAppVisible ? mView.getVisibility() : View.GONE;
762    }
763
764    void disposeResizeBuffer() {
765        if (mResizeBuffer != null) {
766            mResizeBuffer.destroy();
767            mResizeBuffer = null;
768        }
769    }
770
771    /**
772     * Add LayoutTransition to the list of transitions to be started in the next traversal.
773     * This list will be cleared after the transitions on the list are start()'ed. These
774     * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
775     * happens during the layout phase of traversal, which we want to complete before any of the
776     * animations are started (because those animations may side-effect properties that layout
777     * depends upon, like the bounding rectangles of the affected views). So we add the transition
778     * to the list and it is started just prior to starting the drawing phase of traversal.
779     *
780     * @param transition The LayoutTransition to be started on the next traversal.
781     *
782     * @hide
783     */
784    public void requestTransitionStart(LayoutTransition transition) {
785        if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
786            if (mPendingTransitions == null) {
787                 mPendingTransitions = new ArrayList<LayoutTransition>();
788            }
789            mPendingTransitions.add(transition);
790        }
791    }
792
793    private void performTraversals() {
794        // cache mView since it is used so much below...
795        final View host = mView;
796
797        if (DBG) {
798            System.out.println("======================================");
799            System.out.println("performTraversals");
800            host.debug();
801        }
802
803        if (host == null || !mAdded)
804            return;
805
806        mTraversalScheduled = false;
807        mWillDrawSoon = true;
808        boolean windowSizeMayChange = false;
809        boolean fullRedrawNeeded = mFullRedrawNeeded;
810        boolean newSurface = false;
811        boolean surfaceChanged = false;
812        WindowManager.LayoutParams lp = mWindowAttributes;
813
814        int desiredWindowWidth;
815        int desiredWindowHeight;
816        int childWidthMeasureSpec;
817        int childHeightMeasureSpec;
818
819        final View.AttachInfo attachInfo = mAttachInfo;
820
821        final int viewVisibility = getHostVisibility();
822        boolean viewVisibilityChanged = mViewVisibility != viewVisibility
823                || mNewSurfaceNeeded;
824
825        WindowManager.LayoutParams params = null;
826        if (mWindowAttributesChanged) {
827            mWindowAttributesChanged = false;
828            surfaceChanged = true;
829            params = lp;
830        }
831        CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
832        if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
833            params = lp;
834            fullRedrawNeeded = true;
835            mLayoutRequested = true;
836            if (mLastInCompatMode) {
837                params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
838                mLastInCompatMode = false;
839            } else {
840                params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
841                mLastInCompatMode = true;
842            }
843        }
844        Rect frame = mWinFrame;
845        if (mFirst) {
846            fullRedrawNeeded = true;
847            mLayoutRequested = true;
848
849            if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
850                // NOTE -- system code, won't try to do compat mode.
851                Display disp = WindowManagerImpl.getDefault().getDefaultDisplay();
852                Point size = new Point();
853                disp.getRealSize(size);
854                desiredWindowWidth = size.x;
855                desiredWindowHeight = size.y;
856            } else {
857                DisplayMetrics packageMetrics =
858                    mView.getContext().getResources().getDisplayMetrics();
859                desiredWindowWidth = packageMetrics.widthPixels;
860                desiredWindowHeight = packageMetrics.heightPixels;
861            }
862
863            // For the very first time, tell the view hierarchy that it
864            // is attached to the window.  Note that at this point the surface
865            // object is not initialized to its backing store, but soon it
866            // will be (assuming the window is visible).
867            attachInfo.mSurface = mSurface;
868            // We used to use the following condition to choose 32 bits drawing caches:
869            // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
870            // However, windows are now always 32 bits by default, so choose 32 bits
871            attachInfo.mUse32BitDrawingCache = true;
872            attachInfo.mHasWindowFocus = false;
873            attachInfo.mWindowVisibility = viewVisibility;
874            attachInfo.mRecomputeGlobalAttributes = false;
875            attachInfo.mKeepScreenOn = false;
876            attachInfo.mSystemUiVisibility = 0;
877            viewVisibilityChanged = false;
878            mLastConfiguration.setTo(host.getResources().getConfiguration());
879            host.dispatchAttachedToWindow(attachInfo, 0);
880            //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
881
882            host.fitSystemWindows(mAttachInfo.mContentInsets);
883
884        } else {
885            desiredWindowWidth = frame.width();
886            desiredWindowHeight = frame.height();
887            if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
888                if (DEBUG_ORIENTATION) Log.v(TAG,
889                        "View " + host + " resized to: " + frame);
890                fullRedrawNeeded = true;
891                mLayoutRequested = true;
892                windowSizeMayChange = true;
893            }
894        }
895
896        if (viewVisibilityChanged) {
897            attachInfo.mWindowVisibility = viewVisibility;
898            host.dispatchWindowVisibilityChanged(viewVisibility);
899            if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
900                destroyHardwareResources();
901            }
902            if (viewVisibility == View.GONE) {
903                // After making a window gone, we will count it as being
904                // shown for the first time the next time it gets focus.
905                mHasHadWindowFocus = false;
906            }
907        }
908
909        boolean insetsChanged = false;
910
911        if (mLayoutRequested && !mStopped) {
912            // Execute enqueued actions on every layout in case a view that was detached
913            // enqueued an action after being detached
914            getRunQueue().executeActions(attachInfo.mHandler);
915
916            final Resources res = mView.getContext().getResources();
917
918            if (mFirst) {
919                // make sure touch mode code executes by setting cached value
920                // to opposite of the added touch mode.
921                mAttachInfo.mInTouchMode = !mAddedTouchMode;
922                ensureTouchModeLocally(mAddedTouchMode);
923            } else {
924                if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
925                    insetsChanged = true;
926                }
927                if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
928                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
929                    if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
930                            + mAttachInfo.mVisibleInsets);
931                }
932                if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
933                        || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
934                    windowSizeMayChange = true;
935
936                    if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
937                        // NOTE -- system code, won't try to do compat mode.
938                        Display disp = WindowManagerImpl.getDefault().getDefaultDisplay();
939                        Point size = new Point();
940                        disp.getRealSize(size);
941                        desiredWindowWidth = size.x;
942                        desiredWindowHeight = size.y;
943                    } else {
944                        DisplayMetrics packageMetrics = res.getDisplayMetrics();
945                        desiredWindowWidth = packageMetrics.widthPixels;
946                        desiredWindowHeight = packageMetrics.heightPixels;
947                    }
948                }
949            }
950
951            // Ask host how big it wants to be
952            if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
953                    "Measuring " + host + " in display " + desiredWindowWidth
954                    + "x" + desiredWindowHeight + "...");
955
956            boolean goodMeasure = false;
957            if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
958                // On large screens, we don't want to allow dialogs to just
959                // stretch to fill the entire width of the screen to display
960                // one line of text.  First try doing the layout at a smaller
961                // size to see if it will fit.
962                final DisplayMetrics packageMetrics = res.getDisplayMetrics();
963                res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
964                int baseSize = 0;
965                if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
966                    baseSize = (int)mTmpValue.getDimension(packageMetrics);
967                }
968                if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
969                if (baseSize != 0 && desiredWindowWidth > baseSize) {
970                    childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
971                    childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
972                    host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
973                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
974                            + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
975                    if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
976                        goodMeasure = true;
977                    } else {
978                        // Didn't fit in that size... try expanding a bit.
979                        baseSize = (baseSize+desiredWindowWidth)/2;
980                        if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
981                                + baseSize);
982                        childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
983                        host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
984                        if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
985                                + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
986                        if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
987                            if (DEBUG_DIALOG) Log.v(TAG, "Good!");
988                            goodMeasure = true;
989                        }
990                    }
991                }
992            }
993
994            if (!goodMeasure) {
995                childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
996                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
997                host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
998                if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
999                    windowSizeMayChange = true;
1000                }
1001            }
1002
1003            if (DBG) {
1004                System.out.println("======================================");
1005                System.out.println("performTraversals -- after measure");
1006                host.debug();
1007            }
1008        }
1009
1010        if (attachInfo.mRecomputeGlobalAttributes && host.mAttachInfo != null) {
1011            //Log.i(TAG, "Computing view hierarchy attributes!");
1012            attachInfo.mRecomputeGlobalAttributes = false;
1013            boolean oldScreenOn = attachInfo.mKeepScreenOn;
1014            int oldVis = attachInfo.mSystemUiVisibility;
1015            attachInfo.mKeepScreenOn = false;
1016            attachInfo.mSystemUiVisibility = 0;
1017            attachInfo.mHasSystemUiListeners = false;
1018            host.dispatchCollectViewAttributes(0);
1019            if (attachInfo.mKeepScreenOn != oldScreenOn
1020                    || attachInfo.mSystemUiVisibility != oldVis
1021                    || attachInfo.mHasSystemUiListeners) {
1022                params = lp;
1023            }
1024        }
1025
1026        if (mFirst || attachInfo.mViewVisibilityChanged) {
1027            attachInfo.mViewVisibilityChanged = false;
1028            int resizeMode = mSoftInputMode &
1029                    WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1030            // If we are in auto resize mode, then we need to determine
1031            // what mode to use now.
1032            if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1033                final int N = attachInfo.mScrollContainers.size();
1034                for (int i=0; i<N; i++) {
1035                    if (attachInfo.mScrollContainers.get(i).isShown()) {
1036                        resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1037                    }
1038                }
1039                if (resizeMode == 0) {
1040                    resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1041                }
1042                if ((lp.softInputMode &
1043                        WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1044                    lp.softInputMode = (lp.softInputMode &
1045                            ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1046                            resizeMode;
1047                    params = lp;
1048                }
1049            }
1050        }
1051
1052        if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1053            if (!PixelFormat.formatHasAlpha(params.format)) {
1054                params.format = PixelFormat.TRANSLUCENT;
1055            }
1056        }
1057
1058        boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
1059            && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
1060                || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1061                        frame.width() < desiredWindowWidth && frame.width() != mWidth)
1062                || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1063                        frame.height() < desiredWindowHeight && frame.height() != mHeight));
1064
1065        final boolean computesInternalInsets =
1066                attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
1067
1068        boolean insetsPending = false;
1069        int relayoutResult = 0;
1070
1071        if (mFirst || windowShouldResize || insetsChanged ||
1072                viewVisibilityChanged || params != null) {
1073
1074            if (viewVisibility == View.VISIBLE) {
1075                // If this window is giving internal insets to the window
1076                // manager, and it is being added or changing its visibility,
1077                // then we want to first give the window manager "fake"
1078                // insets to cause it to effectively ignore the content of
1079                // the window during layout.  This avoids it briefly causing
1080                // other windows to resize/move based on the raw frame of the
1081                // window, waiting until we can finish laying out this window
1082                // and get back to the window manager with the ultimately
1083                // computed insets.
1084                insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1085            }
1086
1087            if (mSurfaceHolder != null) {
1088                mSurfaceHolder.mSurfaceLock.lock();
1089                mDrawingAllowed = true;
1090            }
1091
1092            boolean hwInitialized = false;
1093            boolean contentInsetsChanged = false;
1094            boolean visibleInsetsChanged;
1095            boolean hadSurface = mSurface.isValid();
1096
1097            try {
1098                int fl = 0;
1099                if (params != null) {
1100                    fl = params.flags;
1101                    if (attachInfo.mKeepScreenOn) {
1102                        params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1103                    }
1104                    params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
1105                    params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners
1106                            || params.subtreeSystemUiVisibility != 0
1107                            || params.systemUiVisibility != 0;
1108                }
1109                if (DEBUG_LAYOUT) {
1110                    Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1111                            host.getMeasuredHeight() + ", params=" + params);
1112                }
1113
1114                final int surfaceGenerationId = mSurface.getGenerationId();
1115                relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1116
1117                if (params != null) {
1118                    params.flags = fl;
1119                }
1120
1121                if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1122                        + " content=" + mPendingContentInsets.toShortString()
1123                        + " visible=" + mPendingVisibleInsets.toShortString()
1124                        + " surface=" + mSurface);
1125
1126                if (mPendingConfiguration.seq != 0) {
1127                    if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1128                            + mPendingConfiguration);
1129                    updateConfiguration(mPendingConfiguration, !mFirst);
1130                    mPendingConfiguration.seq = 0;
1131                }
1132
1133                contentInsetsChanged = !mPendingContentInsets.equals(
1134                        mAttachInfo.mContentInsets);
1135                visibleInsetsChanged = !mPendingVisibleInsets.equals(
1136                        mAttachInfo.mVisibleInsets);
1137                if (contentInsetsChanged) {
1138                    if (mWidth > 0 && mHeight > 0 &&
1139                            mSurface != null && mSurface.isValid() &&
1140                            !mAttachInfo.mTurnOffWindowResizeAnim &&
1141                            mAttachInfo.mHardwareRenderer != null &&
1142                            mAttachInfo.mHardwareRenderer.isEnabled() &&
1143                            mAttachInfo.mHardwareRenderer.validate() &&
1144                            lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
1145
1146                        disposeResizeBuffer();
1147
1148                        boolean completed = false;
1149                        HardwareCanvas canvas = null;
1150                        try {
1151                            if (mResizeBuffer == null) {
1152                                mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
1153                                        mWidth, mHeight, false);
1154                            } else if (mResizeBuffer.getWidth() != mWidth ||
1155                                    mResizeBuffer.getHeight() != mHeight) {
1156                                mResizeBuffer.resize(mWidth, mHeight);
1157                            }
1158                            canvas = mResizeBuffer.start(mAttachInfo.mHardwareCanvas);
1159                            canvas.setViewport(mWidth, mHeight);
1160                            canvas.onPreDraw(null);
1161                            final int restoreCount = canvas.save();
1162
1163                            canvas.drawColor(0xff000000, PorterDuff.Mode.SRC);
1164
1165                            int yoff;
1166                            final boolean scrolling = mScroller != null
1167                                    && mScroller.computeScrollOffset();
1168                            if (scrolling) {
1169                                yoff = mScroller.getCurrY();
1170                                mScroller.abortAnimation();
1171                            } else {
1172                                yoff = mScrollY;
1173                            }
1174
1175                            canvas.translate(0, -yoff);
1176                            if (mTranslator != null) {
1177                                mTranslator.translateCanvas(canvas);
1178                            }
1179
1180                            mView.draw(canvas);
1181
1182                            mResizeBufferStartTime = SystemClock.uptimeMillis();
1183                            mResizeBufferDuration = mView.getResources().getInteger(
1184                                    com.android.internal.R.integer.config_mediumAnimTime);
1185                            completed = true;
1186
1187                            canvas.restoreToCount(restoreCount);
1188                        } catch (OutOfMemoryError e) {
1189                            Log.w(TAG, "Not enough memory for content change anim buffer", e);
1190                        } finally {
1191                            if (canvas != null) {
1192                                canvas.onPostDraw();
1193                            }
1194                            if (mResizeBuffer != null) {
1195                                mResizeBuffer.end(mAttachInfo.mHardwareCanvas);
1196                                if (!completed) {
1197                                    mResizeBuffer.destroy();
1198                                    mResizeBuffer = null;
1199                                }
1200                            }
1201                        }
1202                    }
1203                    mAttachInfo.mContentInsets.set(mPendingContentInsets);
1204                    host.fitSystemWindows(mAttachInfo.mContentInsets);
1205                    if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1206                            + mAttachInfo.mContentInsets);
1207                }
1208                if (visibleInsetsChanged) {
1209                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1210                    if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1211                            + mAttachInfo.mVisibleInsets);
1212                }
1213
1214                if (!hadSurface) {
1215                    if (mSurface.isValid()) {
1216                        // If we are creating a new surface, then we need to
1217                        // completely redraw it.  Also, when we get to the
1218                        // point of drawing it we will hold off and schedule
1219                        // a new traversal instead.  This is so we can tell the
1220                        // window manager about all of the windows being displayed
1221                        // before actually drawing them, so it can display then
1222                        // all at once.
1223                        newSurface = true;
1224                        fullRedrawNeeded = true;
1225                        mPreviousTransparentRegion.setEmpty();
1226
1227                        if (mAttachInfo.mHardwareRenderer != null) {
1228                            try {
1229                                hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
1230                            } catch (Surface.OutOfResourcesException e) {
1231                                Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
1232                                try {
1233                                    if (!sWindowSession.outOfMemory(mWindow)) {
1234                                        Slog.w(TAG, "No processes killed for memory; killing self");
1235                                        Process.killProcess(Process.myPid());
1236                                    }
1237                                } catch (RemoteException ex) {
1238                                }
1239                                mLayoutRequested = true;    // ask wm for a new surface next time.
1240                                return;
1241                            }
1242                        }
1243                    }
1244                } else if (!mSurface.isValid()) {
1245                    // If the surface has been removed, then reset the scroll
1246                    // positions.
1247                    mLastScrolledFocus = null;
1248                    mScrollY = mCurScrollY = 0;
1249                    if (mScroller != null) {
1250                        mScroller.abortAnimation();
1251                    }
1252                    disposeResizeBuffer();
1253                    // Our surface is gone
1254                    if (mAttachInfo.mHardwareRenderer != null &&
1255                            mAttachInfo.mHardwareRenderer.isEnabled()) {
1256                        mAttachInfo.mHardwareRenderer.destroy(true);
1257                    }
1258                } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1259                        mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1260                    fullRedrawNeeded = true;
1261                    try {
1262                        mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
1263                    } catch (Surface.OutOfResourcesException e) {
1264                        Log.e(TAG, "OutOfResourcesException updating HW surface", e);
1265                        try {
1266                            if (!sWindowSession.outOfMemory(mWindow)) {
1267                                Slog.w(TAG, "No processes killed for memory; killing self");
1268                                Process.killProcess(Process.myPid());
1269                            }
1270                        } catch (RemoteException ex) {
1271                        }
1272                        mLayoutRequested = true;    // ask wm for a new surface next time.
1273                        return;
1274                    }
1275                }
1276            } catch (RemoteException e) {
1277            }
1278
1279            if (DEBUG_ORIENTATION) Log.v(
1280                    TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1281
1282            attachInfo.mWindowLeft = frame.left;
1283            attachInfo.mWindowTop = frame.top;
1284
1285            // !!FIXME!! This next section handles the case where we did not get the
1286            // window size we asked for. We should avoid this by getting a maximum size from
1287            // the window session beforehand.
1288            mWidth = frame.width();
1289            mHeight = frame.height();
1290
1291            if (mSurfaceHolder != null) {
1292                // The app owns the surface; tell it about what is going on.
1293                if (mSurface.isValid()) {
1294                    // XXX .copyFrom() doesn't work!
1295                    //mSurfaceHolder.mSurface.copyFrom(mSurface);
1296                    mSurfaceHolder.mSurface = mSurface;
1297                }
1298                mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1299                mSurfaceHolder.mSurfaceLock.unlock();
1300                if (mSurface.isValid()) {
1301                    if (!hadSurface) {
1302                        mSurfaceHolder.ungetCallbacks();
1303
1304                        mIsCreating = true;
1305                        mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1306                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1307                        if (callbacks != null) {
1308                            for (SurfaceHolder.Callback c : callbacks) {
1309                                c.surfaceCreated(mSurfaceHolder);
1310                            }
1311                        }
1312                        surfaceChanged = true;
1313                    }
1314                    if (surfaceChanged) {
1315                        mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1316                                lp.format, mWidth, mHeight);
1317                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1318                        if (callbacks != null) {
1319                            for (SurfaceHolder.Callback c : callbacks) {
1320                                c.surfaceChanged(mSurfaceHolder, lp.format,
1321                                        mWidth, mHeight);
1322                            }
1323                        }
1324                    }
1325                    mIsCreating = false;
1326                } else if (hadSurface) {
1327                    mSurfaceHolder.ungetCallbacks();
1328                    SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1329                    mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1330                    if (callbacks != null) {
1331                        for (SurfaceHolder.Callback c : callbacks) {
1332                            c.surfaceDestroyed(mSurfaceHolder);
1333                        }
1334                    }
1335                    mSurfaceHolder.mSurfaceLock.lock();
1336                    try {
1337                        mSurfaceHolder.mSurface = new Surface();
1338                    } finally {
1339                        mSurfaceHolder.mSurfaceLock.unlock();
1340                    }
1341                }
1342            }
1343
1344            if (hwInitialized || ((windowShouldResize || params != null) &&
1345                    mAttachInfo.mHardwareRenderer != null &&
1346                    mAttachInfo.mHardwareRenderer.isEnabled())) {
1347                mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
1348                if (!hwInitialized) {
1349                    mAttachInfo.mHardwareRenderer.invalidate(mHolder);
1350                }
1351            }
1352
1353            if (!mStopped) {
1354                boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1355                        (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
1356                if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1357                        || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1358                    childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1359                    childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1360
1361                    if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed!  mWidth="
1362                            + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1363                            + " mHeight=" + mHeight
1364                            + " measuredHeight=" + host.getMeasuredHeight()
1365                            + " coveredInsetsChanged=" + contentInsetsChanged);
1366
1367                     // Ask host how big it wants to be
1368                    host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1369
1370                    // Implementation of weights from WindowManager.LayoutParams
1371                    // We just grow the dimensions as needed and re-measure if
1372                    // needs be
1373                    int width = host.getMeasuredWidth();
1374                    int height = host.getMeasuredHeight();
1375                    boolean measureAgain = false;
1376
1377                    if (lp.horizontalWeight > 0.0f) {
1378                        width += (int) ((mWidth - width) * lp.horizontalWeight);
1379                        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1380                                MeasureSpec.EXACTLY);
1381                        measureAgain = true;
1382                    }
1383                    if (lp.verticalWeight > 0.0f) {
1384                        height += (int) ((mHeight - height) * lp.verticalWeight);
1385                        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1386                                MeasureSpec.EXACTLY);
1387                        measureAgain = true;
1388                    }
1389
1390                    if (measureAgain) {
1391                        if (DEBUG_LAYOUT) Log.v(TAG,
1392                                "And hey let's measure once more: width=" + width
1393                                + " height=" + height);
1394                        host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1395                    }
1396
1397                    mLayoutRequested = true;
1398                }
1399            }
1400        }
1401
1402        final boolean didLayout = mLayoutRequested && !mStopped;
1403        boolean triggerGlobalLayoutListener = didLayout
1404                || attachInfo.mRecomputeGlobalAttributes;
1405        if (didLayout) {
1406            mLayoutRequested = false;
1407            mScrollMayChange = true;
1408            if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1409                TAG, "Laying out " + host + " to (" +
1410                host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
1411            long startTime = 0L;
1412            if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
1413                startTime = SystemClock.elapsedRealtime();
1414            }
1415            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
1416
1417            if (false && ViewDebug.consistencyCheckEnabled) {
1418                if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1419                    throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1420                            + "please refer to the logs with the tag "
1421                            + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1422                }
1423            }
1424
1425            if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
1426                EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1427            }
1428
1429            // By this point all views have been sized and positionned
1430            // We can compute the transparent area
1431
1432            if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1433                // start out transparent
1434                // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1435                host.getLocationInWindow(mTmpLocation);
1436                mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1437                        mTmpLocation[0] + host.mRight - host.mLeft,
1438                        mTmpLocation[1] + host.mBottom - host.mTop);
1439
1440                host.gatherTransparentRegion(mTransparentRegion);
1441                if (mTranslator != null) {
1442                    mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1443                }
1444
1445                if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1446                    mPreviousTransparentRegion.set(mTransparentRegion);
1447                    // reconfigure window manager
1448                    try {
1449                        sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1450                    } catch (RemoteException e) {
1451                    }
1452                }
1453            }
1454
1455            if (DBG) {
1456                System.out.println("======================================");
1457                System.out.println("performTraversals -- after setFrame");
1458                host.debug();
1459            }
1460        }
1461
1462        if (triggerGlobalLayoutListener) {
1463            attachInfo.mRecomputeGlobalAttributes = false;
1464            attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1465
1466            if (AccessibilityManager.getInstance(host.mContext).isEnabled()) {
1467                postSendWindowContentChangedCallback();
1468            }
1469        }
1470
1471        if (computesInternalInsets) {
1472            // Clear the original insets.
1473            final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1474            insets.reset();
1475
1476            // Compute new insets in place.
1477            attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
1478
1479            // Tell the window manager.
1480            if (insetsPending || !mLastGivenInsets.equals(insets)) {
1481                mLastGivenInsets.set(insets);
1482
1483                // Translate insets to screen coordinates if needed.
1484                final Rect contentInsets;
1485                final Rect visibleInsets;
1486                final Region touchableRegion;
1487                if (mTranslator != null) {
1488                    contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1489                    visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1490                    touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1491                } else {
1492                    contentInsets = insets.contentInsets;
1493                    visibleInsets = insets.visibleInsets;
1494                    touchableRegion = insets.touchableRegion;
1495                }
1496
1497                try {
1498                    sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
1499                            contentInsets, visibleInsets, touchableRegion);
1500                } catch (RemoteException e) {
1501                }
1502            }
1503        }
1504
1505        if (mFirst) {
1506            // handle first focus request
1507            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1508                    + mView.hasFocus());
1509            if (mView != null) {
1510                if (!mView.hasFocus()) {
1511                    mView.requestFocus(View.FOCUS_FORWARD);
1512                    mFocusedView = mRealFocusedView = mView.findFocus();
1513                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1514                            + mFocusedView);
1515                } else {
1516                    mRealFocusedView = mView.findFocus();
1517                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1518                            + mRealFocusedView);
1519                }
1520            }
1521        }
1522
1523        mFirst = false;
1524        mWillDrawSoon = false;
1525        mNewSurfaceNeeded = false;
1526        mViewVisibility = viewVisibility;
1527
1528        if (mAttachInfo.mHasWindowFocus) {
1529            final boolean imTarget = WindowManager.LayoutParams
1530                    .mayUseInputMethod(mWindowAttributes.flags);
1531            if (imTarget != mLastWasImTarget) {
1532                mLastWasImTarget = imTarget;
1533                InputMethodManager imm = InputMethodManager.peekInstance();
1534                if (imm != null && imTarget) {
1535                    imm.startGettingWindowFocus(mView);
1536                    imm.onWindowFocus(mView, mView.findFocus(),
1537                            mWindowAttributes.softInputMode,
1538                            !mHasHadWindowFocus, mWindowAttributes.flags);
1539                }
1540            }
1541        }
1542
1543        boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() ||
1544                viewVisibility != View.VISIBLE;
1545
1546        if (!cancelDraw && !newSurface) {
1547            if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
1548                for (int i = 0; i < mPendingTransitions.size(); ++i) {
1549                    mPendingTransitions.get(i).startChangingAnimations();
1550                }
1551                mPendingTransitions.clear();
1552            }
1553            mFullRedrawNeeded = false;
1554
1555            final long drawStartTime;
1556            if (ViewDebug.DEBUG_LATENCY) {
1557                drawStartTime = System.nanoTime();
1558            }
1559
1560            draw(fullRedrawNeeded);
1561
1562            if (ViewDebug.DEBUG_LATENCY) {
1563                mLastDrawDurationNanos = System.nanoTime() - drawStartTime;
1564            }
1565
1566            if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1567                    || mReportNextDraw) {
1568                if (LOCAL_LOGV) {
1569                    Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1570                }
1571                mReportNextDraw = false;
1572                if (mSurfaceHolder != null && mSurface.isValid()) {
1573                    mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1574                    SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1575                    if (callbacks != null) {
1576                        for (SurfaceHolder.Callback c : callbacks) {
1577                            if (c instanceof SurfaceHolder.Callback2) {
1578                                ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1579                                        mSurfaceHolder);
1580                            }
1581                        }
1582                    }
1583                }
1584                try {
1585                    sWindowSession.finishDrawing(mWindow);
1586                } catch (RemoteException e) {
1587                }
1588            }
1589        } else {
1590            // We were supposed to report when we are done drawing. Since we canceled the
1591            // draw, remember it here.
1592            if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1593                mReportNextDraw = true;
1594            }
1595            if (fullRedrawNeeded) {
1596                mFullRedrawNeeded = true;
1597            }
1598
1599            if (viewVisibility == View.VISIBLE) {
1600                // Try again
1601                scheduleTraversals();
1602            }
1603        }
1604    }
1605
1606    public void requestTransparentRegion(View child) {
1607        // the test below should not fail unless someone is messing with us
1608        checkThread();
1609        if (mView == child) {
1610            mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1611            // Need to make sure we re-evaluate the window attributes next
1612            // time around, to ensure the window has the correct format.
1613            mWindowAttributesChanged = true;
1614            requestLayout();
1615        }
1616    }
1617
1618    /**
1619     * Figures out the measure spec for the root view in a window based on it's
1620     * layout params.
1621     *
1622     * @param windowSize
1623     *            The available width or height of the window
1624     *
1625     * @param rootDimension
1626     *            The layout params for one dimension (width or height) of the
1627     *            window.
1628     *
1629     * @return The measure spec to use to measure the root view.
1630     */
1631    private int getRootMeasureSpec(int windowSize, int rootDimension) {
1632        int measureSpec;
1633        switch (rootDimension) {
1634
1635        case ViewGroup.LayoutParams.MATCH_PARENT:
1636            // Window can't resize. Force root view to be windowSize.
1637            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1638            break;
1639        case ViewGroup.LayoutParams.WRAP_CONTENT:
1640            // Window can resize. Set max size for root view.
1641            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1642            break;
1643        default:
1644            // Window wants to be an exact size. Force root view to be that size.
1645            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1646            break;
1647        }
1648        return measureSpec;
1649    }
1650
1651    int mHardwareYOffset;
1652    int mResizeAlpha;
1653    final Paint mResizePaint = new Paint();
1654
1655    public void onHardwarePreDraw(HardwareCanvas canvas) {
1656        canvas.translate(0, -mHardwareYOffset);
1657    }
1658
1659    public void onHardwarePostDraw(HardwareCanvas canvas) {
1660        if (mResizeBuffer != null) {
1661            mResizePaint.setAlpha(mResizeAlpha);
1662            canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint);
1663        }
1664    }
1665
1666    /**
1667     * @hide
1668     */
1669    void outputDisplayList(View view) {
1670        if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) {
1671            DisplayList displayList = view.getDisplayList();
1672            if (displayList != null) {
1673                mAttachInfo.mHardwareCanvas.outputDisplayList(displayList);
1674            }
1675        }
1676    }
1677
1678    /**
1679     * @see #PROPERTY_PROFILE_RENDERING
1680     */
1681    private void profileRendering(boolean enabled) {
1682        if (mProfileRendering) {
1683            mRenderProfilingEnabled = enabled;
1684            if (mRenderProfiler == null) {
1685                mRenderProfiler = new Thread(new Runnable() {
1686                    @Override
1687                    public void run() {
1688                        Log.d(TAG, "Starting profiling thread");
1689                        while (mRenderProfilingEnabled) {
1690                            mAttachInfo.mHandler.post(new Runnable() {
1691                                @Override
1692                                public void run() {
1693                                    mDirty.set(0, 0, mWidth, mHeight);
1694                                    scheduleTraversals();
1695                                }
1696                            });
1697                            try {
1698                                // TODO: This should use vsync when we get an API
1699                                Thread.sleep(15);
1700                            } catch (InterruptedException e) {
1701                                Log.d(TAG, "Exiting profiling thread");
1702                            }
1703                        }
1704                    }
1705                }, "Rendering Profiler");
1706                mRenderProfiler.start();
1707            } else {
1708                mRenderProfiler.interrupt();
1709                mRenderProfiler = null;
1710            }
1711        }
1712    }
1713
1714    private void draw(boolean fullRedrawNeeded) {
1715        Surface surface = mSurface;
1716        if (surface == null || !surface.isValid()) {
1717            return;
1718        }
1719
1720        if (!sFirstDrawComplete) {
1721            synchronized (sFirstDrawHandlers) {
1722                sFirstDrawComplete = true;
1723                final int count = sFirstDrawHandlers.size();
1724                for (int i = 0; i< count; i++) {
1725                    post(sFirstDrawHandlers.get(i));
1726                }
1727            }
1728        }
1729
1730        scrollToRectOrFocus(null, false);
1731
1732        if (mAttachInfo.mViewScrollChanged) {
1733            mAttachInfo.mViewScrollChanged = false;
1734            mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1735        }
1736
1737        int yoff;
1738        boolean animating = mScroller != null && mScroller.computeScrollOffset();
1739        if (animating) {
1740            yoff = mScroller.getCurrY();
1741        } else {
1742            yoff = mScrollY;
1743        }
1744        if (mCurScrollY != yoff) {
1745            mCurScrollY = yoff;
1746            fullRedrawNeeded = true;
1747        }
1748        float appScale = mAttachInfo.mApplicationScale;
1749        boolean scalingRequired = mAttachInfo.mScalingRequired;
1750
1751        int resizeAlpha = 0;
1752        if (mResizeBuffer != null) {
1753            long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
1754            if (deltaTime < mResizeBufferDuration) {
1755                float amt = deltaTime/(float) mResizeBufferDuration;
1756                amt = mResizeInterpolator.getInterpolation(amt);
1757                animating = true;
1758                resizeAlpha = 255 - (int)(amt*255);
1759            } else {
1760                disposeResizeBuffer();
1761            }
1762        }
1763
1764        Rect dirty = mDirty;
1765        if (mSurfaceHolder != null) {
1766            // The app owns the surface, we won't draw.
1767            dirty.setEmpty();
1768            if (animating) {
1769                if (mScroller != null) {
1770                    mScroller.abortAnimation();
1771                }
1772                disposeResizeBuffer();
1773            }
1774            return;
1775        }
1776
1777        if (fullRedrawNeeded) {
1778            mAttachInfo.mIgnoreDirtyState = true;
1779            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1780        }
1781
1782        if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
1783            if (!dirty.isEmpty() || mIsAnimating) {
1784                mIsAnimating = false;
1785                mHardwareYOffset = yoff;
1786                mResizeAlpha = resizeAlpha;
1787
1788                mCurrentDirty.set(dirty);
1789                mCurrentDirty.union(mPreviousDirty);
1790                mPreviousDirty.set(dirty);
1791                dirty.setEmpty();
1792
1793                Rect currentDirty = mCurrentDirty;
1794                if (animating) {
1795                    currentDirty = null;
1796                }
1797
1798                if (mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, currentDirty)) {
1799                    mPreviousDirty.set(0, 0, mWidth, mHeight);
1800                }
1801            }
1802
1803            if (animating) {
1804                mFullRedrawNeeded = true;
1805                scheduleTraversals();
1806            }
1807
1808            return;
1809        }
1810
1811        if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1812            Log.v(TAG, "Draw " + mView + "/"
1813                    + mWindowAttributes.getTitle()
1814                    + ": dirty={" + dirty.left + "," + dirty.top
1815                    + "," + dirty.right + "," + dirty.bottom + "} surface="
1816                    + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1817                    appScale + ", width=" + mWidth + ", height=" + mHeight);
1818        }
1819
1820        if (!dirty.isEmpty() || mIsAnimating) {
1821            Canvas canvas;
1822            try {
1823                int left = dirty.left;
1824                int top = dirty.top;
1825                int right = dirty.right;
1826                int bottom = dirty.bottom;
1827
1828                final long lockCanvasStartTime;
1829                if (ViewDebug.DEBUG_LATENCY) {
1830                    lockCanvasStartTime = System.nanoTime();
1831                }
1832
1833                canvas = surface.lockCanvas(dirty);
1834
1835                if (ViewDebug.DEBUG_LATENCY) {
1836                    long now = System.nanoTime();
1837                    Log.d(TAG, "Latency: Spent "
1838                            + ((now - lockCanvasStartTime) * 0.000001f)
1839                            + "ms waiting for surface.lockCanvas()");
1840                }
1841
1842                if (left != dirty.left || top != dirty.top || right != dirty.right ||
1843                        bottom != dirty.bottom) {
1844                    mAttachInfo.mIgnoreDirtyState = true;
1845                }
1846
1847                // TODO: Do this in native
1848                canvas.setDensity(mDensity);
1849            } catch (Surface.OutOfResourcesException e) {
1850                Log.e(TAG, "OutOfResourcesException locking surface", e);
1851                try {
1852                    if (!sWindowSession.outOfMemory(mWindow)) {
1853                        Slog.w(TAG, "No processes killed for memory; killing self");
1854                        Process.killProcess(Process.myPid());
1855                    }
1856                } catch (RemoteException ex) {
1857                }
1858                mLayoutRequested = true;    // ask wm for a new surface next time.
1859                return;
1860            } catch (IllegalArgumentException e) {
1861                Log.e(TAG, "IllegalArgumentException locking surface", e);
1862                // Don't assume this is due to out of memory, it could be
1863                // something else, and if it is something else then we could
1864                // kill stuff (or ourself) for no reason.
1865                mLayoutRequested = true;    // ask wm for a new surface next time.
1866                return;
1867            }
1868
1869            try {
1870                if (!dirty.isEmpty() || mIsAnimating) {
1871                    long startTime = 0L;
1872
1873                    if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1874                        Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
1875                                + canvas.getWidth() + ", h=" + canvas.getHeight());
1876                        //canvas.drawARGB(255, 255, 0, 0);
1877                    }
1878
1879                    if (ViewDebug.DEBUG_PROFILE_DRAWING) {
1880                        startTime = SystemClock.elapsedRealtime();
1881                    }
1882
1883                    // If this bitmap's format includes an alpha channel, we
1884                    // need to clear it before drawing so that the child will
1885                    // properly re-composite its drawing on a transparent
1886                    // background. This automatically respects the clip/dirty region
1887                    // or
1888                    // If we are applying an offset, we need to clear the area
1889                    // where the offset doesn't appear to avoid having garbage
1890                    // left in the blank areas.
1891                    if (!canvas.isOpaque() || yoff != 0) {
1892                        canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1893                    }
1894
1895                    dirty.setEmpty();
1896                    mIsAnimating = false;
1897                    mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1898                    mView.mPrivateFlags |= View.DRAWN;
1899
1900                    if (DEBUG_DRAW) {
1901                        Context cxt = mView.getContext();
1902                        Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1903                                ", metrics=" + cxt.getResources().getDisplayMetrics() +
1904                                ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1905                    }
1906                    try {
1907                        canvas.translate(0, -yoff);
1908                        if (mTranslator != null) {
1909                            mTranslator.translateCanvas(canvas);
1910                        }
1911                        canvas.setScreenDensity(scalingRequired
1912                                ? DisplayMetrics.DENSITY_DEVICE : 0);
1913                        mAttachInfo.mSetIgnoreDirtyState = false;
1914                        mView.draw(canvas);
1915                    } finally {
1916                        if (!mAttachInfo.mSetIgnoreDirtyState) {
1917                            // Only clear the flag if it was not set during the mView.draw() call
1918                            mAttachInfo.mIgnoreDirtyState = false;
1919                        }
1920                    }
1921
1922                    if (false && ViewDebug.consistencyCheckEnabled) {
1923                        mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1924                    }
1925
1926                    if (ViewDebug.DEBUG_PROFILE_DRAWING) {
1927                        EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1928                    }
1929                }
1930
1931            } finally {
1932                surface.unlockCanvasAndPost(canvas);
1933            }
1934        }
1935
1936        if (LOCAL_LOGV) {
1937            Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
1938        }
1939
1940        if (animating) {
1941            mFullRedrawNeeded = true;
1942            scheduleTraversals();
1943        }
1944    }
1945
1946    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1947        final View.AttachInfo attachInfo = mAttachInfo;
1948        final Rect ci = attachInfo.mContentInsets;
1949        final Rect vi = attachInfo.mVisibleInsets;
1950        int scrollY = 0;
1951        boolean handled = false;
1952
1953        if (vi.left > ci.left || vi.top > ci.top
1954                || vi.right > ci.right || vi.bottom > ci.bottom) {
1955            // We'll assume that we aren't going to change the scroll
1956            // offset, since we want to avoid that unless it is actually
1957            // going to make the focus visible...  otherwise we scroll
1958            // all over the place.
1959            scrollY = mScrollY;
1960            // We can be called for two different situations: during a draw,
1961            // to update the scroll position if the focus has changed (in which
1962            // case 'rectangle' is null), or in response to a
1963            // requestChildRectangleOnScreen() call (in which case 'rectangle'
1964            // is non-null and we just want to scroll to whatever that
1965            // rectangle is).
1966            View focus = mRealFocusedView;
1967
1968            // When in touch mode, focus points to the previously focused view,
1969            // which may have been removed from the view hierarchy. The following
1970            // line checks whether the view is still in our hierarchy.
1971            if (focus == null || focus.mAttachInfo != mAttachInfo) {
1972                mRealFocusedView = null;
1973                return false;
1974            }
1975
1976            if (focus != mLastScrolledFocus) {
1977                // If the focus has changed, then ignore any requests to scroll
1978                // to a rectangle; first we want to make sure the entire focus
1979                // view is visible.
1980                rectangle = null;
1981            }
1982            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1983                    + " rectangle=" + rectangle + " ci=" + ci
1984                    + " vi=" + vi);
1985            if (focus == mLastScrolledFocus && !mScrollMayChange
1986                    && rectangle == null) {
1987                // Optimization: if the focus hasn't changed since last
1988                // time, and no layout has happened, then just leave things
1989                // as they are.
1990                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1991                        + mScrollY + " vi=" + vi.toShortString());
1992            } else if (focus != null) {
1993                // We need to determine if the currently focused view is
1994                // within the visible part of the window and, if not, apply
1995                // a pan so it can be seen.
1996                mLastScrolledFocus = focus;
1997                mScrollMayChange = false;
1998                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1999                // Try to find the rectangle from the focus view.
2000                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2001                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2002                            + mView.getWidth() + " h=" + mView.getHeight()
2003                            + " ci=" + ci.toShortString()
2004                            + " vi=" + vi.toShortString());
2005                    if (rectangle == null) {
2006                        focus.getFocusedRect(mTempRect);
2007                        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2008                                + ": focusRect=" + mTempRect.toShortString());
2009                        if (mView instanceof ViewGroup) {
2010                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2011                                    focus, mTempRect);
2012                        }
2013                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2014                                "Focus in window: focusRect="
2015                                + mTempRect.toShortString()
2016                                + " visRect=" + mVisRect.toShortString());
2017                    } else {
2018                        mTempRect.set(rectangle);
2019                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2020                                "Request scroll to rect: "
2021                                + mTempRect.toShortString()
2022                                + " visRect=" + mVisRect.toShortString());
2023                    }
2024                    if (mTempRect.intersect(mVisRect)) {
2025                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2026                                "Focus window visible rect: "
2027                                + mTempRect.toShortString());
2028                        if (mTempRect.height() >
2029                                (mView.getHeight()-vi.top-vi.bottom)) {
2030                            // If the focus simply is not going to fit, then
2031                            // best is probably just to leave things as-is.
2032                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2033                                    "Too tall; leaving scrollY=" + scrollY);
2034                        } else if ((mTempRect.top-scrollY) < vi.top) {
2035                            scrollY -= vi.top - (mTempRect.top-scrollY);
2036                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2037                                    "Top covered; scrollY=" + scrollY);
2038                        } else if ((mTempRect.bottom-scrollY)
2039                                > (mView.getHeight()-vi.bottom)) {
2040                            scrollY += (mTempRect.bottom-scrollY)
2041                                    - (mView.getHeight()-vi.bottom);
2042                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2043                                    "Bottom covered; scrollY=" + scrollY);
2044                        }
2045                        handled = true;
2046                    }
2047                }
2048            }
2049        }
2050
2051        if (scrollY != mScrollY) {
2052            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2053                    + mScrollY + " , new=" + scrollY);
2054            if (!immediate && mResizeBuffer == null) {
2055                if (mScroller == null) {
2056                    mScroller = new Scroller(mView.getContext());
2057                }
2058                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2059            } else if (mScroller != null) {
2060                mScroller.abortAnimation();
2061            }
2062            mScrollY = scrollY;
2063        }
2064
2065        return handled;
2066    }
2067
2068    public void requestChildFocus(View child, View focused) {
2069        checkThread();
2070        if (mFocusedView != focused) {
2071            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
2072            scheduleTraversals();
2073        }
2074        mFocusedView = mRealFocusedView = focused;
2075        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
2076                + mFocusedView);
2077    }
2078
2079    public void clearChildFocus(View child) {
2080        checkThread();
2081
2082        View oldFocus = mFocusedView;
2083
2084        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
2085        mFocusedView = mRealFocusedView = null;
2086        if (mView != null && !mView.hasFocus()) {
2087            // If a view gets the focus, the listener will be invoked from requestChildFocus()
2088            if (!mView.requestFocus(View.FOCUS_FORWARD)) {
2089                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
2090            }
2091        } else if (oldFocus != null) {
2092            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
2093        }
2094    }
2095
2096
2097    public void focusableViewAvailable(View v) {
2098        checkThread();
2099
2100        if (mView != null) {
2101            if (!mView.hasFocus()) {
2102                v.requestFocus();
2103            } else {
2104                // the one case where will transfer focus away from the current one
2105                // is if the current view is a view group that prefers to give focus
2106                // to its children first AND the view is a descendant of it.
2107                mFocusedView = mView.findFocus();
2108                boolean descendantsHaveDibsOnFocus =
2109                        (mFocusedView instanceof ViewGroup) &&
2110                            (((ViewGroup) mFocusedView).getDescendantFocusability() ==
2111                                    ViewGroup.FOCUS_AFTER_DESCENDANTS);
2112                if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
2113                    // If a view gets the focus, the listener will be invoked from requestChildFocus()
2114                    v.requestFocus();
2115                }
2116            }
2117        }
2118    }
2119
2120    public void recomputeViewAttributes(View child) {
2121        checkThread();
2122        if (mView == child) {
2123            mAttachInfo.mRecomputeGlobalAttributes = true;
2124            if (!mWillDrawSoon) {
2125                scheduleTraversals();
2126            }
2127        }
2128    }
2129
2130    void dispatchDetachedFromWindow() {
2131        if (mView != null && mView.mAttachInfo != null) {
2132            mView.dispatchDetachedFromWindow();
2133        }
2134
2135        mAccessibilityInteractionConnectionManager.ensureNoConnection();
2136        mAccessibilityManager.removeAccessibilityStateChangeListener(
2137                mAccessibilityInteractionConnectionManager);
2138        removeSendWindowContentChangedCallback();
2139
2140        mView = null;
2141        mAttachInfo.mRootView = null;
2142        mAttachInfo.mSurface = null;
2143
2144        destroyHardwareRenderer();
2145
2146        mSurface.release();
2147
2148        if (mInputChannel != null) {
2149            if (mInputQueueCallback != null) {
2150                mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2151                mInputQueueCallback = null;
2152            } else {
2153                InputQueue.unregisterInputChannel(mInputChannel);
2154            }
2155        }
2156        try {
2157            sWindowSession.remove(mWindow);
2158        } catch (RemoteException e) {
2159        }
2160
2161        // Dispose the input channel after removing the window so the Window Manager
2162        // doesn't interpret the input channel being closed as an abnormal termination.
2163        if (mInputChannel != null) {
2164            mInputChannel.dispose();
2165            mInputChannel = null;
2166        }
2167    }
2168
2169    void updateConfiguration(Configuration config, boolean force) {
2170        if (DEBUG_CONFIGURATION) Log.v(TAG,
2171                "Applying new config to window "
2172                + mWindowAttributes.getTitle()
2173                + ": " + config);
2174
2175        CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2176        if (ci != null) {
2177            config = new Configuration(config);
2178            ci.applyToConfiguration(config);
2179        }
2180
2181        synchronized (sConfigCallbacks) {
2182            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2183                sConfigCallbacks.get(i).onConfigurationChanged(config);
2184            }
2185        }
2186        if (mView != null) {
2187            // At this point the resources have been updated to
2188            // have the most recent config, whatever that is.  Use
2189            // the on in them which may be newer.
2190            config = mView.getResources().getConfiguration();
2191            if (force || mLastConfiguration.diff(config) != 0) {
2192                mLastConfiguration.setTo(config);
2193                mView.dispatchConfigurationChanged(config);
2194            }
2195        }
2196    }
2197
2198    /**
2199     * Return true if child is an ancestor of parent, (or equal to the parent).
2200     */
2201    private static boolean isViewDescendantOf(View child, View parent) {
2202        if (child == parent) {
2203            return true;
2204        }
2205
2206        final ViewParent theParent = child.getParent();
2207        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2208    }
2209
2210    private static void forceLayout(View view) {
2211        view.forceLayout();
2212        if (view instanceof ViewGroup) {
2213            ViewGroup group = (ViewGroup) view;
2214            final int count = group.getChildCount();
2215            for (int i = 0; i < count; i++) {
2216                forceLayout(group.getChildAt(i));
2217            }
2218        }
2219    }
2220
2221    public final static int DO_TRAVERSAL = 1000;
2222    public final static int DIE = 1001;
2223    public final static int RESIZED = 1002;
2224    public final static int RESIZED_REPORT = 1003;
2225    public final static int WINDOW_FOCUS_CHANGED = 1004;
2226    public final static int DISPATCH_KEY = 1005;
2227    public final static int DISPATCH_POINTER = 1006;
2228    public final static int DISPATCH_TRACKBALL = 1007;
2229    public final static int DISPATCH_APP_VISIBILITY = 1008;
2230    public final static int DISPATCH_GET_NEW_SURFACE = 1009;
2231    public final static int FINISHED_EVENT = 1010;
2232    public final static int DISPATCH_KEY_FROM_IME = 1011;
2233    public final static int FINISH_INPUT_CONNECTION = 1012;
2234    public final static int CHECK_FOCUS = 1013;
2235    public final static int CLOSE_SYSTEM_DIALOGS = 1014;
2236    public final static int DISPATCH_DRAG_EVENT = 1015;
2237    public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
2238    public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
2239    public final static int DISPATCH_GENERIC_MOTION = 1018;
2240    public final static int UPDATE_CONFIGURATION = 1019;
2241    public final static int DO_PERFORM_ACCESSIBILITY_ACTION = 1020;
2242    public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID = 1021;
2243    public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID = 1022;
2244    public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT = 1023;
2245
2246    @Override
2247    public String getMessageName(Message message) {
2248        switch (message.what) {
2249            case DO_TRAVERSAL:
2250                return "DO_TRAVERSAL";
2251            case DIE:
2252                return "DIE";
2253            case RESIZED:
2254                return "RESIZED";
2255            case RESIZED_REPORT:
2256                return "RESIZED_REPORT";
2257            case WINDOW_FOCUS_CHANGED:
2258                return "WINDOW_FOCUS_CHANGED";
2259            case DISPATCH_KEY:
2260                return "DISPATCH_KEY";
2261            case DISPATCH_POINTER:
2262                return "DISPATCH_POINTER";
2263            case DISPATCH_TRACKBALL:
2264                return "DISPATCH_TRACKBALL";
2265            case DISPATCH_APP_VISIBILITY:
2266                return "DISPATCH_APP_VISIBILITY";
2267            case DISPATCH_GET_NEW_SURFACE:
2268                return "DISPATCH_GET_NEW_SURFACE";
2269            case FINISHED_EVENT:
2270                return "FINISHED_EVENT";
2271            case DISPATCH_KEY_FROM_IME:
2272                return "DISPATCH_KEY_FROM_IME";
2273            case FINISH_INPUT_CONNECTION:
2274                return "FINISH_INPUT_CONNECTION";
2275            case CHECK_FOCUS:
2276                return "CHECK_FOCUS";
2277            case CLOSE_SYSTEM_DIALOGS:
2278                return "CLOSE_SYSTEM_DIALOGS";
2279            case DISPATCH_DRAG_EVENT:
2280                return "DISPATCH_DRAG_EVENT";
2281            case DISPATCH_DRAG_LOCATION_EVENT:
2282                return "DISPATCH_DRAG_LOCATION_EVENT";
2283            case DISPATCH_SYSTEM_UI_VISIBILITY:
2284                return "DISPATCH_SYSTEM_UI_VISIBILITY";
2285            case DISPATCH_GENERIC_MOTION:
2286                return "DISPATCH_GENERIC_MOTION";
2287            case UPDATE_CONFIGURATION:
2288                return "UPDATE_CONFIGURATION";
2289            case DO_PERFORM_ACCESSIBILITY_ACTION:
2290                return "DO_PERFORM_ACCESSIBILITY_ACTION";
2291            case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID:
2292                return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID";
2293            case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID:
2294                return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID";
2295            case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT:
2296                return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT";
2297
2298        }
2299        return super.getMessageName(message);
2300    }
2301
2302    @Override
2303    public void handleMessage(Message msg) {
2304        switch (msg.what) {
2305        case View.AttachInfo.INVALIDATE_MSG:
2306            ((View) msg.obj).invalidate();
2307            break;
2308        case View.AttachInfo.INVALIDATE_RECT_MSG:
2309            final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2310            info.target.invalidate(info.left, info.top, info.right, info.bottom);
2311            info.release();
2312            break;
2313        case DO_TRAVERSAL:
2314            if (mProfile) {
2315                Debug.startMethodTracing("ViewAncestor");
2316            }
2317
2318            final long traversalStartTime;
2319            if (ViewDebug.DEBUG_LATENCY) {
2320                traversalStartTime = System.nanoTime();
2321                mLastDrawDurationNanos = 0;
2322            }
2323
2324            performTraversals();
2325
2326            if (ViewDebug.DEBUG_LATENCY) {
2327                long now = System.nanoTime();
2328                Log.d(TAG, "Latency: Spent "
2329                        + ((now - traversalStartTime) * 0.000001f)
2330                        + "ms in performTraversals(), with "
2331                        + (mLastDrawDurationNanos * 0.000001f)
2332                        + "ms of that time in draw()");
2333                mLastTraversalFinishedTimeNanos = now;
2334            }
2335
2336            if (mProfile) {
2337                Debug.stopMethodTracing();
2338                mProfile = false;
2339            }
2340            break;
2341        case FINISHED_EVENT:
2342            handleFinishedEvent(msg.arg1, msg.arg2 != 0);
2343            break;
2344        case DISPATCH_KEY:
2345            deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
2346            break;
2347        case DISPATCH_POINTER:
2348            deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2349            break;
2350        case DISPATCH_TRACKBALL:
2351            deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2352            break;
2353        case DISPATCH_GENERIC_MOTION:
2354            deliverGenericMotionEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2355            break;
2356        case DISPATCH_APP_VISIBILITY:
2357            handleAppVisibility(msg.arg1 != 0);
2358            break;
2359        case DISPATCH_GET_NEW_SURFACE:
2360            handleGetNewSurface();
2361            break;
2362        case RESIZED:
2363            ResizedInfo ri = (ResizedInfo)msg.obj;
2364
2365            if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
2366                    && mPendingContentInsets.equals(ri.coveredInsets)
2367                    && mPendingVisibleInsets.equals(ri.visibleInsets)
2368                    && ((ResizedInfo)msg.obj).newConfig == null) {
2369                break;
2370            }
2371            // fall through...
2372        case RESIZED_REPORT:
2373            if (mAdded) {
2374                Configuration config = ((ResizedInfo)msg.obj).newConfig;
2375                if (config != null) {
2376                    updateConfiguration(config, false);
2377                }
2378                mWinFrame.left = 0;
2379                mWinFrame.right = msg.arg1;
2380                mWinFrame.top = 0;
2381                mWinFrame.bottom = msg.arg2;
2382                mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
2383                mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
2384                if (msg.what == RESIZED_REPORT) {
2385                    mReportNextDraw = true;
2386                }
2387
2388                if (mView != null) {
2389                    forceLayout(mView);
2390                }
2391                requestLayout();
2392            }
2393            break;
2394        case WINDOW_FOCUS_CHANGED: {
2395            if (mAdded) {
2396                boolean hasWindowFocus = msg.arg1 != 0;
2397                mAttachInfo.mHasWindowFocus = hasWindowFocus;
2398
2399                profileRendering(hasWindowFocus);
2400
2401                if (hasWindowFocus) {
2402                    boolean inTouchMode = msg.arg2 != 0;
2403                    ensureTouchModeLocally(inTouchMode);
2404
2405                    if (mAttachInfo.mHardwareRenderer != null &&
2406                            mSurface != null && mSurface.isValid()) {
2407                        mFullRedrawNeeded = true;
2408                        try {
2409                            mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2410                                    mAttachInfo, mHolder);
2411                        } catch (Surface.OutOfResourcesException e) {
2412                            Log.e(TAG, "OutOfResourcesException locking surface", e);
2413                            try {
2414                                if (!sWindowSession.outOfMemory(mWindow)) {
2415                                    Slog.w(TAG, "No processes killed for memory; killing self");
2416                                    Process.killProcess(Process.myPid());
2417                                }
2418                            } catch (RemoteException ex) {
2419                            }
2420                            // Retry in a bit.
2421                            sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
2422                            return;
2423                        }
2424                    }
2425                }
2426
2427                mLastWasImTarget = WindowManager.LayoutParams
2428                        .mayUseInputMethod(mWindowAttributes.flags);
2429
2430                InputMethodManager imm = InputMethodManager.peekInstance();
2431                if (mView != null) {
2432                    if (hasWindowFocus && imm != null && mLastWasImTarget) {
2433                        imm.startGettingWindowFocus(mView);
2434                    }
2435                    mAttachInfo.mKeyDispatchState.reset();
2436                    mView.dispatchWindowFocusChanged(hasWindowFocus);
2437                }
2438
2439                // Note: must be done after the focus change callbacks,
2440                // so all of the view state is set up correctly.
2441                if (hasWindowFocus) {
2442                    if (imm != null && mLastWasImTarget) {
2443                        imm.onWindowFocus(mView, mView.findFocus(),
2444                                mWindowAttributes.softInputMode,
2445                                !mHasHadWindowFocus, mWindowAttributes.flags);
2446                    }
2447                    // Clear the forward bit.  We can just do this directly, since
2448                    // the window manager doesn't care about it.
2449                    mWindowAttributes.softInputMode &=
2450                            ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2451                    ((WindowManager.LayoutParams)mView.getLayoutParams())
2452                            .softInputMode &=
2453                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2454                    mHasHadWindowFocus = true;
2455                }
2456
2457                if (hasWindowFocus && mView != null) {
2458                    sendAccessibilityEvents();
2459                }
2460            }
2461        } break;
2462        case DIE:
2463            doDie();
2464            break;
2465        case DISPATCH_KEY_FROM_IME: {
2466            if (LOCAL_LOGV) Log.v(
2467                TAG, "Dispatching key "
2468                + msg.obj + " from IME to " + mView);
2469            KeyEvent event = (KeyEvent)msg.obj;
2470            if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2471                // The IME is trying to say this event is from the
2472                // system!  Bad bad bad!
2473                //noinspection UnusedAssignment
2474                event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
2475            }
2476            deliverKeyEventPostIme((KeyEvent)msg.obj, false);
2477        } break;
2478        case FINISH_INPUT_CONNECTION: {
2479            InputMethodManager imm = InputMethodManager.peekInstance();
2480            if (imm != null) {
2481                imm.reportFinishInputConnection((InputConnection)msg.obj);
2482            }
2483        } break;
2484        case CHECK_FOCUS: {
2485            InputMethodManager imm = InputMethodManager.peekInstance();
2486            if (imm != null) {
2487                imm.checkFocus();
2488            }
2489        } break;
2490        case CLOSE_SYSTEM_DIALOGS: {
2491            if (mView != null) {
2492                mView.onCloseSystemDialogs((String)msg.obj);
2493            }
2494        } break;
2495        case DISPATCH_DRAG_EVENT:
2496        case DISPATCH_DRAG_LOCATION_EVENT: {
2497            DragEvent event = (DragEvent)msg.obj;
2498            event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
2499            handleDragEvent(event);
2500        } break;
2501        case DISPATCH_SYSTEM_UI_VISIBILITY: {
2502            handleDispatchSystemUiVisibilityChanged(msg.arg1);
2503        } break;
2504        case UPDATE_CONFIGURATION: {
2505            Configuration config = (Configuration)msg.obj;
2506            if (config.isOtherSeqNewer(mLastConfiguration)) {
2507                config = mLastConfiguration;
2508            }
2509            updateConfiguration(config, false);
2510        } break;
2511        case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID: {
2512            if (mView != null) {
2513                getAccessibilityInteractionController()
2514                    .findAccessibilityNodeInfoByAccessibilityIdUiThread(msg);
2515            }
2516        } break;
2517        case DO_PERFORM_ACCESSIBILITY_ACTION: {
2518            if (mView != null) {
2519                getAccessibilityInteractionController()
2520                    .perfromAccessibilityActionUiThread(msg);
2521            }
2522        } break;
2523        case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID: {
2524            if (mView != null) {
2525                getAccessibilityInteractionController()
2526                    .findAccessibilityNodeInfoByViewIdUiThread(msg);
2527            }
2528        } break;
2529        case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT: {
2530            if (mView != null) {
2531                getAccessibilityInteractionController()
2532                    .findAccessibilityNodeInfosByViewTextUiThread(msg);
2533            }
2534        } break;
2535        }
2536    }
2537
2538    private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
2539        if (mFinishedCallback != null) {
2540            Slog.w(TAG, "Received a new input event from the input queue but there is "
2541                    + "already an unfinished input event in progress.");
2542        }
2543
2544        if (ViewDebug.DEBUG_LATENCY) {
2545            mInputEventReceiveTimeNanos = System.nanoTime();
2546            mInputEventDeliverTimeNanos = 0;
2547            mInputEventDeliverPostImeTimeNanos = 0;
2548        }
2549
2550        mFinishedCallback = finishedCallback;
2551    }
2552
2553    private void finishInputEvent(InputEvent event, boolean handled) {
2554        if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
2555
2556        if (mFinishedCallback == null) {
2557            Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2558                    + "is finished but there is no input event actually in progress.");
2559            return;
2560        }
2561
2562        if (ViewDebug.DEBUG_LATENCY) {
2563            final long now = System.nanoTime();
2564            final long eventTime = event.getEventTimeNano();
2565            final StringBuilder msg = new StringBuilder();
2566            msg.append("Latency: Spent ");
2567            msg.append((now - mInputEventReceiveTimeNanos) * 0.000001f);
2568            msg.append("ms processing ");
2569            if (event instanceof KeyEvent) {
2570                final KeyEvent  keyEvent = (KeyEvent)event;
2571                msg.append("key event, action=");
2572                msg.append(KeyEvent.actionToString(keyEvent.getAction()));
2573            } else {
2574                final MotionEvent motionEvent = (MotionEvent)event;
2575                msg.append("motion event, action=");
2576                msg.append(MotionEvent.actionToString(motionEvent.getAction()));
2577                msg.append(", historySize=");
2578                msg.append(motionEvent.getHistorySize());
2579            }
2580            msg.append(", handled=");
2581            msg.append(handled);
2582            msg.append(", received at +");
2583            msg.append((mInputEventReceiveTimeNanos - eventTime) * 0.000001f);
2584            if (mInputEventDeliverTimeNanos != 0) {
2585                msg.append("ms, delivered at +");
2586                msg.append((mInputEventDeliverTimeNanos - eventTime) * 0.000001f);
2587            }
2588            if (mInputEventDeliverPostImeTimeNanos != 0) {
2589                msg.append("ms, delivered post IME at +");
2590                msg.append((mInputEventDeliverPostImeTimeNanos - eventTime) * 0.000001f);
2591            }
2592            msg.append("ms, finished at +");
2593            msg.append((now - eventTime) * 0.000001f);
2594            msg.append("ms.");
2595            Log.d(TAG, msg.toString());
2596        }
2597
2598        mFinishedCallback.finished(handled);
2599        mFinishedCallback = null;
2600    }
2601
2602    /**
2603     * Something in the current window tells us we need to change the touch mode.  For
2604     * example, we are not in touch mode, and the user touches the screen.
2605     *
2606     * If the touch mode has changed, tell the window manager, and handle it locally.
2607     *
2608     * @param inTouchMode Whether we want to be in touch mode.
2609     * @return True if the touch mode changed and focus changed was changed as a result
2610     */
2611    boolean ensureTouchMode(boolean inTouchMode) {
2612        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2613                + "touch mode is " + mAttachInfo.mInTouchMode);
2614        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2615
2616        // tell the window manager
2617        try {
2618            sWindowSession.setInTouchMode(inTouchMode);
2619        } catch (RemoteException e) {
2620            throw new RuntimeException(e);
2621        }
2622
2623        // handle the change
2624        return ensureTouchModeLocally(inTouchMode);
2625    }
2626
2627    /**
2628     * Ensure that the touch mode for this window is set, and if it is changing,
2629     * take the appropriate action.
2630     * @param inTouchMode Whether we want to be in touch mode.
2631     * @return True if the touch mode changed and focus changed was changed as a result
2632     */
2633    private boolean ensureTouchModeLocally(boolean inTouchMode) {
2634        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2635                + "touch mode is " + mAttachInfo.mInTouchMode);
2636
2637        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2638
2639        mAttachInfo.mInTouchMode = inTouchMode;
2640        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2641
2642        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
2643    }
2644
2645    private boolean enterTouchMode() {
2646        if (mView != null) {
2647            if (mView.hasFocus()) {
2648                // note: not relying on mFocusedView here because this could
2649                // be when the window is first being added, and mFocused isn't
2650                // set yet.
2651                final View focused = mView.findFocus();
2652                if (focused != null && !focused.isFocusableInTouchMode()) {
2653
2654                    final ViewGroup ancestorToTakeFocus =
2655                            findAncestorToTakeFocusInTouchMode(focused);
2656                    if (ancestorToTakeFocus != null) {
2657                        // there is an ancestor that wants focus after its descendants that
2658                        // is focusable in touch mode.. give it focus
2659                        return ancestorToTakeFocus.requestFocus();
2660                    } else {
2661                        // nothing appropriate to have focus in touch mode, clear it out
2662                        mView.unFocus();
2663                        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2664                        mFocusedView = null;
2665                        return true;
2666                    }
2667                }
2668            }
2669        }
2670        return false;
2671    }
2672
2673
2674    /**
2675     * Find an ancestor of focused that wants focus after its descendants and is
2676     * focusable in touch mode.
2677     * @param focused The currently focused view.
2678     * @return An appropriate view, or null if no such view exists.
2679     */
2680    private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2681        ViewParent parent = focused.getParent();
2682        while (parent instanceof ViewGroup) {
2683            final ViewGroup vgParent = (ViewGroup) parent;
2684            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2685                    && vgParent.isFocusableInTouchMode()) {
2686                return vgParent;
2687            }
2688            if (vgParent.isRootNamespace()) {
2689                return null;
2690            } else {
2691                parent = vgParent.getParent();
2692            }
2693        }
2694        return null;
2695    }
2696
2697    private boolean leaveTouchMode() {
2698        if (mView != null) {
2699            if (mView.hasFocus()) {
2700                // i learned the hard way to not trust mFocusedView :)
2701                mFocusedView = mView.findFocus();
2702                if (!(mFocusedView instanceof ViewGroup)) {
2703                    // some view has focus, let it keep it
2704                    return false;
2705                } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2706                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2707                    // some view group has focus, and doesn't prefer its children
2708                    // over itself for focus, so let them keep it.
2709                    return false;
2710                }
2711            }
2712
2713            // find the best view to give focus to in this brave new non-touch-mode
2714            // world
2715            final View focused = focusSearch(null, View.FOCUS_DOWN);
2716            if (focused != null) {
2717                return focused.requestFocus(View.FOCUS_DOWN);
2718            }
2719        }
2720        return false;
2721    }
2722
2723    private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2724        if (ViewDebug.DEBUG_LATENCY) {
2725            mInputEventDeliverTimeNanos = System.nanoTime();
2726        }
2727
2728        final boolean isTouchEvent = event.isTouchEvent();
2729        if (mInputEventConsistencyVerifier != null) {
2730            if (isTouchEvent) {
2731                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
2732            } else {
2733                mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
2734            }
2735        }
2736
2737        // If there is no view, then the event will not be handled.
2738        if (mView == null || !mAdded) {
2739            finishMotionEvent(event, sendDone, false);
2740            return;
2741        }
2742
2743        // Translate the pointer event for compatibility, if needed.
2744        if (mTranslator != null) {
2745            mTranslator.translateEventInScreenToAppWindow(event);
2746        }
2747
2748        // Enter touch mode on down or scroll.
2749        final int action = event.getAction();
2750        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
2751            ensureTouchMode(true);
2752        }
2753
2754        // Offset the scroll position.
2755        if (mCurScrollY != 0) {
2756            event.offsetLocation(0, mCurScrollY);
2757        }
2758        if (MEASURE_LATENCY) {
2759            lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
2760        }
2761
2762        // Remember the touch position for possible drag-initiation.
2763        if (isTouchEvent) {
2764            mLastTouchPoint.x = event.getRawX();
2765            mLastTouchPoint.y = event.getRawY();
2766        }
2767
2768        // Dispatch touch to view hierarchy.
2769        boolean handled = mView.dispatchPointerEvent(event);
2770        if (MEASURE_LATENCY) {
2771            lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
2772        }
2773        if (handled) {
2774            finishMotionEvent(event, sendDone, true);
2775            return;
2776        }
2777
2778        // Pointer event was unhandled.
2779        finishMotionEvent(event, sendDone, false);
2780    }
2781
2782    private void finishMotionEvent(MotionEvent event, boolean sendDone, boolean handled) {
2783        event.recycle();
2784        if (sendDone) {
2785            finishInputEvent(event, handled);
2786        }
2787        //noinspection ConstantConditions
2788        if (LOCAL_LOGV || WATCH_POINTER) {
2789            if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2790                Log.i(TAG, "Done dispatching!");
2791            }
2792        }
2793    }
2794
2795    private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
2796        if (ViewDebug.DEBUG_LATENCY) {
2797            mInputEventDeliverTimeNanos = System.nanoTime();
2798        }
2799
2800        if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2801
2802        if (mInputEventConsistencyVerifier != null) {
2803            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
2804        }
2805
2806        // If there is no view, then the event will not be handled.
2807        if (mView == null || !mAdded) {
2808            finishMotionEvent(event, sendDone, false);
2809            return;
2810        }
2811
2812        // Deliver the trackball event to the view.
2813        if (mView.dispatchTrackballEvent(event)) {
2814            // If we reach this, we delivered a trackball event to mView and
2815            // mView consumed it. Because we will not translate the trackball
2816            // event into a key event, touch mode will not exit, so we exit
2817            // touch mode here.
2818            ensureTouchMode(false);
2819
2820            finishMotionEvent(event, sendDone, true);
2821            mLastTrackballTime = Integer.MIN_VALUE;
2822            return;
2823        }
2824
2825        // Translate the trackball event into DPAD keys and try to deliver those.
2826        final TrackballAxis x = mTrackballAxisX;
2827        final TrackballAxis y = mTrackballAxisY;
2828
2829        long curTime = SystemClock.uptimeMillis();
2830        if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
2831            // It has been too long since the last movement,
2832            // so restart at the beginning.
2833            x.reset(0);
2834            y.reset(0);
2835            mLastTrackballTime = curTime;
2836        }
2837
2838        final int action = event.getAction();
2839        final int metaState = event.getMetaState();
2840        switch (action) {
2841            case MotionEvent.ACTION_DOWN:
2842                x.reset(2);
2843                y.reset(2);
2844                deliverKeyEvent(new KeyEvent(curTime, curTime,
2845                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2846                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2847                        InputDevice.SOURCE_KEYBOARD), false);
2848                break;
2849            case MotionEvent.ACTION_UP:
2850                x.reset(2);
2851                y.reset(2);
2852                deliverKeyEvent(new KeyEvent(curTime, curTime,
2853                        KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2854                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2855                        InputDevice.SOURCE_KEYBOARD), false);
2856                break;
2857        }
2858
2859        if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2860                + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2861                + " move=" + event.getX()
2862                + " / Y=" + y.position + " step="
2863                + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2864                + " move=" + event.getY());
2865        final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2866        final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2867
2868        // Generate DPAD events based on the trackball movement.
2869        // We pick the axis that has moved the most as the direction of
2870        // the DPAD.  When we generate DPAD events for one axis, then the
2871        // other axis is reset -- we don't want to perform DPAD jumps due
2872        // to slight movements in the trackball when making major movements
2873        // along the other axis.
2874        int keycode = 0;
2875        int movement = 0;
2876        float accel = 1;
2877        if (xOff > yOff) {
2878            movement = x.generate((2/event.getXPrecision()));
2879            if (movement != 0) {
2880                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2881                        : KeyEvent.KEYCODE_DPAD_LEFT;
2882                accel = x.acceleration;
2883                y.reset(2);
2884            }
2885        } else if (yOff > 0) {
2886            movement = y.generate((2/event.getYPrecision()));
2887            if (movement != 0) {
2888                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2889                        : KeyEvent.KEYCODE_DPAD_UP;
2890                accel = y.acceleration;
2891                x.reset(2);
2892            }
2893        }
2894
2895        if (keycode != 0) {
2896            if (movement < 0) movement = -movement;
2897            int accelMovement = (int)(movement * accel);
2898            if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2899                    + " accelMovement=" + accelMovement
2900                    + " accel=" + accel);
2901            if (accelMovement > movement) {
2902                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2903                        + keycode);
2904                movement--;
2905                int repeatCount = accelMovement - movement;
2906                deliverKeyEvent(new KeyEvent(curTime, curTime,
2907                        KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2908                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2909                        InputDevice.SOURCE_KEYBOARD), false);
2910            }
2911            while (movement > 0) {
2912                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2913                        + keycode);
2914                movement--;
2915                curTime = SystemClock.uptimeMillis();
2916                deliverKeyEvent(new KeyEvent(curTime, curTime,
2917                        KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2918                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2919                        InputDevice.SOURCE_KEYBOARD), false);
2920                deliverKeyEvent(new KeyEvent(curTime, curTime,
2921                        KeyEvent.ACTION_UP, keycode, 0, metaState,
2922                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2923                        InputDevice.SOURCE_KEYBOARD), false);
2924                }
2925            mLastTrackballTime = curTime;
2926        }
2927
2928        // Unfortunately we can't tell whether the application consumed the keys, so
2929        // we always consider the trackball event handled.
2930        finishMotionEvent(event, sendDone, true);
2931    }
2932
2933    private void deliverGenericMotionEvent(MotionEvent event, boolean sendDone) {
2934        if (ViewDebug.DEBUG_LATENCY) {
2935            mInputEventDeliverTimeNanos = System.nanoTime();
2936        }
2937
2938        if (mInputEventConsistencyVerifier != null) {
2939            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
2940        }
2941
2942        final int source = event.getSource();
2943        final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
2944
2945        // If there is no view, then the event will not be handled.
2946        if (mView == null || !mAdded) {
2947            if (isJoystick) {
2948                updateJoystickDirection(event, false);
2949            }
2950            finishMotionEvent(event, sendDone, false);
2951            return;
2952        }
2953
2954        // Deliver the event to the view.
2955        if (mView.dispatchGenericMotionEvent(event)) {
2956            if (isJoystick) {
2957                updateJoystickDirection(event, false);
2958            }
2959            finishMotionEvent(event, sendDone, true);
2960            return;
2961        }
2962
2963        if (isJoystick) {
2964            // Translate the joystick event into DPAD keys and try to deliver those.
2965            updateJoystickDirection(event, true);
2966            finishMotionEvent(event, sendDone, true);
2967        } else {
2968            finishMotionEvent(event, sendDone, false);
2969        }
2970    }
2971
2972    private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
2973        final long time = event.getEventTime();
2974        final int metaState = event.getMetaState();
2975        final int deviceId = event.getDeviceId();
2976        final int source = event.getSource();
2977
2978        int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
2979        if (xDirection == 0) {
2980            xDirection = joystickAxisValueToDirection(event.getX());
2981        }
2982
2983        int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
2984        if (yDirection == 0) {
2985            yDirection = joystickAxisValueToDirection(event.getY());
2986        }
2987
2988        if (xDirection != mLastJoystickXDirection) {
2989            if (mLastJoystickXKeyCode != 0) {
2990                deliverKeyEvent(new KeyEvent(time, time,
2991                        KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
2992                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2993                mLastJoystickXKeyCode = 0;
2994            }
2995
2996            mLastJoystickXDirection = xDirection;
2997
2998            if (xDirection != 0 && synthesizeNewKeys) {
2999                mLastJoystickXKeyCode = xDirection > 0
3000                        ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3001                deliverKeyEvent(new KeyEvent(time, time,
3002                        KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3003                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
3004            }
3005        }
3006
3007        if (yDirection != mLastJoystickYDirection) {
3008            if (mLastJoystickYKeyCode != 0) {
3009                deliverKeyEvent(new KeyEvent(time, time,
3010                        KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3011                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
3012                mLastJoystickYKeyCode = 0;
3013            }
3014
3015            mLastJoystickYDirection = yDirection;
3016
3017            if (yDirection != 0 && synthesizeNewKeys) {
3018                mLastJoystickYKeyCode = yDirection > 0
3019                        ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3020                deliverKeyEvent(new KeyEvent(time, time,
3021                        KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3022                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
3023            }
3024        }
3025    }
3026
3027    private static int joystickAxisValueToDirection(float value) {
3028        if (value >= 0.5f) {
3029            return 1;
3030        } else if (value <= -0.5f) {
3031            return -1;
3032        } else {
3033            return 0;
3034        }
3035    }
3036
3037    /**
3038     * Returns true if the key is used for keyboard navigation.
3039     * @param keyEvent The key event.
3040     * @return True if the key is used for keyboard navigation.
3041     */
3042    private static boolean isNavigationKey(KeyEvent keyEvent) {
3043        switch (keyEvent.getKeyCode()) {
3044        case KeyEvent.KEYCODE_DPAD_LEFT:
3045        case KeyEvent.KEYCODE_DPAD_RIGHT:
3046        case KeyEvent.KEYCODE_DPAD_UP:
3047        case KeyEvent.KEYCODE_DPAD_DOWN:
3048        case KeyEvent.KEYCODE_DPAD_CENTER:
3049        case KeyEvent.KEYCODE_PAGE_UP:
3050        case KeyEvent.KEYCODE_PAGE_DOWN:
3051        case KeyEvent.KEYCODE_MOVE_HOME:
3052        case KeyEvent.KEYCODE_MOVE_END:
3053        case KeyEvent.KEYCODE_TAB:
3054        case KeyEvent.KEYCODE_SPACE:
3055        case KeyEvent.KEYCODE_ENTER:
3056            return true;
3057        }
3058        return false;
3059    }
3060
3061    /**
3062     * Returns true if the key is used for typing.
3063     * @param keyEvent The key event.
3064     * @return True if the key is used for typing.
3065     */
3066    private static boolean isTypingKey(KeyEvent keyEvent) {
3067        return keyEvent.getUnicodeChar() > 0;
3068    }
3069
3070    /**
3071     * See if the key event means we should leave touch mode (and leave touch mode if so).
3072     * @param event The key event.
3073     * @return Whether this key event should be consumed (meaning the act of
3074     *   leaving touch mode alone is considered the event).
3075     */
3076    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3077        // Only relevant in touch mode.
3078        if (!mAttachInfo.mInTouchMode) {
3079            return false;
3080        }
3081
3082        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3083        final int action = event.getAction();
3084        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3085            return false;
3086        }
3087
3088        // Don't leave touch mode if the IME told us not to.
3089        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3090            return false;
3091        }
3092
3093        // If the key can be used for keyboard navigation then leave touch mode
3094        // and select a focused view if needed (in ensureTouchMode).
3095        // When a new focused view is selected, we consume the navigation key because
3096        // navigation doesn't make much sense unless a view already has focus so
3097        // the key's purpose is to set focus.
3098        if (isNavigationKey(event)) {
3099            return ensureTouchMode(false);
3100        }
3101
3102        // If the key can be used for typing then leave touch mode
3103        // and select a focused view if needed (in ensureTouchMode).
3104        // Always allow the view to process the typing key.
3105        if (isTypingKey(event)) {
3106            ensureTouchMode(false);
3107            return false;
3108        }
3109
3110        return false;
3111    }
3112
3113    int enqueuePendingEvent(Object event, boolean sendDone) {
3114        int seq = mPendingEventSeq+1;
3115        if (seq < 0) seq = 0;
3116        mPendingEventSeq = seq;
3117        mPendingEvents.put(seq, event);
3118        return sendDone ? seq : -seq;
3119    }
3120
3121    Object retrievePendingEvent(int seq) {
3122        if (seq < 0) seq = -seq;
3123        Object event = mPendingEvents.get(seq);
3124        if (event != null) {
3125            mPendingEvents.remove(seq);
3126        }
3127        return event;
3128    }
3129
3130    private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
3131        if (ViewDebug.DEBUG_LATENCY) {
3132            mInputEventDeliverTimeNanos = System.nanoTime();
3133        }
3134
3135        if (mInputEventConsistencyVerifier != null) {
3136            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3137        }
3138
3139        // If there is no view, then the event will not be handled.
3140        if (mView == null || !mAdded) {
3141            finishKeyEvent(event, sendDone, false);
3142            return;
3143        }
3144
3145        if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3146
3147        // Perform predispatching before the IME.
3148        if (mView.dispatchKeyEventPreIme(event)) {
3149            finishKeyEvent(event, sendDone, true);
3150            return;
3151        }
3152
3153        // Dispatch to the IME before propagating down the view hierarchy.
3154        // The IME will eventually call back into handleFinishedEvent.
3155        if (mLastWasImTarget) {
3156            InputMethodManager imm = InputMethodManager.peekInstance();
3157            if (imm != null) {
3158                int seq = enqueuePendingEvent(event, sendDone);
3159                if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3160                        + seq + " event=" + event);
3161                imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
3162                return;
3163            }
3164        }
3165
3166        // Not dispatching to IME, continue with post IME actions.
3167        deliverKeyEventPostIme(event, sendDone);
3168    }
3169
3170    private void handleFinishedEvent(int seq, boolean handled) {
3171        final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
3172        if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
3173                + " handled=" + handled + " event=" + event);
3174        if (event != null) {
3175            final boolean sendDone = seq >= 0;
3176            if (handled) {
3177                finishKeyEvent(event, sendDone, true);
3178            } else {
3179                deliverKeyEventPostIme(event, sendDone);
3180            }
3181        }
3182    }
3183
3184    private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
3185        if (ViewDebug.DEBUG_LATENCY) {
3186            mInputEventDeliverPostImeTimeNanos = System.nanoTime();
3187        }
3188
3189        // If the view went away, then the event will not be handled.
3190        if (mView == null || !mAdded) {
3191            finishKeyEvent(event, sendDone, false);
3192            return;
3193        }
3194
3195        // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3196        if (checkForLeavingTouchModeAndConsume(event)) {
3197            finishKeyEvent(event, sendDone, true);
3198            return;
3199        }
3200
3201        // Make sure the fallback event policy sees all keys that will be delivered to the
3202        // view hierarchy.
3203        mFallbackEventHandler.preDispatchKeyEvent(event);
3204
3205        // Deliver the key to the view hierarchy.
3206        if (mView.dispatchKeyEvent(event)) {
3207            finishKeyEvent(event, sendDone, true);
3208            return;
3209        }
3210
3211        // If the Control modifier is held, try to interpret the key as a shortcut.
3212        if (event.getAction() == KeyEvent.ACTION_UP
3213                && event.isCtrlPressed()
3214                && !KeyEvent.isModifierKey(event.getKeyCode())) {
3215            if (mView.dispatchKeyShortcutEvent(event)) {
3216                finishKeyEvent(event, sendDone, true);
3217                return;
3218            }
3219        }
3220
3221        // Apply the fallback event policy.
3222        if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3223            finishKeyEvent(event, sendDone, true);
3224            return;
3225        }
3226
3227        // Handle automatic focus changes.
3228        if (event.getAction() == KeyEvent.ACTION_DOWN) {
3229            int direction = 0;
3230            switch (event.getKeyCode()) {
3231            case KeyEvent.KEYCODE_DPAD_LEFT:
3232                if (event.hasNoModifiers()) {
3233                    direction = View.FOCUS_LEFT;
3234                }
3235                break;
3236            case KeyEvent.KEYCODE_DPAD_RIGHT:
3237                if (event.hasNoModifiers()) {
3238                    direction = View.FOCUS_RIGHT;
3239                }
3240                break;
3241            case KeyEvent.KEYCODE_DPAD_UP:
3242                if (event.hasNoModifiers()) {
3243                    direction = View.FOCUS_UP;
3244                }
3245                break;
3246            case KeyEvent.KEYCODE_DPAD_DOWN:
3247                if (event.hasNoModifiers()) {
3248                    direction = View.FOCUS_DOWN;
3249                }
3250                break;
3251            case KeyEvent.KEYCODE_TAB:
3252                if (event.hasNoModifiers()) {
3253                    direction = View.FOCUS_FORWARD;
3254                } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3255                    direction = View.FOCUS_BACKWARD;
3256                }
3257                break;
3258            }
3259
3260            if (direction != 0) {
3261                View focused = mView != null ? mView.findFocus() : null;
3262                if (focused != null) {
3263                    View v = focused.focusSearch(direction);
3264                    if (v != null && v != focused) {
3265                        // do the math the get the interesting rect
3266                        // of previous focused into the coord system of
3267                        // newly focused view
3268                        focused.getFocusedRect(mTempRect);
3269                        if (mView instanceof ViewGroup) {
3270                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3271                                    focused, mTempRect);
3272                            ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3273                                    v, mTempRect);
3274                        }
3275                        if (v.requestFocus(direction, mTempRect)) {
3276                            playSoundEffect(
3277                                    SoundEffectConstants.getContantForFocusDirection(direction));
3278                            finishKeyEvent(event, sendDone, true);
3279                            return;
3280                        }
3281                    }
3282
3283                    // Give the focused view a last chance to handle the dpad key.
3284                    if (mView.dispatchUnhandledMove(focused, direction)) {
3285                        finishKeyEvent(event, sendDone, true);
3286                        return;
3287                    }
3288                }
3289            }
3290        }
3291
3292        // Key was unhandled.
3293        finishKeyEvent(event, sendDone, false);
3294    }
3295
3296    private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
3297        if (sendDone) {
3298            finishInputEvent(event, handled);
3299        }
3300    }
3301
3302    /* drag/drop */
3303    void setLocalDragState(Object obj) {
3304        mLocalDragState = obj;
3305    }
3306
3307    private void handleDragEvent(DragEvent event) {
3308        // From the root, only drag start/end/location are dispatched.  entered/exited
3309        // are determined and dispatched by the viewgroup hierarchy, who then report
3310        // that back here for ultimate reporting back to the framework.
3311        if (mView != null && mAdded) {
3312            final int what = event.mAction;
3313
3314            if (what == DragEvent.ACTION_DRAG_EXITED) {
3315                // A direct EXITED event means that the window manager knows we've just crossed
3316                // a window boundary, so the current drag target within this one must have
3317                // just been exited.  Send it the usual notifications and then we're done
3318                // for now.
3319                mView.dispatchDragEvent(event);
3320            } else {
3321                // Cache the drag description when the operation starts, then fill it in
3322                // on subsequent calls as a convenience
3323                if (what == DragEvent.ACTION_DRAG_STARTED) {
3324                    mCurrentDragView = null;    // Start the current-recipient tracking
3325                    mDragDescription = event.mClipDescription;
3326                } else {
3327                    event.mClipDescription = mDragDescription;
3328                }
3329
3330                // For events with a [screen] location, translate into window coordinates
3331                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3332                    mDragPoint.set(event.mX, event.mY);
3333                    if (mTranslator != null) {
3334                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3335                    }
3336
3337                    if (mCurScrollY != 0) {
3338                        mDragPoint.offset(0, mCurScrollY);
3339                    }
3340
3341                    event.mX = mDragPoint.x;
3342                    event.mY = mDragPoint.y;
3343                }
3344
3345                // Remember who the current drag target is pre-dispatch
3346                final View prevDragView = mCurrentDragView;
3347
3348                // Now dispatch the drag/drop event
3349                boolean result = mView.dispatchDragEvent(event);
3350
3351                // If we changed apparent drag target, tell the OS about it
3352                if (prevDragView != mCurrentDragView) {
3353                    try {
3354                        if (prevDragView != null) {
3355                            sWindowSession.dragRecipientExited(mWindow);
3356                        }
3357                        if (mCurrentDragView != null) {
3358                            sWindowSession.dragRecipientEntered(mWindow);
3359                        }
3360                    } catch (RemoteException e) {
3361                        Slog.e(TAG, "Unable to note drag target change");
3362                    }
3363                }
3364
3365                // Report the drop result when we're done
3366                if (what == DragEvent.ACTION_DROP) {
3367                    mDragDescription = null;
3368                    try {
3369                        Log.i(TAG, "Reporting drop result: " + result);
3370                        sWindowSession.reportDropResult(mWindow, result);
3371                    } catch (RemoteException e) {
3372                        Log.e(TAG, "Unable to report drop result");
3373                    }
3374                }
3375
3376                // When the drag operation ends, release any local state object
3377                // that may have been in use
3378                if (what == DragEvent.ACTION_DRAG_ENDED) {
3379                    setLocalDragState(null);
3380                }
3381            }
3382        }
3383        event.recycle();
3384    }
3385
3386    public void handleDispatchSystemUiVisibilityChanged(int visibility) {
3387        if (mView == null) return;
3388        if (mAttachInfo != null) {
3389            mAttachInfo.mSystemUiVisibility = visibility;
3390        }
3391        mView.dispatchSystemUiVisibilityChanged(visibility);
3392    }
3393
3394    public void getLastTouchPoint(Point outLocation) {
3395        outLocation.x = (int) mLastTouchPoint.x;
3396        outLocation.y = (int) mLastTouchPoint.y;
3397    }
3398
3399    public void setDragFocus(View newDragTarget) {
3400        if (mCurrentDragView != newDragTarget) {
3401            mCurrentDragView = newDragTarget;
3402        }
3403    }
3404
3405    private AudioManager getAudioManager() {
3406        if (mView == null) {
3407            throw new IllegalStateException("getAudioManager called when there is no mView");
3408        }
3409        if (mAudioManager == null) {
3410            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3411        }
3412        return mAudioManager;
3413    }
3414
3415    public AccessibilityInteractionController getAccessibilityInteractionController() {
3416        if (mView == null) {
3417            throw new IllegalStateException("getAccessibilityInteractionController"
3418                    + " called when there is no mView");
3419        }
3420        if (mAccessibilityInteractionContrtoller == null) {
3421            mAccessibilityInteractionContrtoller = new AccessibilityInteractionController();
3422        }
3423        return mAccessibilityInteractionContrtoller;
3424    }
3425
3426    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3427            boolean insetsPending) throws RemoteException {
3428
3429        float appScale = mAttachInfo.mApplicationScale;
3430        boolean restore = false;
3431        if (params != null && mTranslator != null) {
3432            restore = true;
3433            params.backup();
3434            mTranslator.translateWindowLayout(params);
3435        }
3436        if (params != null) {
3437            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
3438        }
3439        mPendingConfiguration.seq = 0;
3440        //Log.d(TAG, ">>>>>> CALLING relayout");
3441        int relayoutResult = sWindowSession.relayout(
3442                mWindow, params,
3443                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3444                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
3445                viewVisibility, insetsPending, mWinFrame,
3446                mPendingContentInsets, mPendingVisibleInsets,
3447                mPendingConfiguration, mSurface);
3448        //Log.d(TAG, "<<<<<< BACK FROM relayout");
3449        if (restore) {
3450            params.restore();
3451        }
3452
3453        if (mTranslator != null) {
3454            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3455            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3456            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
3457        }
3458        return relayoutResult;
3459    }
3460
3461    /**
3462     * {@inheritDoc}
3463     */
3464    public void playSoundEffect(int effectId) {
3465        checkThread();
3466
3467        try {
3468            final AudioManager audioManager = getAudioManager();
3469
3470            switch (effectId) {
3471                case SoundEffectConstants.CLICK:
3472                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3473                    return;
3474                case SoundEffectConstants.NAVIGATION_DOWN:
3475                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3476                    return;
3477                case SoundEffectConstants.NAVIGATION_LEFT:
3478                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3479                    return;
3480                case SoundEffectConstants.NAVIGATION_RIGHT:
3481                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3482                    return;
3483                case SoundEffectConstants.NAVIGATION_UP:
3484                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3485                    return;
3486                default:
3487                    throw new IllegalArgumentException("unknown effect id " + effectId +
3488                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
3489            }
3490        } catch (IllegalStateException e) {
3491            // Exception thrown by getAudioManager() when mView is null
3492            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3493            e.printStackTrace();
3494        }
3495    }
3496
3497    /**
3498     * {@inheritDoc}
3499     */
3500    public boolean performHapticFeedback(int effectId, boolean always) {
3501        try {
3502            return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3503        } catch (RemoteException e) {
3504            return false;
3505        }
3506    }
3507
3508    /**
3509     * {@inheritDoc}
3510     */
3511    public View focusSearch(View focused, int direction) {
3512        checkThread();
3513        if (!(mView instanceof ViewGroup)) {
3514            return null;
3515        }
3516        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3517    }
3518
3519    public void debug() {
3520        mView.debug();
3521    }
3522
3523    public void dumpGfxInfo(PrintWriter pw, int[] info) {
3524        if (mView != null) {
3525            getGfxInfo(mView, info);
3526        } else {
3527            info[0] = info[1] = 0;
3528        }
3529    }
3530
3531    private void getGfxInfo(View view, int[] info) {
3532        DisplayList displayList = view.mDisplayList;
3533        info[0]++;
3534        if (displayList != null) {
3535            info[1] += displayList.getSize();
3536        }
3537
3538        if (view instanceof ViewGroup) {
3539            ViewGroup group = (ViewGroup) view;
3540
3541            int count = group.getChildCount();
3542            for (int i = 0; i < count; i++) {
3543                getGfxInfo(group.getChildAt(i), info);
3544            }
3545        }
3546    }
3547
3548    public void die(boolean immediate) {
3549        if (immediate) {
3550            doDie();
3551        } else {
3552            sendEmptyMessage(DIE);
3553        }
3554    }
3555
3556    void doDie() {
3557        checkThread();
3558        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
3559        synchronized (this) {
3560            if (mAdded && !mFirst) {
3561                destroyHardwareRenderer();
3562
3563                int viewVisibility = mView.getVisibility();
3564                boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3565                if (mWindowAttributesChanged || viewVisibilityChanged) {
3566                    // If layout params have been changed, first give them
3567                    // to the window manager to make sure it has the correct
3568                    // animation info.
3569                    try {
3570                        if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3571                                & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
3572                            sWindowSession.finishDrawing(mWindow);
3573                        }
3574                    } catch (RemoteException e) {
3575                    }
3576                }
3577
3578                mSurface.release();
3579            }
3580            if (mAdded) {
3581                mAdded = false;
3582                dispatchDetachedFromWindow();
3583            }
3584        }
3585    }
3586
3587    public void requestUpdateConfiguration(Configuration config) {
3588        Message msg = obtainMessage(UPDATE_CONFIGURATION, config);
3589        sendMessage(msg);
3590    }
3591
3592    private void destroyHardwareRenderer() {
3593        if (mAttachInfo.mHardwareRenderer != null) {
3594            mAttachInfo.mHardwareRenderer.destroy(true);
3595            mAttachInfo.mHardwareRenderer = null;
3596            mAttachInfo.mHardwareAccelerated = false;
3597        }
3598    }
3599
3600    public void dispatchFinishedEvent(int seq, boolean handled) {
3601        Message msg = obtainMessage(FINISHED_EVENT);
3602        msg.arg1 = seq;
3603        msg.arg2 = handled ? 1 : 0;
3604        sendMessage(msg);
3605    }
3606
3607    public void dispatchResized(int w, int h, Rect coveredInsets,
3608            Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
3609        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3610                + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3611                + " visibleInsets=" + visibleInsets.toShortString()
3612                + " reportDraw=" + reportDraw);
3613        Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
3614        if (mTranslator != null) {
3615            mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3616            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3617            w *= mTranslator.applicationInvertedScale;
3618            h *= mTranslator.applicationInvertedScale;
3619        }
3620        msg.arg1 = w;
3621        msg.arg2 = h;
3622        ResizedInfo ri = new ResizedInfo();
3623        ri.coveredInsets = new Rect(coveredInsets);
3624        ri.visibleInsets = new Rect(visibleInsets);
3625        ri.newConfig = newConfig;
3626        msg.obj = ri;
3627        sendMessage(msg);
3628    }
3629
3630    private long mInputEventReceiveTimeNanos;
3631    private long mInputEventDeliverTimeNanos;
3632    private long mInputEventDeliverPostImeTimeNanos;
3633    private InputQueue.FinishedCallback mFinishedCallback;
3634
3635    private final InputHandler mInputHandler = new InputHandler() {
3636        public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
3637            startInputEvent(finishedCallback);
3638            dispatchKey(event, true);
3639        }
3640
3641        public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
3642            startInputEvent(finishedCallback);
3643            dispatchMotion(event, true);
3644        }
3645    };
3646
3647    public void dispatchKey(KeyEvent event) {
3648        dispatchKey(event, false);
3649    }
3650
3651    private void dispatchKey(KeyEvent event, boolean sendDone) {
3652        //noinspection ConstantConditions
3653        if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3654            if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
3655                if (DBG) Log.d("keydisp", "===================================================");
3656                if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3657
3658                debug();
3659
3660                if (DBG) Log.d("keydisp", "===================================================");
3661            }
3662        }
3663
3664        Message msg = obtainMessage(DISPATCH_KEY);
3665        msg.obj = event;
3666        msg.arg1 = sendDone ? 1 : 0;
3667
3668        if (LOCAL_LOGV) Log.v(
3669            TAG, "sending key " + event + " to " + mView);
3670
3671        sendMessageAtTime(msg, event.getEventTime());
3672    }
3673
3674    private void dispatchMotion(MotionEvent event, boolean sendDone) {
3675        int source = event.getSource();
3676        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3677            dispatchPointer(event, sendDone);
3678        } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3679            dispatchTrackball(event, sendDone);
3680        } else {
3681            dispatchGenericMotion(event, sendDone);
3682        }
3683    }
3684
3685    private void dispatchPointer(MotionEvent event, boolean sendDone) {
3686        Message msg = obtainMessage(DISPATCH_POINTER);
3687        msg.obj = event;
3688        msg.arg1 = sendDone ? 1 : 0;
3689        sendMessageAtTime(msg, event.getEventTime());
3690    }
3691
3692    private void dispatchTrackball(MotionEvent event, boolean sendDone) {
3693        Message msg = obtainMessage(DISPATCH_TRACKBALL);
3694        msg.obj = event;
3695        msg.arg1 = sendDone ? 1 : 0;
3696        sendMessageAtTime(msg, event.getEventTime());
3697    }
3698
3699    private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
3700        Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
3701        msg.obj = event;
3702        msg.arg1 = sendDone ? 1 : 0;
3703        sendMessageAtTime(msg, event.getEventTime());
3704    }
3705
3706    public void dispatchAppVisibility(boolean visible) {
3707        Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3708        msg.arg1 = visible ? 1 : 0;
3709        sendMessage(msg);
3710    }
3711
3712    public void dispatchGetNewSurface() {
3713        Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3714        sendMessage(msg);
3715    }
3716
3717    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3718        Message msg = Message.obtain();
3719        msg.what = WINDOW_FOCUS_CHANGED;
3720        msg.arg1 = hasFocus ? 1 : 0;
3721        msg.arg2 = inTouchMode ? 1 : 0;
3722        sendMessage(msg);
3723    }
3724
3725    public void dispatchCloseSystemDialogs(String reason) {
3726        Message msg = Message.obtain();
3727        msg.what = CLOSE_SYSTEM_DIALOGS;
3728        msg.obj = reason;
3729        sendMessage(msg);
3730    }
3731
3732    public void dispatchDragEvent(DragEvent event) {
3733        final int what;
3734        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3735            what = DISPATCH_DRAG_LOCATION_EVENT;
3736            removeMessages(what);
3737        } else {
3738            what = DISPATCH_DRAG_EVENT;
3739        }
3740        Message msg = obtainMessage(what, event);
3741        sendMessage(msg);
3742    }
3743
3744    public void dispatchSystemUiVisibilityChanged(int visibility) {
3745        sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3746    }
3747
3748    /**
3749     * The window is getting focus so if there is anything focused/selected
3750     * send an {@link AccessibilityEvent} to announce that.
3751     */
3752    private void sendAccessibilityEvents() {
3753        if (!mAccessibilityManager.isEnabled()) {
3754            return;
3755        }
3756        mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3757        View focusedView = mView.findFocus();
3758        if (focusedView != null && focusedView != mView) {
3759            focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3760        }
3761    }
3762
3763    /**
3764     * Post a callback to send a
3765     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
3766     * This event is send at most once every
3767     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
3768     */
3769    private void postSendWindowContentChangedCallback() {
3770        if (mSendWindowContentChangedAccessibilityEvent == null) {
3771            mSendWindowContentChangedAccessibilityEvent =
3772                new SendWindowContentChangedAccessibilityEvent();
3773        }
3774        if (!mSendWindowContentChangedAccessibilityEvent.mIsPending) {
3775            mSendWindowContentChangedAccessibilityEvent.mIsPending = true;
3776            postDelayed(mSendWindowContentChangedAccessibilityEvent,
3777                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
3778        }
3779    }
3780
3781    /**
3782     * Remove a posted callback to send a
3783     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
3784     */
3785    private void removeSendWindowContentChangedCallback() {
3786        if (mSendWindowContentChangedAccessibilityEvent != null) {
3787            removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
3788        }
3789    }
3790
3791    public boolean showContextMenuForChild(View originalView) {
3792        return false;
3793    }
3794
3795    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3796        return null;
3797    }
3798
3799    public void createContextMenu(ContextMenu menu) {
3800    }
3801
3802    public void childDrawableStateChanged(View child) {
3803    }
3804
3805    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
3806        if (mView == null) {
3807            return false;
3808        }
3809        mAccessibilityManager.sendAccessibilityEvent(event);
3810        return true;
3811    }
3812
3813    void checkThread() {
3814        if (mThread != Thread.currentThread()) {
3815            throw new CalledFromWrongThreadException(
3816                    "Only the original thread that created a view hierarchy can touch its views.");
3817        }
3818    }
3819
3820    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3821        // ViewAncestor never intercepts touch event, so this can be a no-op
3822    }
3823
3824    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3825            boolean immediate) {
3826        return scrollToRectOrFocus(rectangle, immediate);
3827    }
3828
3829    class TakenSurfaceHolder extends BaseSurfaceHolder {
3830        @Override
3831        public boolean onAllowLockCanvas() {
3832            return mDrawingAllowed;
3833        }
3834
3835        @Override
3836        public void onRelayoutContainer() {
3837            // Not currently interesting -- from changing between fixed and layout size.
3838        }
3839
3840        public void setFormat(int format) {
3841            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3842        }
3843
3844        public void setType(int type) {
3845            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3846        }
3847
3848        @Override
3849        public void onUpdateSurface() {
3850            // We take care of format and type changes on our own.
3851            throw new IllegalStateException("Shouldn't be here");
3852        }
3853
3854        public boolean isCreating() {
3855            return mIsCreating;
3856        }
3857
3858        @Override
3859        public void setFixedSize(int width, int height) {
3860            throw new UnsupportedOperationException(
3861                    "Currently only support sizing from layout");
3862        }
3863
3864        public void setKeepScreenOn(boolean screenOn) {
3865            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3866        }
3867    }
3868
3869    static class InputMethodCallback extends IInputMethodCallback.Stub {
3870        private WeakReference<ViewRootImpl> mViewAncestor;
3871
3872        public InputMethodCallback(ViewRootImpl viewAncestor) {
3873            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
3874        }
3875
3876        public void finishedEvent(int seq, boolean handled) {
3877            final ViewRootImpl viewAncestor = mViewAncestor.get();
3878            if (viewAncestor != null) {
3879                viewAncestor.dispatchFinishedEvent(seq, handled);
3880            }
3881        }
3882
3883        public void sessionCreated(IInputMethodSession session) {
3884            // Stub -- not for use in the client.
3885        }
3886    }
3887
3888    static class W extends IWindow.Stub {
3889        private final WeakReference<ViewRootImpl> mViewAncestor;
3890
3891        W(ViewRootImpl viewAncestor) {
3892            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
3893        }
3894
3895        public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3896                boolean reportDraw, Configuration newConfig) {
3897            final ViewRootImpl viewAncestor = mViewAncestor.get();
3898            if (viewAncestor != null) {
3899                viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw,
3900                        newConfig);
3901            }
3902        }
3903
3904        public void dispatchAppVisibility(boolean visible) {
3905            final ViewRootImpl viewAncestor = mViewAncestor.get();
3906            if (viewAncestor != null) {
3907                viewAncestor.dispatchAppVisibility(visible);
3908            }
3909        }
3910
3911        public void dispatchGetNewSurface() {
3912            final ViewRootImpl viewAncestor = mViewAncestor.get();
3913            if (viewAncestor != null) {
3914                viewAncestor.dispatchGetNewSurface();
3915            }
3916        }
3917
3918        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3919            final ViewRootImpl viewAncestor = mViewAncestor.get();
3920            if (viewAncestor != null) {
3921                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
3922            }
3923        }
3924
3925        private static int checkCallingPermission(String permission) {
3926            try {
3927                return ActivityManagerNative.getDefault().checkPermission(
3928                        permission, Binder.getCallingPid(), Binder.getCallingUid());
3929            } catch (RemoteException e) {
3930                return PackageManager.PERMISSION_DENIED;
3931            }
3932        }
3933
3934        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3935            final ViewRootImpl viewAncestor = mViewAncestor.get();
3936            if (viewAncestor != null) {
3937                final View view = viewAncestor.mView;
3938                if (view != null) {
3939                    if (checkCallingPermission(Manifest.permission.DUMP) !=
3940                            PackageManager.PERMISSION_GRANTED) {
3941                        throw new SecurityException("Insufficient permissions to invoke"
3942                                + " executeCommand() from pid=" + Binder.getCallingPid()
3943                                + ", uid=" + Binder.getCallingUid());
3944                    }
3945
3946                    OutputStream clientStream = null;
3947                    try {
3948                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3949                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3950                    } catch (IOException e) {
3951                        e.printStackTrace();
3952                    } finally {
3953                        if (clientStream != null) {
3954                            try {
3955                                clientStream.close();
3956                            } catch (IOException e) {
3957                                e.printStackTrace();
3958                            }
3959                        }
3960                    }
3961                }
3962            }
3963        }
3964
3965        public void closeSystemDialogs(String reason) {
3966            final ViewRootImpl viewAncestor = mViewAncestor.get();
3967            if (viewAncestor != null) {
3968                viewAncestor.dispatchCloseSystemDialogs(reason);
3969            }
3970        }
3971
3972        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3973                boolean sync) {
3974            if (sync) {
3975                try {
3976                    sWindowSession.wallpaperOffsetsComplete(asBinder());
3977                } catch (RemoteException e) {
3978                }
3979            }
3980        }
3981
3982        public void dispatchWallpaperCommand(String action, int x, int y,
3983                int z, Bundle extras, boolean sync) {
3984            if (sync) {
3985                try {
3986                    sWindowSession.wallpaperCommandComplete(asBinder(), null);
3987                } catch (RemoteException e) {
3988                }
3989            }
3990        }
3991
3992        /* Drag/drop */
3993        public void dispatchDragEvent(DragEvent event) {
3994            final ViewRootImpl viewAncestor = mViewAncestor.get();
3995            if (viewAncestor != null) {
3996                viewAncestor.dispatchDragEvent(event);
3997            }
3998        }
3999
4000        public void dispatchSystemUiVisibilityChanged(int visibility) {
4001            final ViewRootImpl viewAncestor = mViewAncestor.get();
4002            if (viewAncestor != null) {
4003                viewAncestor.dispatchSystemUiVisibilityChanged(visibility);
4004            }
4005        }
4006    }
4007
4008    /**
4009     * Maintains state information for a single trackball axis, generating
4010     * discrete (DPAD) movements based on raw trackball motion.
4011     */
4012    static final class TrackballAxis {
4013        /**
4014         * The maximum amount of acceleration we will apply.
4015         */
4016        static final float MAX_ACCELERATION = 20;
4017
4018        /**
4019         * The maximum amount of time (in milliseconds) between events in order
4020         * for us to consider the user to be doing fast trackball movements,
4021         * and thus apply an acceleration.
4022         */
4023        static final long FAST_MOVE_TIME = 150;
4024
4025        /**
4026         * Scaling factor to the time (in milliseconds) between events to how
4027         * much to multiple/divide the current acceleration.  When movement
4028         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4029         * FAST_MOVE_TIME it divides it.
4030         */
4031        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4032
4033        float position;
4034        float absPosition;
4035        float acceleration = 1;
4036        long lastMoveTime = 0;
4037        int step;
4038        int dir;
4039        int nonAccelMovement;
4040
4041        void reset(int _step) {
4042            position = 0;
4043            acceleration = 1;
4044            lastMoveTime = 0;
4045            step = _step;
4046            dir = 0;
4047        }
4048
4049        /**
4050         * Add trackball movement into the state.  If the direction of movement
4051         * has been reversed, the state is reset before adding the
4052         * movement (so that you don't have to compensate for any previously
4053         * collected movement before see the result of the movement in the
4054         * new direction).
4055         *
4056         * @return Returns the absolute value of the amount of movement
4057         * collected so far.
4058         */
4059        float collect(float off, long time, String axis) {
4060            long normTime;
4061            if (off > 0) {
4062                normTime = (long)(off * FAST_MOVE_TIME);
4063                if (dir < 0) {
4064                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4065                    position = 0;
4066                    step = 0;
4067                    acceleration = 1;
4068                    lastMoveTime = 0;
4069                }
4070                dir = 1;
4071            } else if (off < 0) {
4072                normTime = (long)((-off) * FAST_MOVE_TIME);
4073                if (dir > 0) {
4074                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4075                    position = 0;
4076                    step = 0;
4077                    acceleration = 1;
4078                    lastMoveTime = 0;
4079                }
4080                dir = -1;
4081            } else {
4082                normTime = 0;
4083            }
4084
4085            // The number of milliseconds between each movement that is
4086            // considered "normal" and will not result in any acceleration
4087            // or deceleration, scaled by the offset we have here.
4088            if (normTime > 0) {
4089                long delta = time - lastMoveTime;
4090                lastMoveTime = time;
4091                float acc = acceleration;
4092                if (delta < normTime) {
4093                    // The user is scrolling rapidly, so increase acceleration.
4094                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4095                    if (scale > 1) acc *= scale;
4096                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4097                            + off + " normTime=" + normTime + " delta=" + delta
4098                            + " scale=" + scale + " acc=" + acc);
4099                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4100                } else {
4101                    // The user is scrolling slowly, so decrease acceleration.
4102                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4103                    if (scale > 1) acc /= scale;
4104                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4105                            + off + " normTime=" + normTime + " delta=" + delta
4106                            + " scale=" + scale + " acc=" + acc);
4107                    acceleration = acc > 1 ? acc : 1;
4108                }
4109            }
4110            position += off;
4111            return (absPosition = Math.abs(position));
4112        }
4113
4114        /**
4115         * Generate the number of discrete movement events appropriate for
4116         * the currently collected trackball movement.
4117         *
4118         * @param precision The minimum movement required to generate the
4119         * first discrete movement.
4120         *
4121         * @return Returns the number of discrete movements, either positive
4122         * or negative, or 0 if there is not enough trackball movement yet
4123         * for a discrete movement.
4124         */
4125        int generate(float precision) {
4126            int movement = 0;
4127            nonAccelMovement = 0;
4128            do {
4129                final int dir = position >= 0 ? 1 : -1;
4130                switch (step) {
4131                    // If we are going to execute the first step, then we want
4132                    // to do this as soon as possible instead of waiting for
4133                    // a full movement, in order to make things look responsive.
4134                    case 0:
4135                        if (absPosition < precision) {
4136                            return movement;
4137                        }
4138                        movement += dir;
4139                        nonAccelMovement += dir;
4140                        step = 1;
4141                        break;
4142                    // If we have generated the first movement, then we need
4143                    // to wait for the second complete trackball motion before
4144                    // generating the second discrete movement.
4145                    case 1:
4146                        if (absPosition < 2) {
4147                            return movement;
4148                        }
4149                        movement += dir;
4150                        nonAccelMovement += dir;
4151                        position += dir > 0 ? -2 : 2;
4152                        absPosition = Math.abs(position);
4153                        step = 2;
4154                        break;
4155                    // After the first two, we generate discrete movements
4156                    // consistently with the trackball, applying an acceleration
4157                    // if the trackball is moving quickly.  This is a simple
4158                    // acceleration on top of what we already compute based
4159                    // on how quickly the wheel is being turned, to apply
4160                    // a longer increasing acceleration to continuous movement
4161                    // in one direction.
4162                    default:
4163                        if (absPosition < 1) {
4164                            return movement;
4165                        }
4166                        movement += dir;
4167                        position += dir >= 0 ? -1 : 1;
4168                        absPosition = Math.abs(position);
4169                        float acc = acceleration;
4170                        acc *= 1.1f;
4171                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4172                        break;
4173                }
4174            } while (true);
4175        }
4176    }
4177
4178    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
4179        public CalledFromWrongThreadException(String msg) {
4180            super(msg);
4181        }
4182    }
4183
4184    private SurfaceHolder mHolder = new SurfaceHolder() {
4185        // we only need a SurfaceHolder for opengl. it would be nice
4186        // to implement everything else though, especially the callback
4187        // support (opengl doesn't make use of it right now, but eventually
4188        // will).
4189        public Surface getSurface() {
4190            return mSurface;
4191        }
4192
4193        public boolean isCreating() {
4194            return false;
4195        }
4196
4197        public void addCallback(Callback callback) {
4198        }
4199
4200        public void removeCallback(Callback callback) {
4201        }
4202
4203        public void setFixedSize(int width, int height) {
4204        }
4205
4206        public void setSizeFromLayout() {
4207        }
4208
4209        public void setFormat(int format) {
4210        }
4211
4212        public void setType(int type) {
4213        }
4214
4215        public void setKeepScreenOn(boolean screenOn) {
4216        }
4217
4218        public Canvas lockCanvas() {
4219            return null;
4220        }
4221
4222        public Canvas lockCanvas(Rect dirty) {
4223            return null;
4224        }
4225
4226        public void unlockCanvasAndPost(Canvas canvas) {
4227        }
4228        public Rect getSurfaceFrame() {
4229            return null;
4230        }
4231    };
4232
4233    static RunQueue getRunQueue() {
4234        RunQueue rq = sRunQueues.get();
4235        if (rq != null) {
4236            return rq;
4237        }
4238        rq = new RunQueue();
4239        sRunQueues.set(rq);
4240        return rq;
4241    }
4242
4243    /**
4244     * @hide
4245     */
4246    static final class RunQueue {
4247        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
4248
4249        void post(Runnable action) {
4250            postDelayed(action, 0);
4251        }
4252
4253        void postDelayed(Runnable action, long delayMillis) {
4254            HandlerAction handlerAction = new HandlerAction();
4255            handlerAction.action = action;
4256            handlerAction.delay = delayMillis;
4257
4258            synchronized (mActions) {
4259                mActions.add(handlerAction);
4260            }
4261        }
4262
4263        void removeCallbacks(Runnable action) {
4264            final HandlerAction handlerAction = new HandlerAction();
4265            handlerAction.action = action;
4266
4267            synchronized (mActions) {
4268                final ArrayList<HandlerAction> actions = mActions;
4269
4270                while (actions.remove(handlerAction)) {
4271                    // Keep going
4272                }
4273            }
4274        }
4275
4276        void executeActions(Handler handler) {
4277            synchronized (mActions) {
4278                final ArrayList<HandlerAction> actions = mActions;
4279                final int count = actions.size();
4280
4281                for (int i = 0; i < count; i++) {
4282                    final HandlerAction handlerAction = actions.get(i);
4283                    handler.postDelayed(handlerAction.action, handlerAction.delay);
4284                }
4285
4286                actions.clear();
4287            }
4288        }
4289
4290        private static class HandlerAction {
4291            Runnable action;
4292            long delay;
4293
4294            @Override
4295            public boolean equals(Object o) {
4296                if (this == o) return true;
4297                if (o == null || getClass() != o.getClass()) return false;
4298
4299                HandlerAction that = (HandlerAction) o;
4300                return !(action != null ? !action.equals(that.action) : that.action != null);
4301
4302            }
4303
4304            @Override
4305            public int hashCode() {
4306                int result = action != null ? action.hashCode() : 0;
4307                result = 31 * result + (int) (delay ^ (delay >>> 32));
4308                return result;
4309            }
4310        }
4311    }
4312
4313    /**
4314     * Class for managing the accessibility interaction connection
4315     * based on the global accessibility state.
4316     */
4317    final class AccessibilityInteractionConnectionManager
4318            implements AccessibilityStateChangeListener {
4319        public void onAccessibilityStateChanged(boolean enabled) {
4320            if (enabled) {
4321                ensureConnection();
4322            } else {
4323                ensureNoConnection();
4324            }
4325        }
4326
4327        public void ensureConnection() {
4328            final boolean registered = mAttachInfo.mAccessibilityWindowId != View.NO_ID;
4329            if (!registered) {
4330                mAttachInfo.mAccessibilityWindowId =
4331                    mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
4332                            new AccessibilityInteractionConnection(ViewRootImpl.this));
4333            }
4334        }
4335
4336        public void ensureNoConnection() {
4337            final boolean registered = mAttachInfo.mAccessibilityWindowId != View.NO_ID;
4338            if (registered) {
4339                mAttachInfo.mAccessibilityWindowId = View.NO_ID;
4340                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
4341            }
4342        }
4343    }
4344
4345    /**
4346     * This class is an interface this ViewAncestor provides to the
4347     * AccessibilityManagerService to the latter can interact with
4348     * the view hierarchy in this ViewAncestor.
4349     */
4350    final class AccessibilityInteractionConnection
4351            extends IAccessibilityInteractionConnection.Stub {
4352        private final WeakReference<ViewRootImpl> mViewAncestor;
4353
4354        AccessibilityInteractionConnection(ViewRootImpl viewAncestor) {
4355            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4356        }
4357
4358        public void findAccessibilityNodeInfoByAccessibilityId(int accessibilityId,
4359                int interactionId, IAccessibilityInteractionConnectionCallback callback) {
4360            if (mViewAncestor.get() != null) {
4361                getAccessibilityInteractionController()
4362                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityId,
4363                        interactionId, callback);
4364            }
4365        }
4366
4367        public void performAccessibilityAction(int accessibilityId, int action,
4368                int interactionId, IAccessibilityInteractionConnectionCallback callback) {
4369            if (mViewAncestor.get() != null) {
4370                getAccessibilityInteractionController()
4371                    .performAccessibilityActionClientThread(accessibilityId, action, interactionId,
4372                            callback);
4373            }
4374        }
4375
4376        public void findAccessibilityNodeInfoByViewId(int viewId,
4377                int interactionId, IAccessibilityInteractionConnectionCallback callback) {
4378            if (mViewAncestor.get() != null) {
4379                getAccessibilityInteractionController()
4380                    .findAccessibilityNodeInfoByViewIdClientThread(viewId, interactionId, callback);
4381            }
4382        }
4383
4384        public void findAccessibilityNodeInfosByViewText(String text, int accessibilityId,
4385                int interactionId, IAccessibilityInteractionConnectionCallback callback) {
4386            if (mViewAncestor.get() != null) {
4387                getAccessibilityInteractionController()
4388                    .findAccessibilityNodeInfosByViewTextClientThread(text, accessibilityId,
4389                            interactionId, callback);
4390            }
4391        }
4392    }
4393
4394    /**
4395     * Class for managing accessibility interactions initiated from the system
4396     * and targeting the view hierarchy. A *ClientThread method is to be
4397     * called from the interaction connection this ViewAncestor gives the
4398     * system to talk to it and a corresponding *UiThread method that is executed
4399     * on the UI thread.
4400     */
4401    final class AccessibilityInteractionController {
4402        private static final int POOL_SIZE = 5;
4403
4404        private FindByAccessibilitytIdPredicate mFindByAccessibilityIdPredicate =
4405            new FindByAccessibilitytIdPredicate();
4406
4407        private ArrayList<AccessibilityNodeInfo> mTempAccessibilityNodeInfoList =
4408            new ArrayList<AccessibilityNodeInfo>();
4409
4410        // Reusable poolable arguments for interacting with the view hierarchy
4411        // to fit more arguments than Message and to avoid sharing objects between
4412        // two messages since several threads can send messages concurrently.
4413        private final Pool<SomeArgs> mPool = Pools.synchronizedPool(Pools.finitePool(
4414                new PoolableManager<SomeArgs>() {
4415                    public SomeArgs newInstance() {
4416                        return new SomeArgs();
4417                    }
4418
4419                    public void onAcquired(SomeArgs info) {
4420                        /* do nothing */
4421                    }
4422
4423                    public void onReleased(SomeArgs info) {
4424                        info.clear();
4425                    }
4426                }, POOL_SIZE)
4427        );
4428
4429        public class SomeArgs implements Poolable<SomeArgs> {
4430            private SomeArgs mNext;
4431            private boolean mIsPooled;
4432
4433            public Object arg1;
4434            public Object arg2;
4435            public int argi1;
4436            public int argi2;
4437            public int argi3;
4438
4439            public SomeArgs getNextPoolable() {
4440                return mNext;
4441            }
4442
4443            public boolean isPooled() {
4444                return mIsPooled;
4445            }
4446
4447            public void setNextPoolable(SomeArgs args) {
4448                mNext = args;
4449            }
4450
4451            public void setPooled(boolean isPooled) {
4452                mIsPooled = isPooled;
4453            }
4454
4455            private void clear() {
4456                arg1 = null;
4457                arg2 = null;
4458                argi1 = 0;
4459                argi2 = 0;
4460                argi3 = 0;
4461            }
4462        }
4463
4464        public void findAccessibilityNodeInfoByAccessibilityIdClientThread(int accessibilityId,
4465                int interactionId, IAccessibilityInteractionConnectionCallback callback) {
4466            Message message = Message.obtain();
4467            message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID;
4468            message.arg1 = accessibilityId;
4469            message.arg2 = interactionId;
4470            message.obj = callback;
4471            sendMessage(message);
4472        }
4473
4474        public void findAccessibilityNodeInfoByAccessibilityIdUiThread(Message message) {
4475            final int accessibilityId = message.arg1;
4476            final int interactionId = message.arg2;
4477            final IAccessibilityInteractionConnectionCallback callback =
4478                (IAccessibilityInteractionConnectionCallback) message.obj;
4479
4480            AccessibilityNodeInfo info = null;
4481            try {
4482                FindByAccessibilitytIdPredicate predicate = mFindByAccessibilityIdPredicate;
4483                predicate.init(accessibilityId);
4484                View root = ViewRootImpl.this.mView;
4485                View target = root.findViewByPredicate(predicate);
4486                if (target != null && target.isShown()) {
4487                    info = target.createAccessibilityNodeInfo();
4488                }
4489            } finally {
4490                try {
4491                    callback.setFindAccessibilityNodeInfoResult(info, interactionId);
4492                } catch (RemoteException re) {
4493                    /* ignore - the other side will time out */
4494                }
4495            }
4496        }
4497
4498        public void findAccessibilityNodeInfoByViewIdClientThread(int viewId, int interactionId,
4499                IAccessibilityInteractionConnectionCallback callback) {
4500            Message message = Message.obtain();
4501            message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID;
4502            message.arg1 = viewId;
4503            message.arg2 = interactionId;
4504            message.obj = callback;
4505            sendMessage(message);
4506        }
4507
4508        public void findAccessibilityNodeInfoByViewIdUiThread(Message message) {
4509            final int viewId = message.arg1;
4510            final int interactionId = message.arg2;
4511            final IAccessibilityInteractionConnectionCallback callback =
4512                (IAccessibilityInteractionConnectionCallback) message.obj;
4513
4514            AccessibilityNodeInfo info = null;
4515            try {
4516                View root = ViewRootImpl.this.mView;
4517                View target = root.findViewById(viewId);
4518                if (target != null && target.isShown()) {
4519                    info = target.createAccessibilityNodeInfo();
4520                }
4521            } finally {
4522                try {
4523                    callback.setFindAccessibilityNodeInfoResult(info, interactionId);
4524                } catch (RemoteException re) {
4525                    /* ignore - the other side will time out */
4526                }
4527            }
4528        }
4529
4530        public void findAccessibilityNodeInfosByViewTextClientThread(String text,
4531                int accessibilityViewId, int interactionId,
4532                IAccessibilityInteractionConnectionCallback callback) {
4533            Message message = Message.obtain();
4534            message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT;
4535            SomeArgs args = mPool.acquire();
4536            args.arg1 = text;
4537            args.argi1 = accessibilityViewId;
4538            args.argi2 = interactionId;
4539            args.arg2 = callback;
4540            message.obj = args;
4541            sendMessage(message);
4542        }
4543
4544        public void findAccessibilityNodeInfosByViewTextUiThread(Message message) {
4545            SomeArgs args = (SomeArgs) message.obj;
4546            final String text = (String) args.arg1;
4547            final int accessibilityViewId = args.argi1;
4548            final int interactionId = args.argi2;
4549            final IAccessibilityInteractionConnectionCallback callback =
4550                (IAccessibilityInteractionConnectionCallback) args.arg2;
4551            mPool.release(args);
4552
4553            List<AccessibilityNodeInfo> infos = null;
4554            try {
4555                ArrayList<View> foundViews = mAttachInfo.mFocusablesTempList;
4556                foundViews.clear();
4557
4558                View root;
4559                if (accessibilityViewId != View.NO_ID) {
4560                    root = findViewByAccessibilityId(accessibilityViewId);
4561                } else {
4562                    root = ViewRootImpl.this.mView;
4563                }
4564
4565                if (root == null || !root.isShown()) {
4566                    return;
4567                }
4568
4569                root.findViewsWithText(foundViews, text);
4570                if (foundViews.isEmpty()) {
4571                    return;
4572                }
4573
4574                infos = mTempAccessibilityNodeInfoList;
4575                infos.clear();
4576
4577                final int viewCount = foundViews.size();
4578                for (int i = 0; i < viewCount; i++) {
4579                    View foundView = foundViews.get(i);
4580                    if (foundView.isShown()) {
4581                        infos.add(foundView.createAccessibilityNodeInfo());
4582                    }
4583                 }
4584            } finally {
4585                try {
4586                    callback.setFindAccessibilityNodeInfosResult(infos, interactionId);
4587                } catch (RemoteException re) {
4588                    /* ignore - the other side will time out */
4589                }
4590            }
4591        }
4592
4593        public void performAccessibilityActionClientThread(int accessibilityId, int action,
4594                int interactionId, IAccessibilityInteractionConnectionCallback callback) {
4595            Message message = Message.obtain();
4596            message.what = DO_PERFORM_ACCESSIBILITY_ACTION;
4597            SomeArgs args = mPool.acquire();
4598            args.argi1 = accessibilityId;
4599            args.argi2 = action;
4600            args.argi3 = interactionId;
4601            args.arg1 = callback;
4602            message.obj = args;
4603            sendMessage(message);
4604        }
4605
4606        public void perfromAccessibilityActionUiThread(Message message) {
4607            SomeArgs args = (SomeArgs) message.obj;
4608            final int accessibilityId = args.argi1;
4609            final int action = args.argi2;
4610            final int interactionId = args.argi3;
4611            final IAccessibilityInteractionConnectionCallback callback =
4612                (IAccessibilityInteractionConnectionCallback) args.arg1;
4613            mPool.release(args);
4614
4615            boolean succeeded = false;
4616            try {
4617                switch (action) {
4618                    case AccessibilityNodeInfo.ACTION_FOCUS: {
4619                        succeeded = performActionFocus(accessibilityId);
4620                    } break;
4621                    case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
4622                        succeeded = performActionClearFocus(accessibilityId);
4623                    } break;
4624                    case AccessibilityNodeInfo.ACTION_SELECT: {
4625                        succeeded = performActionSelect(accessibilityId);
4626                    } break;
4627                    case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
4628                        succeeded = performActionClearSelection(accessibilityId);
4629                    } break;
4630                }
4631            } finally {
4632                try {
4633                    callback.setPerformAccessibilityActionResult(succeeded, interactionId);
4634                } catch (RemoteException re) {
4635                    /* ignore - the other side will time out */
4636                }
4637            }
4638        }
4639
4640        private boolean performActionFocus(int accessibilityId) {
4641            View target = findViewByAccessibilityId(accessibilityId);
4642            if (target == null) {
4643                return false;
4644            }
4645            // Get out of touch mode since accessibility wants to move focus around.
4646            ensureTouchMode(false);
4647            return target.requestFocus();
4648        }
4649
4650        private boolean performActionClearFocus(int accessibilityId) {
4651            View target = findViewByAccessibilityId(accessibilityId);
4652            if (target == null) {
4653                return false;
4654            }
4655            if (!target.isFocused()) {
4656                return false;
4657            }
4658            target.clearFocus();
4659            return !target.isFocused();
4660        }
4661
4662        private boolean performActionSelect(int accessibilityId) {
4663            View target = findViewByAccessibilityId(accessibilityId);
4664            if (target == null) {
4665                return false;
4666            }
4667            if (target.isSelected()) {
4668                return false;
4669            }
4670            target.setSelected(true);
4671            return target.isSelected();
4672        }
4673
4674        private boolean performActionClearSelection(int accessibilityId) {
4675            View target = findViewByAccessibilityId(accessibilityId);
4676            if (target == null) {
4677                return false;
4678            }
4679            if (!target.isSelected()) {
4680                return false;
4681            }
4682            target.setSelected(false);
4683            return !target.isSelected();
4684        }
4685
4686        private View findViewByAccessibilityId(int accessibilityId) {
4687            View root = ViewRootImpl.this.mView;
4688            if (root == null) {
4689                return null;
4690            }
4691            mFindByAccessibilityIdPredicate.init(accessibilityId);
4692            View foundView = root.findViewByPredicate(mFindByAccessibilityIdPredicate);
4693            return (foundView != null && foundView.isShown()) ? foundView : null;
4694        }
4695
4696        private final class FindByAccessibilitytIdPredicate implements Predicate<View> {
4697            public int mSerchedId;
4698
4699            public void init(int searchedId) {
4700                mSerchedId = searchedId;
4701            }
4702
4703            public boolean apply(View view) {
4704                return (view.getAccessibilityViewId() == mSerchedId);
4705            }
4706        }
4707    }
4708
4709    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
4710        public volatile boolean mIsPending;
4711
4712        public void run() {
4713            if (mView != null) {
4714                // Check again for accessibility state since this is executed delayed.
4715                AccessibilityManager accessibilityManager =
4716                    AccessibilityManager.getInstance(mView.mContext);
4717                if (accessibilityManager.isEnabled()) {
4718                    // Send the event directly since we do not want to append the
4719                    // source text because this is the text for the entire window
4720                    // and we just want to notify that the content has changed.
4721                    AccessibilityEvent event = AccessibilityEvent.obtain(
4722                            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
4723                    mView.onInitializeAccessibilityEvent(event);
4724                    accessibilityManager.sendAccessibilityEvent(event);
4725                }
4726                mIsPending = false;
4727            }
4728        }
4729    }
4730}
4731