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