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