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