ViewRootImpl.java revision 3c4ce72c4d66d9ee041924259f20381b658c1529
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            // If we're not drawing, then we don't need to draw the transitions, either
1603            if (mPendingTransitions != null) {
1604                mPendingTransitions.clear();
1605            }
1606
1607            // We were supposed to report when we are done drawing. Since we canceled the
1608            // draw, remember it here.
1609            if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1610                mReportNextDraw = true;
1611            }
1612            if (fullRedrawNeeded) {
1613                mFullRedrawNeeded = true;
1614            }
1615
1616            if (viewVisibility == View.VISIBLE) {
1617                // Try again
1618                scheduleTraversals();
1619            }
1620        }
1621    }
1622
1623    public void requestTransparentRegion(View child) {
1624        // the test below should not fail unless someone is messing with us
1625        checkThread();
1626        if (mView == child) {
1627            mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1628            // Need to make sure we re-evaluate the window attributes next
1629            // time around, to ensure the window has the correct format.
1630            mWindowAttributesChanged = true;
1631            requestLayout();
1632        }
1633    }
1634
1635    /**
1636     * Figures out the measure spec for the root view in a window based on it's
1637     * layout params.
1638     *
1639     * @param windowSize
1640     *            The available width or height of the window
1641     *
1642     * @param rootDimension
1643     *            The layout params for one dimension (width or height) of the
1644     *            window.
1645     *
1646     * @return The measure spec to use to measure the root view.
1647     */
1648    private int getRootMeasureSpec(int windowSize, int rootDimension) {
1649        int measureSpec;
1650        switch (rootDimension) {
1651
1652        case ViewGroup.LayoutParams.MATCH_PARENT:
1653            // Window can't resize. Force root view to be windowSize.
1654            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1655            break;
1656        case ViewGroup.LayoutParams.WRAP_CONTENT:
1657            // Window can resize. Set max size for root view.
1658            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1659            break;
1660        default:
1661            // Window wants to be an exact size. Force root view to be that size.
1662            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1663            break;
1664        }
1665        return measureSpec;
1666    }
1667
1668    int mHardwareYOffset;
1669    int mResizeAlpha;
1670    final Paint mResizePaint = new Paint();
1671
1672    public void onHardwarePreDraw(HardwareCanvas canvas) {
1673        canvas.translate(0, -mHardwareYOffset);
1674    }
1675
1676    public void onHardwarePostDraw(HardwareCanvas canvas) {
1677        if (mResizeBuffer != null) {
1678            mResizePaint.setAlpha(mResizeAlpha);
1679            canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint);
1680        }
1681    }
1682
1683    /**
1684     * @hide
1685     */
1686    void outputDisplayList(View view) {
1687        if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) {
1688            DisplayList displayList = view.getDisplayList();
1689            if (displayList != null) {
1690                mAttachInfo.mHardwareCanvas.outputDisplayList(displayList);
1691            }
1692        }
1693    }
1694
1695    /**
1696     * @see #PROPERTY_PROFILE_RENDERING
1697     */
1698    private void profileRendering(boolean enabled) {
1699        if (mProfileRendering) {
1700            mRenderProfilingEnabled = enabled;
1701            if (mRenderProfiler == null) {
1702                mRenderProfiler = new Thread(new Runnable() {
1703                    @Override
1704                    public void run() {
1705                        Log.d(TAG, "Starting profiling thread");
1706                        while (mRenderProfilingEnabled) {
1707                            mAttachInfo.mHandler.post(new Runnable() {
1708                                @Override
1709                                public void run() {
1710                                    mDirty.set(0, 0, mWidth, mHeight);
1711                                    scheduleTraversals();
1712                                }
1713                            });
1714                            try {
1715                                // TODO: This should use vsync when we get an API
1716                                Thread.sleep(15);
1717                            } catch (InterruptedException e) {
1718                                Log.d(TAG, "Exiting profiling thread");
1719                            }
1720                        }
1721                    }
1722                }, "Rendering Profiler");
1723                mRenderProfiler.start();
1724            } else {
1725                mRenderProfiler.interrupt();
1726                mRenderProfiler = null;
1727            }
1728        }
1729    }
1730
1731    private void draw(boolean fullRedrawNeeded) {
1732        Surface surface = mSurface;
1733        if (surface == null || !surface.isValid()) {
1734            return;
1735        }
1736
1737        if (!sFirstDrawComplete) {
1738            synchronized (sFirstDrawHandlers) {
1739                sFirstDrawComplete = true;
1740                final int count = sFirstDrawHandlers.size();
1741                for (int i = 0; i< count; i++) {
1742                    post(sFirstDrawHandlers.get(i));
1743                }
1744            }
1745        }
1746
1747        scrollToRectOrFocus(null, false);
1748
1749        if (mAttachInfo.mViewScrollChanged) {
1750            mAttachInfo.mViewScrollChanged = false;
1751            mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1752        }
1753
1754        int yoff;
1755        boolean animating = mScroller != null && mScroller.computeScrollOffset();
1756        if (animating) {
1757            yoff = mScroller.getCurrY();
1758        } else {
1759            yoff = mScrollY;
1760        }
1761        if (mCurScrollY != yoff) {
1762            mCurScrollY = yoff;
1763            fullRedrawNeeded = true;
1764        }
1765        float appScale = mAttachInfo.mApplicationScale;
1766        boolean scalingRequired = mAttachInfo.mScalingRequired;
1767
1768        int resizeAlpha = 0;
1769        if (mResizeBuffer != null) {
1770            long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
1771            if (deltaTime < mResizeBufferDuration) {
1772                float amt = deltaTime/(float) mResizeBufferDuration;
1773                amt = mResizeInterpolator.getInterpolation(amt);
1774                animating = true;
1775                resizeAlpha = 255 - (int)(amt*255);
1776            } else {
1777                disposeResizeBuffer();
1778            }
1779        }
1780
1781        Rect dirty = mDirty;
1782        if (mSurfaceHolder != null) {
1783            // The app owns the surface, we won't draw.
1784            dirty.setEmpty();
1785            if (animating) {
1786                if (mScroller != null) {
1787                    mScroller.abortAnimation();
1788                }
1789                disposeResizeBuffer();
1790            }
1791            return;
1792        }
1793
1794        if (fullRedrawNeeded) {
1795            mAttachInfo.mIgnoreDirtyState = true;
1796            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1797        }
1798
1799        if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
1800            if (!dirty.isEmpty() || mIsAnimating) {
1801                mIsAnimating = false;
1802                mHardwareYOffset = yoff;
1803                mResizeAlpha = resizeAlpha;
1804
1805                mCurrentDirty.set(dirty);
1806                mCurrentDirty.union(mPreviousDirty);
1807                mPreviousDirty.set(dirty);
1808                dirty.setEmpty();
1809
1810                Rect currentDirty = mCurrentDirty;
1811                if (animating) {
1812                    currentDirty = null;
1813                }
1814
1815                if (mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, currentDirty)) {
1816                    mPreviousDirty.set(0, 0, mWidth, mHeight);
1817                }
1818            }
1819
1820            if (animating) {
1821                mFullRedrawNeeded = true;
1822                scheduleTraversals();
1823            }
1824
1825            return;
1826        }
1827
1828        if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1829            Log.v(TAG, "Draw " + mView + "/"
1830                    + mWindowAttributes.getTitle()
1831                    + ": dirty={" + dirty.left + "," + dirty.top
1832                    + "," + dirty.right + "," + dirty.bottom + "} surface="
1833                    + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1834                    appScale + ", width=" + mWidth + ", height=" + mHeight);
1835        }
1836
1837        if (!dirty.isEmpty() || mIsAnimating) {
1838            Canvas canvas;
1839            try {
1840                int left = dirty.left;
1841                int top = dirty.top;
1842                int right = dirty.right;
1843                int bottom = dirty.bottom;
1844
1845                final long lockCanvasStartTime;
1846                if (ViewDebug.DEBUG_LATENCY) {
1847                    lockCanvasStartTime = System.nanoTime();
1848                }
1849
1850                canvas = surface.lockCanvas(dirty);
1851
1852                if (ViewDebug.DEBUG_LATENCY) {
1853                    long now = System.nanoTime();
1854                    Log.d(TAG, "Latency: Spent "
1855                            + ((now - lockCanvasStartTime) * 0.000001f)
1856                            + "ms waiting for surface.lockCanvas()");
1857                }
1858
1859                if (left != dirty.left || top != dirty.top || right != dirty.right ||
1860                        bottom != dirty.bottom) {
1861                    mAttachInfo.mIgnoreDirtyState = true;
1862                }
1863
1864                // TODO: Do this in native
1865                canvas.setDensity(mDensity);
1866            } catch (Surface.OutOfResourcesException e) {
1867                Log.e(TAG, "OutOfResourcesException locking surface", e);
1868                try {
1869                    if (!sWindowSession.outOfMemory(mWindow)) {
1870                        Slog.w(TAG, "No processes killed for memory; killing self");
1871                        Process.killProcess(Process.myPid());
1872                    }
1873                } catch (RemoteException ex) {
1874                }
1875                mLayoutRequested = true;    // ask wm for a new surface next time.
1876                return;
1877            } catch (IllegalArgumentException e) {
1878                Log.e(TAG, "IllegalArgumentException locking surface", e);
1879                // Don't assume this is due to out of memory, it could be
1880                // something else, and if it is something else then we could
1881                // kill stuff (or ourself) for no reason.
1882                mLayoutRequested = true;    // ask wm for a new surface next time.
1883                return;
1884            }
1885
1886            try {
1887                if (!dirty.isEmpty() || mIsAnimating) {
1888                    long startTime = 0L;
1889
1890                    if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1891                        Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
1892                                + canvas.getWidth() + ", h=" + canvas.getHeight());
1893                        //canvas.drawARGB(255, 255, 0, 0);
1894                    }
1895
1896                    if (ViewDebug.DEBUG_PROFILE_DRAWING) {
1897                        startTime = SystemClock.elapsedRealtime();
1898                    }
1899
1900                    // If this bitmap's format includes an alpha channel, we
1901                    // need to clear it before drawing so that the child will
1902                    // properly re-composite its drawing on a transparent
1903                    // background. This automatically respects the clip/dirty region
1904                    // or
1905                    // If we are applying an offset, we need to clear the area
1906                    // where the offset doesn't appear to avoid having garbage
1907                    // left in the blank areas.
1908                    if (!canvas.isOpaque() || yoff != 0) {
1909                        canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1910                    }
1911
1912                    dirty.setEmpty();
1913                    mIsAnimating = false;
1914                    mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1915                    mView.mPrivateFlags |= View.DRAWN;
1916
1917                    if (DEBUG_DRAW) {
1918                        Context cxt = mView.getContext();
1919                        Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1920                                ", metrics=" + cxt.getResources().getDisplayMetrics() +
1921                                ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1922                    }
1923                    try {
1924                        canvas.translate(0, -yoff);
1925                        if (mTranslator != null) {
1926                            mTranslator.translateCanvas(canvas);
1927                        }
1928                        canvas.setScreenDensity(scalingRequired
1929                                ? DisplayMetrics.DENSITY_DEVICE : 0);
1930                        mAttachInfo.mSetIgnoreDirtyState = false;
1931                        mView.draw(canvas);
1932                    } finally {
1933                        if (!mAttachInfo.mSetIgnoreDirtyState) {
1934                            // Only clear the flag if it was not set during the mView.draw() call
1935                            mAttachInfo.mIgnoreDirtyState = false;
1936                        }
1937                    }
1938
1939                    if (false && ViewDebug.consistencyCheckEnabled) {
1940                        mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1941                    }
1942
1943                    if (ViewDebug.DEBUG_PROFILE_DRAWING) {
1944                        EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1945                    }
1946                }
1947
1948            } finally {
1949                surface.unlockCanvasAndPost(canvas);
1950            }
1951        }
1952
1953        if (LOCAL_LOGV) {
1954            Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
1955        }
1956
1957        if (animating) {
1958            mFullRedrawNeeded = true;
1959            scheduleTraversals();
1960        }
1961    }
1962
1963    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1964        final View.AttachInfo attachInfo = mAttachInfo;
1965        final Rect ci = attachInfo.mContentInsets;
1966        final Rect vi = attachInfo.mVisibleInsets;
1967        int scrollY = 0;
1968        boolean handled = false;
1969
1970        if (vi.left > ci.left || vi.top > ci.top
1971                || vi.right > ci.right || vi.bottom > ci.bottom) {
1972            // We'll assume that we aren't going to change the scroll
1973            // offset, since we want to avoid that unless it is actually
1974            // going to make the focus visible...  otherwise we scroll
1975            // all over the place.
1976            scrollY = mScrollY;
1977            // We can be called for two different situations: during a draw,
1978            // to update the scroll position if the focus has changed (in which
1979            // case 'rectangle' is null), or in response to a
1980            // requestChildRectangleOnScreen() call (in which case 'rectangle'
1981            // is non-null and we just want to scroll to whatever that
1982            // rectangle is).
1983            View focus = mRealFocusedView;
1984
1985            // When in touch mode, focus points to the previously focused view,
1986            // which may have been removed from the view hierarchy. The following
1987            // line checks whether the view is still in our hierarchy.
1988            if (focus == null || focus.mAttachInfo != mAttachInfo) {
1989                mRealFocusedView = null;
1990                return false;
1991            }
1992
1993            if (focus != mLastScrolledFocus) {
1994                // If the focus has changed, then ignore any requests to scroll
1995                // to a rectangle; first we want to make sure the entire focus
1996                // view is visible.
1997                rectangle = null;
1998            }
1999            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2000                    + " rectangle=" + rectangle + " ci=" + ci
2001                    + " vi=" + vi);
2002            if (focus == mLastScrolledFocus && !mScrollMayChange
2003                    && rectangle == null) {
2004                // Optimization: if the focus hasn't changed since last
2005                // time, and no layout has happened, then just leave things
2006                // as they are.
2007                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2008                        + mScrollY + " vi=" + vi.toShortString());
2009            } else if (focus != null) {
2010                // We need to determine if the currently focused view is
2011                // within the visible part of the window and, if not, apply
2012                // a pan so it can be seen.
2013                mLastScrolledFocus = focus;
2014                mScrollMayChange = false;
2015                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2016                // Try to find the rectangle from the focus view.
2017                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2018                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2019                            + mView.getWidth() + " h=" + mView.getHeight()
2020                            + " ci=" + ci.toShortString()
2021                            + " vi=" + vi.toShortString());
2022                    if (rectangle == null) {
2023                        focus.getFocusedRect(mTempRect);
2024                        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2025                                + ": focusRect=" + mTempRect.toShortString());
2026                        if (mView instanceof ViewGroup) {
2027                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2028                                    focus, mTempRect);
2029                        }
2030                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2031                                "Focus in window: focusRect="
2032                                + mTempRect.toShortString()
2033                                + " visRect=" + mVisRect.toShortString());
2034                    } else {
2035                        mTempRect.set(rectangle);
2036                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2037                                "Request scroll to rect: "
2038                                + mTempRect.toShortString()
2039                                + " visRect=" + mVisRect.toShortString());
2040                    }
2041                    if (mTempRect.intersect(mVisRect)) {
2042                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2043                                "Focus window visible rect: "
2044                                + mTempRect.toShortString());
2045                        if (mTempRect.height() >
2046                                (mView.getHeight()-vi.top-vi.bottom)) {
2047                            // If the focus simply is not going to fit, then
2048                            // best is probably just to leave things as-is.
2049                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2050                                    "Too tall; leaving scrollY=" + scrollY);
2051                        } else if ((mTempRect.top-scrollY) < vi.top) {
2052                            scrollY -= vi.top - (mTempRect.top-scrollY);
2053                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2054                                    "Top covered; scrollY=" + scrollY);
2055                        } else if ((mTempRect.bottom-scrollY)
2056                                > (mView.getHeight()-vi.bottom)) {
2057                            scrollY += (mTempRect.bottom-scrollY)
2058                                    - (mView.getHeight()-vi.bottom);
2059                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2060                                    "Bottom covered; scrollY=" + scrollY);
2061                        }
2062                        handled = true;
2063                    }
2064                }
2065            }
2066        }
2067
2068        if (scrollY != mScrollY) {
2069            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2070                    + mScrollY + " , new=" + scrollY);
2071            if (!immediate && mResizeBuffer == null) {
2072                if (mScroller == null) {
2073                    mScroller = new Scroller(mView.getContext());
2074                }
2075                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2076            } else if (mScroller != null) {
2077                mScroller.abortAnimation();
2078            }
2079            mScrollY = scrollY;
2080        }
2081
2082        return handled;
2083    }
2084
2085    public void requestChildFocus(View child, View focused) {
2086        checkThread();
2087        if (mFocusedView != focused) {
2088            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
2089            scheduleTraversals();
2090        }
2091        mFocusedView = mRealFocusedView = focused;
2092        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
2093                + mFocusedView);
2094    }
2095
2096    public void clearChildFocus(View child) {
2097        checkThread();
2098
2099        View oldFocus = mFocusedView;
2100
2101        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
2102        mFocusedView = mRealFocusedView = null;
2103        if (mView != null && !mView.hasFocus()) {
2104            // If a view gets the focus, the listener will be invoked from requestChildFocus()
2105            if (!mView.requestFocus(View.FOCUS_FORWARD)) {
2106                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
2107            }
2108        } else if (oldFocus != null) {
2109            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
2110        }
2111    }
2112
2113
2114    public void focusableViewAvailable(View v) {
2115        checkThread();
2116
2117        if (mView != null) {
2118            if (!mView.hasFocus()) {
2119                v.requestFocus();
2120            } else {
2121                // the one case where will transfer focus away from the current one
2122                // is if the current view is a view group that prefers to give focus
2123                // to its children first AND the view is a descendant of it.
2124                mFocusedView = mView.findFocus();
2125                boolean descendantsHaveDibsOnFocus =
2126                        (mFocusedView instanceof ViewGroup) &&
2127                            (((ViewGroup) mFocusedView).getDescendantFocusability() ==
2128                                    ViewGroup.FOCUS_AFTER_DESCENDANTS);
2129                if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
2130                    // If a view gets the focus, the listener will be invoked from requestChildFocus()
2131                    v.requestFocus();
2132                }
2133            }
2134        }
2135    }
2136
2137    public void recomputeViewAttributes(View child) {
2138        checkThread();
2139        if (mView == child) {
2140            mAttachInfo.mRecomputeGlobalAttributes = true;
2141            if (!mWillDrawSoon) {
2142                scheduleTraversals();
2143            }
2144        }
2145    }
2146
2147    void dispatchDetachedFromWindow() {
2148        if (mView != null && mView.mAttachInfo != null) {
2149            if (mAttachInfo.mHardwareRenderer != null &&
2150                    mAttachInfo.mHardwareRenderer.isEnabled()) {
2151                mAttachInfo.mHardwareRenderer.validate();
2152            }
2153            mView.dispatchDetachedFromWindow();
2154        }
2155
2156        mAccessibilityInteractionConnectionManager.ensureNoConnection();
2157        mAccessibilityManager.removeAccessibilityStateChangeListener(
2158                mAccessibilityInteractionConnectionManager);
2159        removeSendWindowContentChangedCallback();
2160
2161        mView = null;
2162        mAttachInfo.mRootView = null;
2163        mAttachInfo.mSurface = null;
2164
2165        destroyHardwareRenderer();
2166
2167        mSurface.release();
2168
2169        if (mInputQueueCallback != null && mInputQueue != null) {
2170            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2171            mInputQueueCallback = null;
2172            mInputQueue = null;
2173        } else if (mInputChannel != null) {
2174            InputQueue.unregisterInputChannel(mInputChannel);
2175        }
2176        try {
2177            sWindowSession.remove(mWindow);
2178        } catch (RemoteException e) {
2179        }
2180
2181        // Dispose the input channel after removing the window so the Window Manager
2182        // doesn't interpret the input channel being closed as an abnormal termination.
2183        if (mInputChannel != null) {
2184            mInputChannel.dispose();
2185            mInputChannel = null;
2186        }
2187    }
2188
2189    void updateConfiguration(Configuration config, boolean force) {
2190        if (DEBUG_CONFIGURATION) Log.v(TAG,
2191                "Applying new config to window "
2192                + mWindowAttributes.getTitle()
2193                + ": " + config);
2194
2195        CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2196        if (ci != null) {
2197            config = new Configuration(config);
2198            ci.applyToConfiguration(config);
2199        }
2200
2201        synchronized (sConfigCallbacks) {
2202            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2203                sConfigCallbacks.get(i).onConfigurationChanged(config);
2204            }
2205        }
2206        if (mView != null) {
2207            // At this point the resources have been updated to
2208            // have the most recent config, whatever that is.  Use
2209            // the on in them which may be newer.
2210            config = mView.getResources().getConfiguration();
2211            if (force || mLastConfiguration.diff(config) != 0) {
2212                mLastConfiguration.setTo(config);
2213                mView.dispatchConfigurationChanged(config);
2214            }
2215        }
2216    }
2217
2218    /**
2219     * Return true if child is an ancestor of parent, (or equal to the parent).
2220     */
2221    private static boolean isViewDescendantOf(View child, View parent) {
2222        if (child == parent) {
2223            return true;
2224        }
2225
2226        final ViewParent theParent = child.getParent();
2227        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2228    }
2229
2230    private static void forceLayout(View view) {
2231        view.forceLayout();
2232        if (view instanceof ViewGroup) {
2233            ViewGroup group = (ViewGroup) view;
2234            final int count = group.getChildCount();
2235            for (int i = 0; i < count; i++) {
2236                forceLayout(group.getChildAt(i));
2237            }
2238        }
2239    }
2240
2241    public final static int DO_TRAVERSAL = 1000;
2242    public final static int DIE = 1001;
2243    public final static int RESIZED = 1002;
2244    public final static int RESIZED_REPORT = 1003;
2245    public final static int WINDOW_FOCUS_CHANGED = 1004;
2246    public final static int DISPATCH_KEY = 1005;
2247    public final static int DISPATCH_POINTER = 1006;
2248    public final static int DISPATCH_TRACKBALL = 1007;
2249    public final static int DISPATCH_APP_VISIBILITY = 1008;
2250    public final static int DISPATCH_GET_NEW_SURFACE = 1009;
2251    public final static int FINISHED_EVENT = 1010;
2252    public final static int DISPATCH_KEY_FROM_IME = 1011;
2253    public final static int FINISH_INPUT_CONNECTION = 1012;
2254    public final static int CHECK_FOCUS = 1013;
2255    public final static int CLOSE_SYSTEM_DIALOGS = 1014;
2256    public final static int DISPATCH_DRAG_EVENT = 1015;
2257    public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
2258    public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
2259    public final static int DISPATCH_GENERIC_MOTION = 1018;
2260    public final static int UPDATE_CONFIGURATION = 1019;
2261    public final static int DO_PERFORM_ACCESSIBILITY_ACTION = 1020;
2262    public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID = 1021;
2263    public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID = 1022;
2264    public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT = 1023;
2265
2266    @Override
2267    public String getMessageName(Message message) {
2268        switch (message.what) {
2269            case DO_TRAVERSAL:
2270                return "DO_TRAVERSAL";
2271            case DIE:
2272                return "DIE";
2273            case RESIZED:
2274                return "RESIZED";
2275            case RESIZED_REPORT:
2276                return "RESIZED_REPORT";
2277            case WINDOW_FOCUS_CHANGED:
2278                return "WINDOW_FOCUS_CHANGED";
2279            case DISPATCH_KEY:
2280                return "DISPATCH_KEY";
2281            case DISPATCH_POINTER:
2282                return "DISPATCH_POINTER";
2283            case DISPATCH_TRACKBALL:
2284                return "DISPATCH_TRACKBALL";
2285            case DISPATCH_APP_VISIBILITY:
2286                return "DISPATCH_APP_VISIBILITY";
2287            case DISPATCH_GET_NEW_SURFACE:
2288                return "DISPATCH_GET_NEW_SURFACE";
2289            case FINISHED_EVENT:
2290                return "FINISHED_EVENT";
2291            case DISPATCH_KEY_FROM_IME:
2292                return "DISPATCH_KEY_FROM_IME";
2293            case FINISH_INPUT_CONNECTION:
2294                return "FINISH_INPUT_CONNECTION";
2295            case CHECK_FOCUS:
2296                return "CHECK_FOCUS";
2297            case CLOSE_SYSTEM_DIALOGS:
2298                return "CLOSE_SYSTEM_DIALOGS";
2299            case DISPATCH_DRAG_EVENT:
2300                return "DISPATCH_DRAG_EVENT";
2301            case DISPATCH_DRAG_LOCATION_EVENT:
2302                return "DISPATCH_DRAG_LOCATION_EVENT";
2303            case DISPATCH_SYSTEM_UI_VISIBILITY:
2304                return "DISPATCH_SYSTEM_UI_VISIBILITY";
2305            case DISPATCH_GENERIC_MOTION:
2306                return "DISPATCH_GENERIC_MOTION";
2307            case UPDATE_CONFIGURATION:
2308                return "UPDATE_CONFIGURATION";
2309            case DO_PERFORM_ACCESSIBILITY_ACTION:
2310                return "DO_PERFORM_ACCESSIBILITY_ACTION";
2311            case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID:
2312                return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID";
2313            case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID:
2314                return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID";
2315            case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT:
2316                return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT";
2317
2318        }
2319        return super.getMessageName(message);
2320    }
2321
2322    @Override
2323    public void handleMessage(Message msg) {
2324        switch (msg.what) {
2325        case View.AttachInfo.INVALIDATE_MSG:
2326            ((View) msg.obj).invalidate();
2327            break;
2328        case View.AttachInfo.INVALIDATE_RECT_MSG:
2329            final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2330            info.target.invalidate(info.left, info.top, info.right, info.bottom);
2331            info.release();
2332            break;
2333        case DO_TRAVERSAL:
2334            if (mProfile) {
2335                Debug.startMethodTracing("ViewAncestor");
2336            }
2337
2338            final long traversalStartTime;
2339            if (ViewDebug.DEBUG_LATENCY) {
2340                traversalStartTime = System.nanoTime();
2341                mLastDrawDurationNanos = 0;
2342            }
2343
2344            performTraversals();
2345
2346            if (ViewDebug.DEBUG_LATENCY) {
2347                long now = System.nanoTime();
2348                Log.d(TAG, "Latency: Spent "
2349                        + ((now - traversalStartTime) * 0.000001f)
2350                        + "ms in performTraversals(), with "
2351                        + (mLastDrawDurationNanos * 0.000001f)
2352                        + "ms of that time in draw()");
2353                mLastTraversalFinishedTimeNanos = now;
2354            }
2355
2356            if (mProfile) {
2357                Debug.stopMethodTracing();
2358                mProfile = false;
2359            }
2360            break;
2361        case FINISHED_EVENT:
2362            handleFinishedEvent(msg.arg1, msg.arg2 != 0);
2363            break;
2364        case DISPATCH_KEY:
2365            deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
2366            break;
2367        case DISPATCH_POINTER:
2368            deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2369            break;
2370        case DISPATCH_TRACKBALL:
2371            deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2372            break;
2373        case DISPATCH_GENERIC_MOTION:
2374            deliverGenericMotionEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2375            break;
2376        case DISPATCH_APP_VISIBILITY:
2377            handleAppVisibility(msg.arg1 != 0);
2378            break;
2379        case DISPATCH_GET_NEW_SURFACE:
2380            handleGetNewSurface();
2381            break;
2382        case RESIZED:
2383            ResizedInfo ri = (ResizedInfo)msg.obj;
2384
2385            if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
2386                    && mPendingContentInsets.equals(ri.coveredInsets)
2387                    && mPendingVisibleInsets.equals(ri.visibleInsets)
2388                    && ((ResizedInfo)msg.obj).newConfig == null) {
2389                break;
2390            }
2391            // fall through...
2392        case RESIZED_REPORT:
2393            if (mAdded) {
2394                Configuration config = ((ResizedInfo)msg.obj).newConfig;
2395                if (config != null) {
2396                    updateConfiguration(config, false);
2397                }
2398                mWinFrame.left = 0;
2399                mWinFrame.right = msg.arg1;
2400                mWinFrame.top = 0;
2401                mWinFrame.bottom = msg.arg2;
2402                mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
2403                mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
2404                if (msg.what == RESIZED_REPORT) {
2405                    mReportNextDraw = true;
2406                }
2407
2408                if (mView != null) {
2409                    forceLayout(mView);
2410                }
2411                requestLayout();
2412            }
2413            break;
2414        case WINDOW_FOCUS_CHANGED: {
2415            if (mAdded) {
2416                boolean hasWindowFocus = msg.arg1 != 0;
2417                mAttachInfo.mHasWindowFocus = hasWindowFocus;
2418
2419                profileRendering(hasWindowFocus);
2420
2421                if (hasWindowFocus) {
2422                    boolean inTouchMode = msg.arg2 != 0;
2423                    ensureTouchModeLocally(inTouchMode);
2424
2425                    if (mAttachInfo.mHardwareRenderer != null &&
2426                            mSurface != null && mSurface.isValid()) {
2427                        mFullRedrawNeeded = true;
2428                        try {
2429                            mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2430                                    mAttachInfo, mHolder);
2431                        } catch (Surface.OutOfResourcesException e) {
2432                            Log.e(TAG, "OutOfResourcesException locking surface", e);
2433                            try {
2434                                if (!sWindowSession.outOfMemory(mWindow)) {
2435                                    Slog.w(TAG, "No processes killed for memory; killing self");
2436                                    Process.killProcess(Process.myPid());
2437                                }
2438                            } catch (RemoteException ex) {
2439                            }
2440                            // Retry in a bit.
2441                            sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
2442                            return;
2443                        }
2444                    }
2445                }
2446
2447                mLastWasImTarget = WindowManager.LayoutParams
2448                        .mayUseInputMethod(mWindowAttributes.flags);
2449
2450                InputMethodManager imm = InputMethodManager.peekInstance();
2451                if (mView != null) {
2452                    if (hasWindowFocus && imm != null && mLastWasImTarget) {
2453                        imm.startGettingWindowFocus(mView);
2454                    }
2455                    mAttachInfo.mKeyDispatchState.reset();
2456                    mView.dispatchWindowFocusChanged(hasWindowFocus);
2457                }
2458
2459                // Note: must be done after the focus change callbacks,
2460                // so all of the view state is set up correctly.
2461                if (hasWindowFocus) {
2462                    if (imm != null && mLastWasImTarget) {
2463                        imm.onWindowFocus(mView, mView.findFocus(),
2464                                mWindowAttributes.softInputMode,
2465                                !mHasHadWindowFocus, mWindowAttributes.flags);
2466                    }
2467                    // Clear the forward bit.  We can just do this directly, since
2468                    // the window manager doesn't care about it.
2469                    mWindowAttributes.softInputMode &=
2470                            ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2471                    ((WindowManager.LayoutParams)mView.getLayoutParams())
2472                            .softInputMode &=
2473                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2474                    mHasHadWindowFocus = true;
2475                }
2476
2477                if (hasWindowFocus && mView != null) {
2478                    sendAccessibilityEvents();
2479                }
2480            }
2481        } break;
2482        case DIE:
2483            doDie();
2484            break;
2485        case DISPATCH_KEY_FROM_IME: {
2486            if (LOCAL_LOGV) Log.v(
2487                TAG, "Dispatching key "
2488                + msg.obj + " from IME to " + mView);
2489            KeyEvent event = (KeyEvent)msg.obj;
2490            if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2491                // The IME is trying to say this event is from the
2492                // system!  Bad bad bad!
2493                //noinspection UnusedAssignment
2494                event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
2495            }
2496            deliverKeyEventPostIme((KeyEvent)msg.obj, false);
2497        } break;
2498        case FINISH_INPUT_CONNECTION: {
2499            InputMethodManager imm = InputMethodManager.peekInstance();
2500            if (imm != null) {
2501                imm.reportFinishInputConnection((InputConnection)msg.obj);
2502            }
2503        } break;
2504        case CHECK_FOCUS: {
2505            InputMethodManager imm = InputMethodManager.peekInstance();
2506            if (imm != null) {
2507                imm.checkFocus();
2508            }
2509        } break;
2510        case CLOSE_SYSTEM_DIALOGS: {
2511            if (mView != null) {
2512                mView.onCloseSystemDialogs((String)msg.obj);
2513            }
2514        } break;
2515        case DISPATCH_DRAG_EVENT:
2516        case DISPATCH_DRAG_LOCATION_EVENT: {
2517            DragEvent event = (DragEvent)msg.obj;
2518            event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
2519            handleDragEvent(event);
2520        } break;
2521        case DISPATCH_SYSTEM_UI_VISIBILITY: {
2522            handleDispatchSystemUiVisibilityChanged(msg.arg1);
2523        } break;
2524        case UPDATE_CONFIGURATION: {
2525            Configuration config = (Configuration)msg.obj;
2526            if (config.isOtherSeqNewer(mLastConfiguration)) {
2527                config = mLastConfiguration;
2528            }
2529            updateConfiguration(config, false);
2530        } break;
2531        case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID: {
2532            if (mView != null) {
2533                getAccessibilityInteractionController()
2534                    .findAccessibilityNodeInfoByAccessibilityIdUiThread(msg);
2535            }
2536        } break;
2537        case DO_PERFORM_ACCESSIBILITY_ACTION: {
2538            if (mView != null) {
2539                getAccessibilityInteractionController()
2540                    .perfromAccessibilityActionUiThread(msg);
2541            }
2542        } break;
2543        case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID: {
2544            if (mView != null) {
2545                getAccessibilityInteractionController()
2546                    .findAccessibilityNodeInfoByViewIdUiThread(msg);
2547            }
2548        } break;
2549        case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT: {
2550            if (mView != null) {
2551                getAccessibilityInteractionController()
2552                    .findAccessibilityNodeInfosByViewTextUiThread(msg);
2553            }
2554        } break;
2555        }
2556    }
2557
2558    private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
2559        if (mFinishedCallback != null) {
2560            Slog.w(TAG, "Received a new input event from the input queue but there is "
2561                    + "already an unfinished input event in progress.");
2562        }
2563
2564        if (ViewDebug.DEBUG_LATENCY) {
2565            mInputEventReceiveTimeNanos = System.nanoTime();
2566            mInputEventDeliverTimeNanos = 0;
2567            mInputEventDeliverPostImeTimeNanos = 0;
2568        }
2569
2570        mFinishedCallback = finishedCallback;
2571    }
2572
2573    private void finishInputEvent(InputEvent event, boolean handled) {
2574        if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
2575
2576        if (mFinishedCallback == null) {
2577            Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2578                    + "is finished but there is no input event actually in progress.");
2579            return;
2580        }
2581
2582        if (ViewDebug.DEBUG_LATENCY) {
2583            final long now = System.nanoTime();
2584            final long eventTime = event.getEventTimeNano();
2585            final StringBuilder msg = new StringBuilder();
2586            msg.append("Latency: Spent ");
2587            msg.append((now - mInputEventReceiveTimeNanos) * 0.000001f);
2588            msg.append("ms processing ");
2589            if (event instanceof KeyEvent) {
2590                final KeyEvent  keyEvent = (KeyEvent)event;
2591                msg.append("key event, action=");
2592                msg.append(KeyEvent.actionToString(keyEvent.getAction()));
2593            } else {
2594                final MotionEvent motionEvent = (MotionEvent)event;
2595                msg.append("motion event, action=");
2596                msg.append(MotionEvent.actionToString(motionEvent.getAction()));
2597                msg.append(", historySize=");
2598                msg.append(motionEvent.getHistorySize());
2599            }
2600            msg.append(", handled=");
2601            msg.append(handled);
2602            msg.append(", received at +");
2603            msg.append((mInputEventReceiveTimeNanos - eventTime) * 0.000001f);
2604            if (mInputEventDeliverTimeNanos != 0) {
2605                msg.append("ms, delivered at +");
2606                msg.append((mInputEventDeliverTimeNanos - eventTime) * 0.000001f);
2607            }
2608            if (mInputEventDeliverPostImeTimeNanos != 0) {
2609                msg.append("ms, delivered post IME at +");
2610                msg.append((mInputEventDeliverPostImeTimeNanos - eventTime) * 0.000001f);
2611            }
2612            msg.append("ms, finished at +");
2613            msg.append((now - eventTime) * 0.000001f);
2614            msg.append("ms.");
2615            Log.d(TAG, msg.toString());
2616        }
2617
2618        mFinishedCallback.finished(handled);
2619        mFinishedCallback = null;
2620    }
2621
2622    /**
2623     * Something in the current window tells us we need to change the touch mode.  For
2624     * example, we are not in touch mode, and the user touches the screen.
2625     *
2626     * If the touch mode has changed, tell the window manager, and handle it locally.
2627     *
2628     * @param inTouchMode Whether we want to be in touch mode.
2629     * @return True if the touch mode changed and focus changed was changed as a result
2630     */
2631    boolean ensureTouchMode(boolean inTouchMode) {
2632        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2633                + "touch mode is " + mAttachInfo.mInTouchMode);
2634        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2635
2636        // tell the window manager
2637        try {
2638            sWindowSession.setInTouchMode(inTouchMode);
2639        } catch (RemoteException e) {
2640            throw new RuntimeException(e);
2641        }
2642
2643        // handle the change
2644        return ensureTouchModeLocally(inTouchMode);
2645    }
2646
2647    /**
2648     * Ensure that the touch mode for this window is set, and if it is changing,
2649     * take the appropriate action.
2650     * @param inTouchMode Whether we want to be in touch mode.
2651     * @return True if the touch mode changed and focus changed was changed as a result
2652     */
2653    private boolean ensureTouchModeLocally(boolean inTouchMode) {
2654        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2655                + "touch mode is " + mAttachInfo.mInTouchMode);
2656
2657        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2658
2659        mAttachInfo.mInTouchMode = inTouchMode;
2660        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2661
2662        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
2663    }
2664
2665    private boolean enterTouchMode() {
2666        if (mView != null) {
2667            if (mView.hasFocus()) {
2668                // note: not relying on mFocusedView here because this could
2669                // be when the window is first being added, and mFocused isn't
2670                // set yet.
2671                final View focused = mView.findFocus();
2672                if (focused != null && !focused.isFocusableInTouchMode()) {
2673
2674                    final ViewGroup ancestorToTakeFocus =
2675                            findAncestorToTakeFocusInTouchMode(focused);
2676                    if (ancestorToTakeFocus != null) {
2677                        // there is an ancestor that wants focus after its descendants that
2678                        // is focusable in touch mode.. give it focus
2679                        return ancestorToTakeFocus.requestFocus();
2680                    } else {
2681                        // nothing appropriate to have focus in touch mode, clear it out
2682                        mView.unFocus();
2683                        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2684                        mFocusedView = null;
2685                        return true;
2686                    }
2687                }
2688            }
2689        }
2690        return false;
2691    }
2692
2693
2694    /**
2695     * Find an ancestor of focused that wants focus after its descendants and is
2696     * focusable in touch mode.
2697     * @param focused The currently focused view.
2698     * @return An appropriate view, or null if no such view exists.
2699     */
2700    private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2701        ViewParent parent = focused.getParent();
2702        while (parent instanceof ViewGroup) {
2703            final ViewGroup vgParent = (ViewGroup) parent;
2704            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2705                    && vgParent.isFocusableInTouchMode()) {
2706                return vgParent;
2707            }
2708            if (vgParent.isRootNamespace()) {
2709                return null;
2710            } else {
2711                parent = vgParent.getParent();
2712            }
2713        }
2714        return null;
2715    }
2716
2717    private boolean leaveTouchMode() {
2718        if (mView != null) {
2719            if (mView.hasFocus()) {
2720                // i learned the hard way to not trust mFocusedView :)
2721                mFocusedView = mView.findFocus();
2722                if (!(mFocusedView instanceof ViewGroup)) {
2723                    // some view has focus, let it keep it
2724                    return false;
2725                } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2726                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2727                    // some view group has focus, and doesn't prefer its children
2728                    // over itself for focus, so let them keep it.
2729                    return false;
2730                }
2731            }
2732
2733            // find the best view to give focus to in this brave new non-touch-mode
2734            // world
2735            final View focused = focusSearch(null, View.FOCUS_DOWN);
2736            if (focused != null) {
2737                return focused.requestFocus(View.FOCUS_DOWN);
2738            }
2739        }
2740        return false;
2741    }
2742
2743    private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2744        if (ViewDebug.DEBUG_LATENCY) {
2745            mInputEventDeliverTimeNanos = System.nanoTime();
2746        }
2747
2748        final boolean isTouchEvent = event.isTouchEvent();
2749        if (mInputEventConsistencyVerifier != null) {
2750            if (isTouchEvent) {
2751                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
2752            } else {
2753                mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
2754            }
2755        }
2756
2757        // If there is no view, then the event will not be handled.
2758        if (mView == null || !mAdded) {
2759            finishMotionEvent(event, sendDone, false);
2760            return;
2761        }
2762
2763        // Translate the pointer event for compatibility, if needed.
2764        if (mTranslator != null) {
2765            mTranslator.translateEventInScreenToAppWindow(event);
2766        }
2767
2768        // Enter touch mode on down or scroll.
2769        final int action = event.getAction();
2770        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
2771            ensureTouchMode(true);
2772        }
2773
2774        // Offset the scroll position.
2775        if (mCurScrollY != 0) {
2776            event.offsetLocation(0, mCurScrollY);
2777        }
2778        if (MEASURE_LATENCY) {
2779            lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
2780        }
2781
2782        // Remember the touch position for possible drag-initiation.
2783        if (isTouchEvent) {
2784            mLastTouchPoint.x = event.getRawX();
2785            mLastTouchPoint.y = event.getRawY();
2786        }
2787
2788        // Dispatch touch to view hierarchy.
2789        boolean handled = mView.dispatchPointerEvent(event);
2790        if (MEASURE_LATENCY) {
2791            lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
2792        }
2793        if (handled) {
2794            finishMotionEvent(event, sendDone, true);
2795            return;
2796        }
2797
2798        // Pointer event was unhandled.
2799        finishMotionEvent(event, sendDone, false);
2800    }
2801
2802    private void finishMotionEvent(MotionEvent event, boolean sendDone, boolean handled) {
2803        event.recycle();
2804        if (sendDone) {
2805            finishInputEvent(event, handled);
2806        }
2807        //noinspection ConstantConditions
2808        if (LOCAL_LOGV || WATCH_POINTER) {
2809            if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2810                Log.i(TAG, "Done dispatching!");
2811            }
2812        }
2813    }
2814
2815    private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
2816        if (ViewDebug.DEBUG_LATENCY) {
2817            mInputEventDeliverTimeNanos = System.nanoTime();
2818        }
2819
2820        if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2821
2822        if (mInputEventConsistencyVerifier != null) {
2823            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
2824        }
2825
2826        // If there is no view, then the event will not be handled.
2827        if (mView == null || !mAdded) {
2828            finishMotionEvent(event, sendDone, false);
2829            return;
2830        }
2831
2832        // Deliver the trackball event to the view.
2833        if (mView.dispatchTrackballEvent(event)) {
2834            // If we reach this, we delivered a trackball event to mView and
2835            // mView consumed it. Because we will not translate the trackball
2836            // event into a key event, touch mode will not exit, so we exit
2837            // touch mode here.
2838            ensureTouchMode(false);
2839
2840            finishMotionEvent(event, sendDone, true);
2841            mLastTrackballTime = Integer.MIN_VALUE;
2842            return;
2843        }
2844
2845        // Translate the trackball event into DPAD keys and try to deliver those.
2846        final TrackballAxis x = mTrackballAxisX;
2847        final TrackballAxis y = mTrackballAxisY;
2848
2849        long curTime = SystemClock.uptimeMillis();
2850        if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
2851            // It has been too long since the last movement,
2852            // so restart at the beginning.
2853            x.reset(0);
2854            y.reset(0);
2855            mLastTrackballTime = curTime;
2856        }
2857
2858        final int action = event.getAction();
2859        final int metaState = event.getMetaState();
2860        switch (action) {
2861            case MotionEvent.ACTION_DOWN:
2862                x.reset(2);
2863                y.reset(2);
2864                deliverKeyEvent(new KeyEvent(curTime, curTime,
2865                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2866                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2867                        InputDevice.SOURCE_KEYBOARD), false);
2868                break;
2869            case MotionEvent.ACTION_UP:
2870                x.reset(2);
2871                y.reset(2);
2872                deliverKeyEvent(new KeyEvent(curTime, curTime,
2873                        KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2874                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2875                        InputDevice.SOURCE_KEYBOARD), false);
2876                break;
2877        }
2878
2879        if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2880                + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2881                + " move=" + event.getX()
2882                + " / Y=" + y.position + " step="
2883                + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2884                + " move=" + event.getY());
2885        final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2886        final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2887
2888        // Generate DPAD events based on the trackball movement.
2889        // We pick the axis that has moved the most as the direction of
2890        // the DPAD.  When we generate DPAD events for one axis, then the
2891        // other axis is reset -- we don't want to perform DPAD jumps due
2892        // to slight movements in the trackball when making major movements
2893        // along the other axis.
2894        int keycode = 0;
2895        int movement = 0;
2896        float accel = 1;
2897        if (xOff > yOff) {
2898            movement = x.generate((2/event.getXPrecision()));
2899            if (movement != 0) {
2900                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2901                        : KeyEvent.KEYCODE_DPAD_LEFT;
2902                accel = x.acceleration;
2903                y.reset(2);
2904            }
2905        } else if (yOff > 0) {
2906            movement = y.generate((2/event.getYPrecision()));
2907            if (movement != 0) {
2908                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2909                        : KeyEvent.KEYCODE_DPAD_UP;
2910                accel = y.acceleration;
2911                x.reset(2);
2912            }
2913        }
2914
2915        if (keycode != 0) {
2916            if (movement < 0) movement = -movement;
2917            int accelMovement = (int)(movement * accel);
2918            if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2919                    + " accelMovement=" + accelMovement
2920                    + " accel=" + accel);
2921            if (accelMovement > movement) {
2922                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2923                        + keycode);
2924                movement--;
2925                int repeatCount = accelMovement - movement;
2926                deliverKeyEvent(new KeyEvent(curTime, curTime,
2927                        KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2928                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2929                        InputDevice.SOURCE_KEYBOARD), false);
2930            }
2931            while (movement > 0) {
2932                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2933                        + keycode);
2934                movement--;
2935                curTime = SystemClock.uptimeMillis();
2936                deliverKeyEvent(new KeyEvent(curTime, curTime,
2937                        KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2938                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2939                        InputDevice.SOURCE_KEYBOARD), false);
2940                deliverKeyEvent(new KeyEvent(curTime, curTime,
2941                        KeyEvent.ACTION_UP, keycode, 0, metaState,
2942                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2943                        InputDevice.SOURCE_KEYBOARD), false);
2944                }
2945            mLastTrackballTime = curTime;
2946        }
2947
2948        // Unfortunately we can't tell whether the application consumed the keys, so
2949        // we always consider the trackball event handled.
2950        finishMotionEvent(event, sendDone, true);
2951    }
2952
2953    private void deliverGenericMotionEvent(MotionEvent event, boolean sendDone) {
2954        if (ViewDebug.DEBUG_LATENCY) {
2955            mInputEventDeliverTimeNanos = System.nanoTime();
2956        }
2957
2958        if (mInputEventConsistencyVerifier != null) {
2959            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
2960        }
2961
2962        final int source = event.getSource();
2963        final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
2964
2965        // If there is no view, then the event will not be handled.
2966        if (mView == null || !mAdded) {
2967            if (isJoystick) {
2968                updateJoystickDirection(event, false);
2969            }
2970            finishMotionEvent(event, sendDone, false);
2971            return;
2972        }
2973
2974        // Deliver the event to the view.
2975        if (mView.dispatchGenericMotionEvent(event)) {
2976            if (isJoystick) {
2977                updateJoystickDirection(event, false);
2978            }
2979            finishMotionEvent(event, sendDone, true);
2980            return;
2981        }
2982
2983        if (isJoystick) {
2984            // Translate the joystick event into DPAD keys and try to deliver those.
2985            updateJoystickDirection(event, true);
2986            finishMotionEvent(event, sendDone, true);
2987        } else {
2988            finishMotionEvent(event, sendDone, false);
2989        }
2990    }
2991
2992    private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
2993        final long time = event.getEventTime();
2994        final int metaState = event.getMetaState();
2995        final int deviceId = event.getDeviceId();
2996        final int source = event.getSource();
2997
2998        int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
2999        if (xDirection == 0) {
3000            xDirection = joystickAxisValueToDirection(event.getX());
3001        }
3002
3003        int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
3004        if (yDirection == 0) {
3005            yDirection = joystickAxisValueToDirection(event.getY());
3006        }
3007
3008        if (xDirection != mLastJoystickXDirection) {
3009            if (mLastJoystickXKeyCode != 0) {
3010                deliverKeyEvent(new KeyEvent(time, time,
3011                        KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
3012                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
3013                mLastJoystickXKeyCode = 0;
3014            }
3015
3016            mLastJoystickXDirection = xDirection;
3017
3018            if (xDirection != 0 && synthesizeNewKeys) {
3019                mLastJoystickXKeyCode = xDirection > 0
3020                        ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3021                deliverKeyEvent(new KeyEvent(time, time,
3022                        KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3023                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
3024            }
3025        }
3026
3027        if (yDirection != mLastJoystickYDirection) {
3028            if (mLastJoystickYKeyCode != 0) {
3029                deliverKeyEvent(new KeyEvent(time, time,
3030                        KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3031                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
3032                mLastJoystickYKeyCode = 0;
3033            }
3034
3035            mLastJoystickYDirection = yDirection;
3036
3037            if (yDirection != 0 && synthesizeNewKeys) {
3038                mLastJoystickYKeyCode = yDirection > 0
3039                        ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3040                deliverKeyEvent(new KeyEvent(time, time,
3041                        KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3042                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
3043            }
3044        }
3045    }
3046
3047    private static int joystickAxisValueToDirection(float value) {
3048        if (value >= 0.5f) {
3049            return 1;
3050        } else if (value <= -0.5f) {
3051            return -1;
3052        } else {
3053            return 0;
3054        }
3055    }
3056
3057    /**
3058     * Returns true if the key is used for keyboard navigation.
3059     * @param keyEvent The key event.
3060     * @return True if the key is used for keyboard navigation.
3061     */
3062    private static boolean isNavigationKey(KeyEvent keyEvent) {
3063        switch (keyEvent.getKeyCode()) {
3064        case KeyEvent.KEYCODE_DPAD_LEFT:
3065        case KeyEvent.KEYCODE_DPAD_RIGHT:
3066        case KeyEvent.KEYCODE_DPAD_UP:
3067        case KeyEvent.KEYCODE_DPAD_DOWN:
3068        case KeyEvent.KEYCODE_DPAD_CENTER:
3069        case KeyEvent.KEYCODE_PAGE_UP:
3070        case KeyEvent.KEYCODE_PAGE_DOWN:
3071        case KeyEvent.KEYCODE_MOVE_HOME:
3072        case KeyEvent.KEYCODE_MOVE_END:
3073        case KeyEvent.KEYCODE_TAB:
3074        case KeyEvent.KEYCODE_SPACE:
3075        case KeyEvent.KEYCODE_ENTER:
3076            return true;
3077        }
3078        return false;
3079    }
3080
3081    /**
3082     * Returns true if the key is used for typing.
3083     * @param keyEvent The key event.
3084     * @return True if the key is used for typing.
3085     */
3086    private static boolean isTypingKey(KeyEvent keyEvent) {
3087        return keyEvent.getUnicodeChar() > 0;
3088    }
3089
3090    /**
3091     * See if the key event means we should leave touch mode (and leave touch mode if so).
3092     * @param event The key event.
3093     * @return Whether this key event should be consumed (meaning the act of
3094     *   leaving touch mode alone is considered the event).
3095     */
3096    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3097        // Only relevant in touch mode.
3098        if (!mAttachInfo.mInTouchMode) {
3099            return false;
3100        }
3101
3102        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3103        final int action = event.getAction();
3104        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3105            return false;
3106        }
3107
3108        // Don't leave touch mode if the IME told us not to.
3109        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3110            return false;
3111        }
3112
3113        // If the key can be used for keyboard navigation then leave touch mode
3114        // and select a focused view if needed (in ensureTouchMode).
3115        // When a new focused view is selected, we consume the navigation key because
3116        // navigation doesn't make much sense unless a view already has focus so
3117        // the key's purpose is to set focus.
3118        if (isNavigationKey(event)) {
3119            return ensureTouchMode(false);
3120        }
3121
3122        // If the key can be used for typing then leave touch mode
3123        // and select a focused view if needed (in ensureTouchMode).
3124        // Always allow the view to process the typing key.
3125        if (isTypingKey(event)) {
3126            ensureTouchMode(false);
3127            return false;
3128        }
3129
3130        return false;
3131    }
3132
3133    int enqueuePendingEvent(Object event, boolean sendDone) {
3134        int seq = mPendingEventSeq+1;
3135        if (seq < 0) seq = 0;
3136        mPendingEventSeq = seq;
3137        mPendingEvents.put(seq, event);
3138        return sendDone ? seq : -seq;
3139    }
3140
3141    Object retrievePendingEvent(int seq) {
3142        if (seq < 0) seq = -seq;
3143        Object event = mPendingEvents.get(seq);
3144        if (event != null) {
3145            mPendingEvents.remove(seq);
3146        }
3147        return event;
3148    }
3149
3150    private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
3151        if (ViewDebug.DEBUG_LATENCY) {
3152            mInputEventDeliverTimeNanos = System.nanoTime();
3153        }
3154
3155        if (mInputEventConsistencyVerifier != null) {
3156            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3157        }
3158
3159        // If there is no view, then the event will not be handled.
3160        if (mView == null || !mAdded) {
3161            finishKeyEvent(event, sendDone, false);
3162            return;
3163        }
3164
3165        if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3166
3167        // Perform predispatching before the IME.
3168        if (mView.dispatchKeyEventPreIme(event)) {
3169            finishKeyEvent(event, sendDone, true);
3170            return;
3171        }
3172
3173        // Dispatch to the IME before propagating down the view hierarchy.
3174        // The IME will eventually call back into handleFinishedEvent.
3175        if (mLastWasImTarget) {
3176            InputMethodManager imm = InputMethodManager.peekInstance();
3177            if (imm != null) {
3178                int seq = enqueuePendingEvent(event, sendDone);
3179                if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3180                        + seq + " event=" + event);
3181                imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
3182                return;
3183            }
3184        }
3185
3186        // Not dispatching to IME, continue with post IME actions.
3187        deliverKeyEventPostIme(event, sendDone);
3188    }
3189
3190    private void handleFinishedEvent(int seq, boolean handled) {
3191        final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
3192        if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
3193                + " handled=" + handled + " event=" + event);
3194        if (event != null) {
3195            final boolean sendDone = seq >= 0;
3196            if (handled) {
3197                finishKeyEvent(event, sendDone, true);
3198            } else {
3199                deliverKeyEventPostIme(event, sendDone);
3200            }
3201        }
3202    }
3203
3204    private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
3205        if (ViewDebug.DEBUG_LATENCY) {
3206            mInputEventDeliverPostImeTimeNanos = System.nanoTime();
3207        }
3208
3209        // If the view went away, then the event will not be handled.
3210        if (mView == null || !mAdded) {
3211            finishKeyEvent(event, sendDone, false);
3212            return;
3213        }
3214
3215        // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3216        if (checkForLeavingTouchModeAndConsume(event)) {
3217            finishKeyEvent(event, sendDone, true);
3218            return;
3219        }
3220
3221        // Make sure the fallback event policy sees all keys that will be delivered to the
3222        // view hierarchy.
3223        mFallbackEventHandler.preDispatchKeyEvent(event);
3224
3225        // Deliver the key to the view hierarchy.
3226        if (mView.dispatchKeyEvent(event)) {
3227            finishKeyEvent(event, sendDone, true);
3228            return;
3229        }
3230
3231        // If the Control modifier is held, try to interpret the key as a shortcut.
3232        if (event.getAction() == KeyEvent.ACTION_UP
3233                && event.isCtrlPressed()
3234                && !KeyEvent.isModifierKey(event.getKeyCode())) {
3235            if (mView.dispatchKeyShortcutEvent(event)) {
3236                finishKeyEvent(event, sendDone, true);
3237                return;
3238            }
3239        }
3240
3241        // Apply the fallback event policy.
3242        if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3243            finishKeyEvent(event, sendDone, true);
3244            return;
3245        }
3246
3247        // Handle automatic focus changes.
3248        if (event.getAction() == KeyEvent.ACTION_DOWN) {
3249            int direction = 0;
3250            switch (event.getKeyCode()) {
3251            case KeyEvent.KEYCODE_DPAD_LEFT:
3252                if (event.hasNoModifiers()) {
3253                    direction = View.FOCUS_LEFT;
3254                }
3255                break;
3256            case KeyEvent.KEYCODE_DPAD_RIGHT:
3257                if (event.hasNoModifiers()) {
3258                    direction = View.FOCUS_RIGHT;
3259                }
3260                break;
3261            case KeyEvent.KEYCODE_DPAD_UP:
3262                if (event.hasNoModifiers()) {
3263                    direction = View.FOCUS_UP;
3264                }
3265                break;
3266            case KeyEvent.KEYCODE_DPAD_DOWN:
3267                if (event.hasNoModifiers()) {
3268                    direction = View.FOCUS_DOWN;
3269                }
3270                break;
3271            case KeyEvent.KEYCODE_TAB:
3272                if (event.hasNoModifiers()) {
3273                    direction = View.FOCUS_FORWARD;
3274                } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3275                    direction = View.FOCUS_BACKWARD;
3276                }
3277                break;
3278            }
3279
3280            if (direction != 0) {
3281                View focused = mView != null ? mView.findFocus() : null;
3282                if (focused != null) {
3283                    View v = focused.focusSearch(direction);
3284                    if (v != null && v != focused) {
3285                        // do the math the get the interesting rect
3286                        // of previous focused into the coord system of
3287                        // newly focused view
3288                        focused.getFocusedRect(mTempRect);
3289                        if (mView instanceof ViewGroup) {
3290                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3291                                    focused, mTempRect);
3292                            ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3293                                    v, mTempRect);
3294                        }
3295                        if (v.requestFocus(direction, mTempRect)) {
3296                            playSoundEffect(
3297                                    SoundEffectConstants.getContantForFocusDirection(direction));
3298                            finishKeyEvent(event, sendDone, true);
3299                            return;
3300                        }
3301                    }
3302
3303                    // Give the focused view a last chance to handle the dpad key.
3304                    if (mView.dispatchUnhandledMove(focused, direction)) {
3305                        finishKeyEvent(event, sendDone, true);
3306                        return;
3307                    }
3308                }
3309            }
3310        }
3311
3312        // Key was unhandled.
3313        finishKeyEvent(event, sendDone, false);
3314    }
3315
3316    private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
3317        if (sendDone) {
3318            finishInputEvent(event, handled);
3319        }
3320    }
3321
3322    /* drag/drop */
3323    void setLocalDragState(Object obj) {
3324        mLocalDragState = obj;
3325    }
3326
3327    private void handleDragEvent(DragEvent event) {
3328        // From the root, only drag start/end/location are dispatched.  entered/exited
3329        // are determined and dispatched by the viewgroup hierarchy, who then report
3330        // that back here for ultimate reporting back to the framework.
3331        if (mView != null && mAdded) {
3332            final int what = event.mAction;
3333
3334            if (what == DragEvent.ACTION_DRAG_EXITED) {
3335                // A direct EXITED event means that the window manager knows we've just crossed
3336                // a window boundary, so the current drag target within this one must have
3337                // just been exited.  Send it the usual notifications and then we're done
3338                // for now.
3339                mView.dispatchDragEvent(event);
3340            } else {
3341                // Cache the drag description when the operation starts, then fill it in
3342                // on subsequent calls as a convenience
3343                if (what == DragEvent.ACTION_DRAG_STARTED) {
3344                    mCurrentDragView = null;    // Start the current-recipient tracking
3345                    mDragDescription = event.mClipDescription;
3346                } else {
3347                    event.mClipDescription = mDragDescription;
3348                }
3349
3350                // For events with a [screen] location, translate into window coordinates
3351                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3352                    mDragPoint.set(event.mX, event.mY);
3353                    if (mTranslator != null) {
3354                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3355                    }
3356
3357                    if (mCurScrollY != 0) {
3358                        mDragPoint.offset(0, mCurScrollY);
3359                    }
3360
3361                    event.mX = mDragPoint.x;
3362                    event.mY = mDragPoint.y;
3363                }
3364
3365                // Remember who the current drag target is pre-dispatch
3366                final View prevDragView = mCurrentDragView;
3367
3368                // Now dispatch the drag/drop event
3369                boolean result = mView.dispatchDragEvent(event);
3370
3371                // If we changed apparent drag target, tell the OS about it
3372                if (prevDragView != mCurrentDragView) {
3373                    try {
3374                        if (prevDragView != null) {
3375                            sWindowSession.dragRecipientExited(mWindow);
3376                        }
3377                        if (mCurrentDragView != null) {
3378                            sWindowSession.dragRecipientEntered(mWindow);
3379                        }
3380                    } catch (RemoteException e) {
3381                        Slog.e(TAG, "Unable to note drag target change");
3382                    }
3383                }
3384
3385                // Report the drop result when we're done
3386                if (what == DragEvent.ACTION_DROP) {
3387                    mDragDescription = null;
3388                    try {
3389                        Log.i(TAG, "Reporting drop result: " + result);
3390                        sWindowSession.reportDropResult(mWindow, result);
3391                    } catch (RemoteException e) {
3392                        Log.e(TAG, "Unable to report drop result");
3393                    }
3394                }
3395
3396                // When the drag operation ends, release any local state object
3397                // that may have been in use
3398                if (what == DragEvent.ACTION_DRAG_ENDED) {
3399                    setLocalDragState(null);
3400                }
3401            }
3402        }
3403        event.recycle();
3404    }
3405
3406    public void handleDispatchSystemUiVisibilityChanged(int visibility) {
3407        if (mView == null) return;
3408        if (mAttachInfo != null) {
3409            mAttachInfo.mSystemUiVisibility = visibility;
3410        }
3411        mView.dispatchSystemUiVisibilityChanged(visibility);
3412    }
3413
3414    public void getLastTouchPoint(Point outLocation) {
3415        outLocation.x = (int) mLastTouchPoint.x;
3416        outLocation.y = (int) mLastTouchPoint.y;
3417    }
3418
3419    public void setDragFocus(View newDragTarget) {
3420        if (mCurrentDragView != newDragTarget) {
3421            mCurrentDragView = newDragTarget;
3422        }
3423    }
3424
3425    private AudioManager getAudioManager() {
3426        if (mView == null) {
3427            throw new IllegalStateException("getAudioManager called when there is no mView");
3428        }
3429        if (mAudioManager == null) {
3430            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3431        }
3432        return mAudioManager;
3433    }
3434
3435    public AccessibilityInteractionController getAccessibilityInteractionController() {
3436        if (mView == null) {
3437            throw new IllegalStateException("getAccessibilityInteractionController"
3438                    + " called when there is no mView");
3439        }
3440        if (mAccessibilityInteractionContrtoller == null) {
3441            mAccessibilityInteractionContrtoller = new AccessibilityInteractionController();
3442        }
3443        return mAccessibilityInteractionContrtoller;
3444    }
3445
3446    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3447            boolean insetsPending) throws RemoteException {
3448
3449        float appScale = mAttachInfo.mApplicationScale;
3450        boolean restore = false;
3451        if (params != null && mTranslator != null) {
3452            restore = true;
3453            params.backup();
3454            mTranslator.translateWindowLayout(params);
3455        }
3456        if (params != null) {
3457            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
3458        }
3459        mPendingConfiguration.seq = 0;
3460        //Log.d(TAG, ">>>>>> CALLING relayout");
3461        int relayoutResult = sWindowSession.relayout(
3462                mWindow, params,
3463                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3464                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
3465                viewVisibility, insetsPending, mWinFrame,
3466                mPendingContentInsets, mPendingVisibleInsets,
3467                mPendingConfiguration, mSurface);
3468        //Log.d(TAG, "<<<<<< BACK FROM relayout");
3469        if (restore) {
3470            params.restore();
3471        }
3472
3473        if (mTranslator != null) {
3474            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3475            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3476            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
3477        }
3478        return relayoutResult;
3479    }
3480
3481    /**
3482     * {@inheritDoc}
3483     */
3484    public void playSoundEffect(int effectId) {
3485        checkThread();
3486
3487        try {
3488            final AudioManager audioManager = getAudioManager();
3489
3490            switch (effectId) {
3491                case SoundEffectConstants.CLICK:
3492                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3493                    return;
3494                case SoundEffectConstants.NAVIGATION_DOWN:
3495                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3496                    return;
3497                case SoundEffectConstants.NAVIGATION_LEFT:
3498                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3499                    return;
3500                case SoundEffectConstants.NAVIGATION_RIGHT:
3501                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3502                    return;
3503                case SoundEffectConstants.NAVIGATION_UP:
3504                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3505                    return;
3506                default:
3507                    throw new IllegalArgumentException("unknown effect id " + effectId +
3508                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
3509            }
3510        } catch (IllegalStateException e) {
3511            // Exception thrown by getAudioManager() when mView is null
3512            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3513            e.printStackTrace();
3514        }
3515    }
3516
3517    /**
3518     * {@inheritDoc}
3519     */
3520    public boolean performHapticFeedback(int effectId, boolean always) {
3521        try {
3522            return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3523        } catch (RemoteException e) {
3524            return false;
3525        }
3526    }
3527
3528    /**
3529     * {@inheritDoc}
3530     */
3531    public View focusSearch(View focused, int direction) {
3532        checkThread();
3533        if (!(mView instanceof ViewGroup)) {
3534            return null;
3535        }
3536        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3537    }
3538
3539    public void debug() {
3540        mView.debug();
3541    }
3542
3543    public void dumpGfxInfo(PrintWriter pw, int[] info) {
3544        if (mView != null) {
3545            getGfxInfo(mView, info);
3546        } else {
3547            info[0] = info[1] = 0;
3548        }
3549    }
3550
3551    private void getGfxInfo(View view, int[] info) {
3552        DisplayList displayList = view.mDisplayList;
3553        info[0]++;
3554        if (displayList != null) {
3555            info[1] += displayList.getSize();
3556        }
3557
3558        if (view instanceof ViewGroup) {
3559            ViewGroup group = (ViewGroup) view;
3560
3561            int count = group.getChildCount();
3562            for (int i = 0; i < count; i++) {
3563                getGfxInfo(group.getChildAt(i), info);
3564            }
3565        }
3566    }
3567
3568    public void die(boolean immediate) {
3569        if (immediate) {
3570            doDie();
3571        } else {
3572            sendEmptyMessage(DIE);
3573        }
3574    }
3575
3576    void doDie() {
3577        checkThread();
3578        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
3579        synchronized (this) {
3580            if (mAdded) {
3581                mAdded = false;
3582                dispatchDetachedFromWindow();
3583            }
3584
3585            if (mAdded && !mFirst) {
3586                destroyHardwareRenderer();
3587
3588                int viewVisibility = mView.getVisibility();
3589                boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3590                if (mWindowAttributesChanged || viewVisibilityChanged) {
3591                    // If layout params have been changed, first give them
3592                    // to the window manager to make sure it has the correct
3593                    // animation info.
3594                    try {
3595                        if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3596                                & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
3597                            sWindowSession.finishDrawing(mWindow);
3598                        }
3599                    } catch (RemoteException e) {
3600                    }
3601                }
3602
3603                mSurface.release();
3604            }
3605        }
3606    }
3607
3608    public void requestUpdateConfiguration(Configuration config) {
3609        Message msg = obtainMessage(UPDATE_CONFIGURATION, config);
3610        sendMessage(msg);
3611    }
3612
3613    private void destroyHardwareRenderer() {
3614        if (mAttachInfo.mHardwareRenderer != null) {
3615            mAttachInfo.mHardwareRenderer.destroy(true);
3616            mAttachInfo.mHardwareRenderer = null;
3617            mAttachInfo.mHardwareAccelerated = false;
3618        }
3619    }
3620
3621    public void dispatchFinishedEvent(int seq, boolean handled) {
3622        Message msg = obtainMessage(FINISHED_EVENT);
3623        msg.arg1 = seq;
3624        msg.arg2 = handled ? 1 : 0;
3625        sendMessage(msg);
3626    }
3627
3628    public void dispatchResized(int w, int h, Rect coveredInsets,
3629            Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
3630        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3631                + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3632                + " visibleInsets=" + visibleInsets.toShortString()
3633                + " reportDraw=" + reportDraw);
3634        Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
3635        if (mTranslator != null) {
3636            mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3637            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3638            w *= mTranslator.applicationInvertedScale;
3639            h *= mTranslator.applicationInvertedScale;
3640        }
3641        msg.arg1 = w;
3642        msg.arg2 = h;
3643        ResizedInfo ri = new ResizedInfo();
3644        ri.coveredInsets = new Rect(coveredInsets);
3645        ri.visibleInsets = new Rect(visibleInsets);
3646        ri.newConfig = newConfig;
3647        msg.obj = ri;
3648        sendMessage(msg);
3649    }
3650
3651    private long mInputEventReceiveTimeNanos;
3652    private long mInputEventDeliverTimeNanos;
3653    private long mInputEventDeliverPostImeTimeNanos;
3654    private InputQueue.FinishedCallback mFinishedCallback;
3655
3656    private final InputHandler mInputHandler = new InputHandler() {
3657        public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
3658            startInputEvent(finishedCallback);
3659            dispatchKey(event, true);
3660        }
3661
3662        public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
3663            startInputEvent(finishedCallback);
3664            dispatchMotion(event, true);
3665        }
3666    };
3667
3668    public void dispatchKey(KeyEvent event) {
3669        dispatchKey(event, false);
3670    }
3671
3672    private void dispatchKey(KeyEvent event, boolean sendDone) {
3673        //noinspection ConstantConditions
3674        if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3675            if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
3676                if (DBG) Log.d("keydisp", "===================================================");
3677                if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3678
3679                debug();
3680
3681                if (DBG) Log.d("keydisp", "===================================================");
3682            }
3683        }
3684
3685        Message msg = obtainMessage(DISPATCH_KEY);
3686        msg.obj = event;
3687        msg.arg1 = sendDone ? 1 : 0;
3688
3689        if (LOCAL_LOGV) Log.v(
3690            TAG, "sending key " + event + " to " + mView);
3691
3692        sendMessageAtTime(msg, event.getEventTime());
3693    }
3694
3695    private void dispatchMotion(MotionEvent event, boolean sendDone) {
3696        int source = event.getSource();
3697        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3698            dispatchPointer(event, sendDone);
3699        } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3700            dispatchTrackball(event, sendDone);
3701        } else {
3702            dispatchGenericMotion(event, sendDone);
3703        }
3704    }
3705
3706    private void dispatchPointer(MotionEvent event, boolean sendDone) {
3707        Message msg = obtainMessage(DISPATCH_POINTER);
3708        msg.obj = event;
3709        msg.arg1 = sendDone ? 1 : 0;
3710        sendMessageAtTime(msg, event.getEventTime());
3711    }
3712
3713    private void dispatchTrackball(MotionEvent event, boolean sendDone) {
3714        Message msg = obtainMessage(DISPATCH_TRACKBALL);
3715        msg.obj = event;
3716        msg.arg1 = sendDone ? 1 : 0;
3717        sendMessageAtTime(msg, event.getEventTime());
3718    }
3719
3720    private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
3721        Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
3722        msg.obj = event;
3723        msg.arg1 = sendDone ? 1 : 0;
3724        sendMessageAtTime(msg, event.getEventTime());
3725    }
3726
3727    public void dispatchAppVisibility(boolean visible) {
3728        Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3729        msg.arg1 = visible ? 1 : 0;
3730        sendMessage(msg);
3731    }
3732
3733    public void dispatchGetNewSurface() {
3734        Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3735        sendMessage(msg);
3736    }
3737
3738    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3739        Message msg = Message.obtain();
3740        msg.what = WINDOW_FOCUS_CHANGED;
3741        msg.arg1 = hasFocus ? 1 : 0;
3742        msg.arg2 = inTouchMode ? 1 : 0;
3743        sendMessage(msg);
3744    }
3745
3746    public void dispatchCloseSystemDialogs(String reason) {
3747        Message msg = Message.obtain();
3748        msg.what = CLOSE_SYSTEM_DIALOGS;
3749        msg.obj = reason;
3750        sendMessage(msg);
3751    }
3752
3753    public void dispatchDragEvent(DragEvent event) {
3754        final int what;
3755        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3756            what = DISPATCH_DRAG_LOCATION_EVENT;
3757            removeMessages(what);
3758        } else {
3759            what = DISPATCH_DRAG_EVENT;
3760        }
3761        Message msg = obtainMessage(what, event);
3762        sendMessage(msg);
3763    }
3764
3765    public void dispatchSystemUiVisibilityChanged(int visibility) {
3766        sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3767    }
3768
3769    /**
3770     * The window is getting focus so if there is anything focused/selected
3771     * send an {@link AccessibilityEvent} to announce that.
3772     */
3773    private void sendAccessibilityEvents() {
3774        if (!mAccessibilityManager.isEnabled()) {
3775            return;
3776        }
3777        mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3778        View focusedView = mView.findFocus();
3779        if (focusedView != null && focusedView != mView) {
3780            focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3781        }
3782    }
3783
3784    /**
3785     * Post a callback to send a
3786     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
3787     * This event is send at most once every
3788     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
3789     */
3790    private void postSendWindowContentChangedCallback() {
3791        if (mSendWindowContentChangedAccessibilityEvent == null) {
3792            mSendWindowContentChangedAccessibilityEvent =
3793                new SendWindowContentChangedAccessibilityEvent();
3794        }
3795        if (!mSendWindowContentChangedAccessibilityEvent.mIsPending) {
3796            mSendWindowContentChangedAccessibilityEvent.mIsPending = true;
3797            postDelayed(mSendWindowContentChangedAccessibilityEvent,
3798                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
3799        }
3800    }
3801
3802    /**
3803     * Remove a posted callback to send a
3804     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
3805     */
3806    private void removeSendWindowContentChangedCallback() {
3807        if (mSendWindowContentChangedAccessibilityEvent != null) {
3808            removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
3809        }
3810    }
3811
3812    public boolean showContextMenuForChild(View originalView) {
3813        return false;
3814    }
3815
3816    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3817        return null;
3818    }
3819
3820    public void createContextMenu(ContextMenu menu) {
3821    }
3822
3823    public void childDrawableStateChanged(View child) {
3824    }
3825
3826    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
3827        if (mView == null) {
3828            return false;
3829        }
3830        mAccessibilityManager.sendAccessibilityEvent(event);
3831        return true;
3832    }
3833
3834    void checkThread() {
3835        if (mThread != Thread.currentThread()) {
3836            throw new CalledFromWrongThreadException(
3837                    "Only the original thread that created a view hierarchy can touch its views.");
3838        }
3839    }
3840
3841    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3842        // ViewAncestor never intercepts touch event, so this can be a no-op
3843    }
3844
3845    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3846            boolean immediate) {
3847        return scrollToRectOrFocus(rectangle, immediate);
3848    }
3849
3850    class TakenSurfaceHolder extends BaseSurfaceHolder {
3851        @Override
3852        public boolean onAllowLockCanvas() {
3853            return mDrawingAllowed;
3854        }
3855
3856        @Override
3857        public void onRelayoutContainer() {
3858            // Not currently interesting -- from changing between fixed and layout size.
3859        }
3860
3861        public void setFormat(int format) {
3862            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3863        }
3864
3865        public void setType(int type) {
3866            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3867        }
3868
3869        @Override
3870        public void onUpdateSurface() {
3871            // We take care of format and type changes on our own.
3872            throw new IllegalStateException("Shouldn't be here");
3873        }
3874
3875        public boolean isCreating() {
3876            return mIsCreating;
3877        }
3878
3879        @Override
3880        public void setFixedSize(int width, int height) {
3881            throw new UnsupportedOperationException(
3882                    "Currently only support sizing from layout");
3883        }
3884
3885        public void setKeepScreenOn(boolean screenOn) {
3886            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3887        }
3888    }
3889
3890    static class InputMethodCallback extends IInputMethodCallback.Stub {
3891        private WeakReference<ViewRootImpl> mViewAncestor;
3892
3893        public InputMethodCallback(ViewRootImpl viewAncestor) {
3894            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
3895        }
3896
3897        public void finishedEvent(int seq, boolean handled) {
3898            final ViewRootImpl viewAncestor = mViewAncestor.get();
3899            if (viewAncestor != null) {
3900                viewAncestor.dispatchFinishedEvent(seq, handled);
3901            }
3902        }
3903
3904        public void sessionCreated(IInputMethodSession session) {
3905            // Stub -- not for use in the client.
3906        }
3907    }
3908
3909    static class W extends IWindow.Stub {
3910        private final WeakReference<ViewRootImpl> mViewAncestor;
3911
3912        W(ViewRootImpl viewAncestor) {
3913            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
3914        }
3915
3916        public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3917                boolean reportDraw, Configuration newConfig) {
3918            final ViewRootImpl viewAncestor = mViewAncestor.get();
3919            if (viewAncestor != null) {
3920                viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw,
3921                        newConfig);
3922            }
3923        }
3924
3925        public void dispatchAppVisibility(boolean visible) {
3926            final ViewRootImpl viewAncestor = mViewAncestor.get();
3927            if (viewAncestor != null) {
3928                viewAncestor.dispatchAppVisibility(visible);
3929            }
3930        }
3931
3932        public void dispatchGetNewSurface() {
3933            final ViewRootImpl viewAncestor = mViewAncestor.get();
3934            if (viewAncestor != null) {
3935                viewAncestor.dispatchGetNewSurface();
3936            }
3937        }
3938
3939        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3940            final ViewRootImpl viewAncestor = mViewAncestor.get();
3941            if (viewAncestor != null) {
3942                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
3943            }
3944        }
3945
3946        private static int checkCallingPermission(String permission) {
3947            try {
3948                return ActivityManagerNative.getDefault().checkPermission(
3949                        permission, Binder.getCallingPid(), Binder.getCallingUid());
3950            } catch (RemoteException e) {
3951                return PackageManager.PERMISSION_DENIED;
3952            }
3953        }
3954
3955        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3956            final ViewRootImpl viewAncestor = mViewAncestor.get();
3957            if (viewAncestor != null) {
3958                final View view = viewAncestor.mView;
3959                if (view != null) {
3960                    if (checkCallingPermission(Manifest.permission.DUMP) !=
3961                            PackageManager.PERMISSION_GRANTED) {
3962                        throw new SecurityException("Insufficient permissions to invoke"
3963                                + " executeCommand() from pid=" + Binder.getCallingPid()
3964                                + ", uid=" + Binder.getCallingUid());
3965                    }
3966
3967                    OutputStream clientStream = null;
3968                    try {
3969                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3970                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3971                    } catch (IOException e) {
3972                        e.printStackTrace();
3973                    } finally {
3974                        if (clientStream != null) {
3975                            try {
3976                                clientStream.close();
3977                            } catch (IOException e) {
3978                                e.printStackTrace();
3979                            }
3980                        }
3981                    }
3982                }
3983            }
3984        }
3985
3986        public void closeSystemDialogs(String reason) {
3987            final ViewRootImpl viewAncestor = mViewAncestor.get();
3988            if (viewAncestor != null) {
3989                viewAncestor.dispatchCloseSystemDialogs(reason);
3990            }
3991        }
3992
3993        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3994                boolean sync) {
3995            if (sync) {
3996                try {
3997                    sWindowSession.wallpaperOffsetsComplete(asBinder());
3998                } catch (RemoteException e) {
3999                }
4000            }
4001        }
4002
4003        public void dispatchWallpaperCommand(String action, int x, int y,
4004                int z, Bundle extras, boolean sync) {
4005            if (sync) {
4006                try {
4007                    sWindowSession.wallpaperCommandComplete(asBinder(), null);
4008                } catch (RemoteException e) {
4009                }
4010            }
4011        }
4012
4013        /* Drag/drop */
4014        public void dispatchDragEvent(DragEvent event) {
4015            final ViewRootImpl viewAncestor = mViewAncestor.get();
4016            if (viewAncestor != null) {
4017                viewAncestor.dispatchDragEvent(event);
4018            }
4019        }
4020
4021        public void dispatchSystemUiVisibilityChanged(int visibility) {
4022            final ViewRootImpl viewAncestor = mViewAncestor.get();
4023            if (viewAncestor != null) {
4024                viewAncestor.dispatchSystemUiVisibilityChanged(visibility);
4025            }
4026        }
4027    }
4028
4029    /**
4030     * Maintains state information for a single trackball axis, generating
4031     * discrete (DPAD) movements based on raw trackball motion.
4032     */
4033    static final class TrackballAxis {
4034        /**
4035         * The maximum amount of acceleration we will apply.
4036         */
4037        static final float MAX_ACCELERATION = 20;
4038
4039        /**
4040         * The maximum amount of time (in milliseconds) between events in order
4041         * for us to consider the user to be doing fast trackball movements,
4042         * and thus apply an acceleration.
4043         */
4044        static final long FAST_MOVE_TIME = 150;
4045
4046        /**
4047         * Scaling factor to the time (in milliseconds) between events to how
4048         * much to multiple/divide the current acceleration.  When movement
4049         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4050         * FAST_MOVE_TIME it divides it.
4051         */
4052        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4053
4054        float position;
4055        float absPosition;
4056        float acceleration = 1;
4057        long lastMoveTime = 0;
4058        int step;
4059        int dir;
4060        int nonAccelMovement;
4061
4062        void reset(int _step) {
4063            position = 0;
4064            acceleration = 1;
4065            lastMoveTime = 0;
4066            step = _step;
4067            dir = 0;
4068        }
4069
4070        /**
4071         * Add trackball movement into the state.  If the direction of movement
4072         * has been reversed, the state is reset before adding the
4073         * movement (so that you don't have to compensate for any previously
4074         * collected movement before see the result of the movement in the
4075         * new direction).
4076         *
4077         * @return Returns the absolute value of the amount of movement
4078         * collected so far.
4079         */
4080        float collect(float off, long time, String axis) {
4081            long normTime;
4082            if (off > 0) {
4083                normTime = (long)(off * FAST_MOVE_TIME);
4084                if (dir < 0) {
4085                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4086                    position = 0;
4087                    step = 0;
4088                    acceleration = 1;
4089                    lastMoveTime = 0;
4090                }
4091                dir = 1;
4092            } else if (off < 0) {
4093                normTime = (long)((-off) * FAST_MOVE_TIME);
4094                if (dir > 0) {
4095                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4096                    position = 0;
4097                    step = 0;
4098                    acceleration = 1;
4099                    lastMoveTime = 0;
4100                }
4101                dir = -1;
4102            } else {
4103                normTime = 0;
4104            }
4105
4106            // The number of milliseconds between each movement that is
4107            // considered "normal" and will not result in any acceleration
4108            // or deceleration, scaled by the offset we have here.
4109            if (normTime > 0) {
4110                long delta = time - lastMoveTime;
4111                lastMoveTime = time;
4112                float acc = acceleration;
4113                if (delta < normTime) {
4114                    // The user is scrolling rapidly, so increase acceleration.
4115                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4116                    if (scale > 1) acc *= scale;
4117                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4118                            + off + " normTime=" + normTime + " delta=" + delta
4119                            + " scale=" + scale + " acc=" + acc);
4120                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4121                } else {
4122                    // The user is scrolling slowly, so decrease acceleration.
4123                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4124                    if (scale > 1) acc /= scale;
4125                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4126                            + off + " normTime=" + normTime + " delta=" + delta
4127                            + " scale=" + scale + " acc=" + acc);
4128                    acceleration = acc > 1 ? acc : 1;
4129                }
4130            }
4131            position += off;
4132            return (absPosition = Math.abs(position));
4133        }
4134
4135        /**
4136         * Generate the number of discrete movement events appropriate for
4137         * the currently collected trackball movement.
4138         *
4139         * @param precision The minimum movement required to generate the
4140         * first discrete movement.
4141         *
4142         * @return Returns the number of discrete movements, either positive
4143         * or negative, or 0 if there is not enough trackball movement yet
4144         * for a discrete movement.
4145         */
4146        int generate(float precision) {
4147            int movement = 0;
4148            nonAccelMovement = 0;
4149            do {
4150                final int dir = position >= 0 ? 1 : -1;
4151                switch (step) {
4152                    // If we are going to execute the first step, then we want
4153                    // to do this as soon as possible instead of waiting for
4154                    // a full movement, in order to make things look responsive.
4155                    case 0:
4156                        if (absPosition < precision) {
4157                            return movement;
4158                        }
4159                        movement += dir;
4160                        nonAccelMovement += dir;
4161                        step = 1;
4162                        break;
4163                    // If we have generated the first movement, then we need
4164                    // to wait for the second complete trackball motion before
4165                    // generating the second discrete movement.
4166                    case 1:
4167                        if (absPosition < 2) {
4168                            return movement;
4169                        }
4170                        movement += dir;
4171                        nonAccelMovement += dir;
4172                        position += dir > 0 ? -2 : 2;
4173                        absPosition = Math.abs(position);
4174                        step = 2;
4175                        break;
4176                    // After the first two, we generate discrete movements
4177                    // consistently with the trackball, applying an acceleration
4178                    // if the trackball is moving quickly.  This is a simple
4179                    // acceleration on top of what we already compute based
4180                    // on how quickly the wheel is being turned, to apply
4181                    // a longer increasing acceleration to continuous movement
4182                    // in one direction.
4183                    default:
4184                        if (absPosition < 1) {
4185                            return movement;
4186                        }
4187                        movement += dir;
4188                        position += dir >= 0 ? -1 : 1;
4189                        absPosition = Math.abs(position);
4190                        float acc = acceleration;
4191                        acc *= 1.1f;
4192                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4193                        break;
4194                }
4195            } while (true);
4196        }
4197    }
4198
4199    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
4200        public CalledFromWrongThreadException(String msg) {
4201            super(msg);
4202        }
4203    }
4204
4205    private SurfaceHolder mHolder = new SurfaceHolder() {
4206        // we only need a SurfaceHolder for opengl. it would be nice
4207        // to implement everything else though, especially the callback
4208        // support (opengl doesn't make use of it right now, but eventually
4209        // will).
4210        public Surface getSurface() {
4211            return mSurface;
4212        }
4213
4214        public boolean isCreating() {
4215            return false;
4216        }
4217
4218        public void addCallback(Callback callback) {
4219        }
4220
4221        public void removeCallback(Callback callback) {
4222        }
4223
4224        public void setFixedSize(int width, int height) {
4225        }
4226
4227        public void setSizeFromLayout() {
4228        }
4229
4230        public void setFormat(int format) {
4231        }
4232
4233        public void setType(int type) {
4234        }
4235
4236        public void setKeepScreenOn(boolean screenOn) {
4237        }
4238
4239        public Canvas lockCanvas() {
4240            return null;
4241        }
4242
4243        public Canvas lockCanvas(Rect dirty) {
4244            return null;
4245        }
4246
4247        public void unlockCanvasAndPost(Canvas canvas) {
4248        }
4249        public Rect getSurfaceFrame() {
4250            return null;
4251        }
4252    };
4253
4254    static RunQueue getRunQueue() {
4255        RunQueue rq = sRunQueues.get();
4256        if (rq != null) {
4257            return rq;
4258        }
4259        rq = new RunQueue();
4260        sRunQueues.set(rq);
4261        return rq;
4262    }
4263
4264    /**
4265     * @hide
4266     */
4267    static final class RunQueue {
4268        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
4269
4270        void post(Runnable action) {
4271            postDelayed(action, 0);
4272        }
4273
4274        void postDelayed(Runnable action, long delayMillis) {
4275            HandlerAction handlerAction = new HandlerAction();
4276            handlerAction.action = action;
4277            handlerAction.delay = delayMillis;
4278
4279            synchronized (mActions) {
4280                mActions.add(handlerAction);
4281            }
4282        }
4283
4284        void removeCallbacks(Runnable action) {
4285            final HandlerAction handlerAction = new HandlerAction();
4286            handlerAction.action = action;
4287
4288            synchronized (mActions) {
4289                final ArrayList<HandlerAction> actions = mActions;
4290
4291                while (actions.remove(handlerAction)) {
4292                    // Keep going
4293                }
4294            }
4295        }
4296
4297        void executeActions(Handler handler) {
4298            synchronized (mActions) {
4299                final ArrayList<HandlerAction> actions = mActions;
4300                final int count = actions.size();
4301
4302                for (int i = 0; i < count; i++) {
4303                    final HandlerAction handlerAction = actions.get(i);
4304                    handler.postDelayed(handlerAction.action, handlerAction.delay);
4305                }
4306
4307                actions.clear();
4308            }
4309        }
4310
4311        private static class HandlerAction {
4312            Runnable action;
4313            long delay;
4314
4315            @Override
4316            public boolean equals(Object o) {
4317                if (this == o) return true;
4318                if (o == null || getClass() != o.getClass()) return false;
4319
4320                HandlerAction that = (HandlerAction) o;
4321                return !(action != null ? !action.equals(that.action) : that.action != null);
4322
4323            }
4324
4325            @Override
4326            public int hashCode() {
4327                int result = action != null ? action.hashCode() : 0;
4328                result = 31 * result + (int) (delay ^ (delay >>> 32));
4329                return result;
4330            }
4331        }
4332    }
4333
4334    /**
4335     * Class for managing the accessibility interaction connection
4336     * based on the global accessibility state.
4337     */
4338    final class AccessibilityInteractionConnectionManager
4339            implements AccessibilityStateChangeListener {
4340        public void onAccessibilityStateChanged(boolean enabled) {
4341            if (enabled) {
4342                ensureConnection();
4343            } else {
4344                ensureNoConnection();
4345            }
4346        }
4347
4348        public void ensureConnection() {
4349            final boolean registered = mAttachInfo.mAccessibilityWindowId != View.NO_ID;
4350            if (!registered) {
4351                mAttachInfo.mAccessibilityWindowId =
4352                    mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
4353                            new AccessibilityInteractionConnection(ViewRootImpl.this));
4354            }
4355        }
4356
4357        public void ensureNoConnection() {
4358            final boolean registered = mAttachInfo.mAccessibilityWindowId != View.NO_ID;
4359            if (registered) {
4360                mAttachInfo.mAccessibilityWindowId = View.NO_ID;
4361                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
4362            }
4363        }
4364    }
4365
4366    /**
4367     * This class is an interface this ViewAncestor provides to the
4368     * AccessibilityManagerService to the latter can interact with
4369     * the view hierarchy in this ViewAncestor.
4370     */
4371    final class AccessibilityInteractionConnection
4372            extends IAccessibilityInteractionConnection.Stub {
4373        private final WeakReference<ViewRootImpl> mViewAncestor;
4374
4375        AccessibilityInteractionConnection(ViewRootImpl viewAncestor) {
4376            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4377        }
4378
4379        public void findAccessibilityNodeInfoByAccessibilityId(int accessibilityId,
4380                int interactionId, IAccessibilityInteractionConnectionCallback callback,
4381                int interrogatingPid, long interrogatingTid) {
4382            if (mViewAncestor.get() != null) {
4383                getAccessibilityInteractionController()
4384                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityId,
4385                        interactionId, callback, interrogatingPid, interrogatingTid);
4386            }
4387        }
4388
4389        public void performAccessibilityAction(int accessibilityId, int action,
4390                int interactionId, IAccessibilityInteractionConnectionCallback callback,
4391                int interogatingPid, long interrogatingTid) {
4392            if (mViewAncestor.get() != null) {
4393                getAccessibilityInteractionController()
4394                    .performAccessibilityActionClientThread(accessibilityId, action, interactionId,
4395                            callback, interogatingPid, interrogatingTid);
4396            }
4397        }
4398
4399        public void findAccessibilityNodeInfoByViewId(int viewId,
4400                int interactionId, IAccessibilityInteractionConnectionCallback callback,
4401                int interrogatingPid, long interrogatingTid) {
4402            if (mViewAncestor.get() != null) {
4403                getAccessibilityInteractionController()
4404                    .findAccessibilityNodeInfoByViewIdClientThread(viewId, interactionId, callback,
4405                            interrogatingPid, interrogatingTid);
4406            }
4407        }
4408
4409        public void findAccessibilityNodeInfosByViewText(String text, int accessibilityId,
4410                int interactionId, IAccessibilityInteractionConnectionCallback callback,
4411                int interrogatingPid, long interrogatingTid) {
4412            if (mViewAncestor.get() != null) {
4413                getAccessibilityInteractionController()
4414                    .findAccessibilityNodeInfosByViewTextClientThread(text, accessibilityId,
4415                            interactionId, callback, interrogatingPid, interrogatingTid);
4416            }
4417        }
4418    }
4419
4420    /**
4421     * Class for managing accessibility interactions initiated from the system
4422     * and targeting the view hierarchy. A *ClientThread method is to be
4423     * called from the interaction connection this ViewAncestor gives the
4424     * system to talk to it and a corresponding *UiThread method that is executed
4425     * on the UI thread.
4426     */
4427    final class AccessibilityInteractionController {
4428        private static final int POOL_SIZE = 5;
4429
4430        private FindByAccessibilitytIdPredicate mFindByAccessibilityIdPredicate =
4431            new FindByAccessibilitytIdPredicate();
4432
4433        private ArrayList<AccessibilityNodeInfo> mTempAccessibilityNodeInfoList =
4434            new ArrayList<AccessibilityNodeInfo>();
4435
4436        // Reusable poolable arguments for interacting with the view hierarchy
4437        // to fit more arguments than Message and to avoid sharing objects between
4438        // two messages since several threads can send messages concurrently.
4439        private final Pool<SomeArgs> mPool = Pools.synchronizedPool(Pools.finitePool(
4440                new PoolableManager<SomeArgs>() {
4441                    public SomeArgs newInstance() {
4442                        return new SomeArgs();
4443                    }
4444
4445                    public void onAcquired(SomeArgs info) {
4446                        /* do nothing */
4447                    }
4448
4449                    public void onReleased(SomeArgs info) {
4450                        info.clear();
4451                    }
4452                }, POOL_SIZE)
4453        );
4454
4455        public class SomeArgs implements Poolable<SomeArgs> {
4456            private SomeArgs mNext;
4457            private boolean mIsPooled;
4458
4459            public Object arg1;
4460            public Object arg2;
4461            public int argi1;
4462            public int argi2;
4463            public int argi3;
4464
4465            public SomeArgs getNextPoolable() {
4466                return mNext;
4467            }
4468
4469            public boolean isPooled() {
4470                return mIsPooled;
4471            }
4472
4473            public void setNextPoolable(SomeArgs args) {
4474                mNext = args;
4475            }
4476
4477            public void setPooled(boolean isPooled) {
4478                mIsPooled = isPooled;
4479            }
4480
4481            private void clear() {
4482                arg1 = null;
4483                arg2 = null;
4484                argi1 = 0;
4485                argi2 = 0;
4486                argi3 = 0;
4487            }
4488        }
4489
4490        public void findAccessibilityNodeInfoByAccessibilityIdClientThread(int accessibilityId,
4491                int interactionId, IAccessibilityInteractionConnectionCallback callback,
4492                int interrogatingPid, long interrogatingTid) {
4493            Message message = Message.obtain();
4494            message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID;
4495            message.arg1 = accessibilityId;
4496            message.arg2 = interactionId;
4497            message.obj = callback;
4498            // If the interrogation is performed by the same thread as the main UI
4499            // thread in this process, set the message as a static reference so
4500            // after this call completes the same thread but in the interrogating
4501            // client can handle the message to generate the result.
4502            if (interrogatingPid == Process.myPid()
4503                    && interrogatingTid == Looper.getMainLooper().getThread().getId()) {
4504                message.setTarget(ViewRootImpl.this);
4505                AccessibilityInteractionClient.getInstance().setSameThreadMessage(message);
4506            } else {
4507                sendMessage(message);
4508            }
4509        }
4510
4511        public void findAccessibilityNodeInfoByAccessibilityIdUiThread(Message message) {
4512            final int accessibilityId = message.arg1;
4513            final int interactionId = message.arg2;
4514            final IAccessibilityInteractionConnectionCallback callback =
4515                (IAccessibilityInteractionConnectionCallback) message.obj;
4516
4517            AccessibilityNodeInfo info = null;
4518            try {
4519                FindByAccessibilitytIdPredicate predicate = mFindByAccessibilityIdPredicate;
4520                predicate.init(accessibilityId);
4521                View root = ViewRootImpl.this.mView;
4522                View target = root.findViewByPredicate(predicate);
4523                if (target != null && target.isShown()) {
4524                    info = target.createAccessibilityNodeInfo();
4525                }
4526            } finally {
4527                try {
4528                    callback.setFindAccessibilityNodeInfoResult(info, interactionId);
4529                } catch (RemoteException re) {
4530                    /* ignore - the other side will time out */
4531                }
4532            }
4533        }
4534
4535        public void findAccessibilityNodeInfoByViewIdClientThread(int viewId, int interactionId,
4536                IAccessibilityInteractionConnectionCallback callback, int interrogatingPid,
4537                long interrogatingTid) {
4538            Message message = Message.obtain();
4539            message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID;
4540            message.arg1 = viewId;
4541            message.arg2 = interactionId;
4542            message.obj = callback;
4543            // If the interrogation is performed by the same thread as the main UI
4544            // thread in this process, set the message as a static reference so
4545            // after this call completes the same thread but in the interrogating
4546            // client can handle the message to generate the result.
4547            if (interrogatingPid == Process.myPid()
4548                    && interrogatingTid == Looper.getMainLooper().getThread().getId()) {
4549                message.setTarget(ViewRootImpl.this);
4550                AccessibilityInteractionClient.getInstance().setSameThreadMessage(message);
4551            } else {
4552                sendMessage(message);
4553            }
4554        }
4555
4556        public void findAccessibilityNodeInfoByViewIdUiThread(Message message) {
4557            final int viewId = message.arg1;
4558            final int interactionId = message.arg2;
4559            final IAccessibilityInteractionConnectionCallback callback =
4560                (IAccessibilityInteractionConnectionCallback) message.obj;
4561
4562            AccessibilityNodeInfo info = null;
4563            try {
4564                View root = ViewRootImpl.this.mView;
4565                View target = root.findViewById(viewId);
4566                if (target != null && target.isShown()) {
4567                    info = target.createAccessibilityNodeInfo();
4568                }
4569            } finally {
4570                try {
4571                    callback.setFindAccessibilityNodeInfoResult(info, interactionId);
4572                } catch (RemoteException re) {
4573                    /* ignore - the other side will time out */
4574                }
4575            }
4576        }
4577
4578        public void findAccessibilityNodeInfosByViewTextClientThread(String text,
4579                int accessibilityViewId, int interactionId,
4580                IAccessibilityInteractionConnectionCallback callback, int interrogatingPid,
4581                long interrogatingTid) {
4582            Message message = Message.obtain();
4583            message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_TEXT;
4584            SomeArgs args = mPool.acquire();
4585            args.arg1 = text;
4586            args.argi1 = accessibilityViewId;
4587            args.argi2 = interactionId;
4588            args.arg2 = callback;
4589            message.obj = args;
4590            // If the interrogation is performed by the same thread as the main UI
4591            // thread in this process, set the message as a static reference so
4592            // after this call completes the same thread but in the interrogating
4593            // client can handle the message to generate the result.
4594            if (interrogatingPid == Process.myPid()
4595                    && interrogatingTid == Looper.getMainLooper().getThread().getId()) {
4596                message.setTarget(ViewRootImpl.this);
4597                AccessibilityInteractionClient.getInstance().setSameThreadMessage(message);
4598            } else {
4599                sendMessage(message);
4600            }
4601        }
4602
4603        public void findAccessibilityNodeInfosByViewTextUiThread(Message message) {
4604            SomeArgs args = (SomeArgs) message.obj;
4605            final String text = (String) args.arg1;
4606            final int accessibilityViewId = args.argi1;
4607            final int interactionId = args.argi2;
4608            final IAccessibilityInteractionConnectionCallback callback =
4609                (IAccessibilityInteractionConnectionCallback) args.arg2;
4610            mPool.release(args);
4611
4612            List<AccessibilityNodeInfo> infos = null;
4613            try {
4614                ArrayList<View> foundViews = mAttachInfo.mFocusablesTempList;
4615                foundViews.clear();
4616
4617                View root;
4618                if (accessibilityViewId != View.NO_ID) {
4619                    root = findViewByAccessibilityId(accessibilityViewId);
4620                } else {
4621                    root = ViewRootImpl.this.mView;
4622                }
4623
4624                if (root == null || !root.isShown()) {
4625                    return;
4626                }
4627
4628                root.findViewsWithText(foundViews, text);
4629                if (foundViews.isEmpty()) {
4630                    return;
4631                }
4632
4633                infos = mTempAccessibilityNodeInfoList;
4634                infos.clear();
4635
4636                final int viewCount = foundViews.size();
4637                for (int i = 0; i < viewCount; i++) {
4638                    View foundView = foundViews.get(i);
4639                    if (foundView.isShown()) {
4640                        infos.add(foundView.createAccessibilityNodeInfo());
4641                    }
4642                 }
4643            } finally {
4644                try {
4645                    callback.setFindAccessibilityNodeInfosResult(infos, interactionId);
4646                } catch (RemoteException re) {
4647                    /* ignore - the other side will time out */
4648                }
4649            }
4650        }
4651
4652        public void performAccessibilityActionClientThread(int accessibilityId, int action,
4653                int interactionId, IAccessibilityInteractionConnectionCallback callback,
4654                int interogatingPid, long interrogatingTid) {
4655            Message message = Message.obtain();
4656            message.what = DO_PERFORM_ACCESSIBILITY_ACTION;
4657            SomeArgs args = mPool.acquire();
4658            args.argi1 = accessibilityId;
4659            args.argi2 = action;
4660            args.argi3 = interactionId;
4661            args.arg1 = callback;
4662            message.obj = args;
4663            // If the interrogation is performed by the same thread as the main UI
4664            // thread in this process, set the message as a static reference so
4665            // after this call completes the same thread but in the interrogating
4666            // client can handle the message to generate the result.
4667            if (interogatingPid == Process.myPid()
4668                    && interrogatingTid == Looper.getMainLooper().getThread().getId()) {
4669                message.setTarget(ViewRootImpl.this);
4670                AccessibilityInteractionClient.getInstance().setSameThreadMessage(message);
4671            } else {
4672                sendMessage(message);
4673            }
4674        }
4675
4676        public void perfromAccessibilityActionUiThread(Message message) {
4677            SomeArgs args = (SomeArgs) message.obj;
4678            final int accessibilityId = args.argi1;
4679            final int action = args.argi2;
4680            final int interactionId = args.argi3;
4681            final IAccessibilityInteractionConnectionCallback callback =
4682                (IAccessibilityInteractionConnectionCallback) args.arg1;
4683            mPool.release(args);
4684
4685            boolean succeeded = false;
4686            try {
4687                switch (action) {
4688                    case AccessibilityNodeInfo.ACTION_FOCUS: {
4689                        succeeded = performActionFocus(accessibilityId);
4690                    } break;
4691                    case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
4692                        succeeded = performActionClearFocus(accessibilityId);
4693                    } break;
4694                    case AccessibilityNodeInfo.ACTION_SELECT: {
4695                        succeeded = performActionSelect(accessibilityId);
4696                    } break;
4697                    case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
4698                        succeeded = performActionClearSelection(accessibilityId);
4699                    } break;
4700                }
4701            } finally {
4702                try {
4703                    callback.setPerformAccessibilityActionResult(succeeded, interactionId);
4704                } catch (RemoteException re) {
4705                    /* ignore - the other side will time out */
4706                }
4707            }
4708        }
4709
4710        private boolean performActionFocus(int accessibilityId) {
4711            View target = findViewByAccessibilityId(accessibilityId);
4712            if (target == null) {
4713                return false;
4714            }
4715            // Get out of touch mode since accessibility wants to move focus around.
4716            ensureTouchMode(false);
4717            return target.requestFocus();
4718        }
4719
4720        private boolean performActionClearFocus(int accessibilityId) {
4721            View target = findViewByAccessibilityId(accessibilityId);
4722            if (target == null) {
4723                return false;
4724            }
4725            if (!target.isFocused()) {
4726                return false;
4727            }
4728            target.clearFocus();
4729            return !target.isFocused();
4730        }
4731
4732        private boolean performActionSelect(int accessibilityId) {
4733            View target = findViewByAccessibilityId(accessibilityId);
4734            if (target == null) {
4735                return false;
4736            }
4737            if (target.isSelected()) {
4738                return false;
4739            }
4740            target.setSelected(true);
4741            return target.isSelected();
4742        }
4743
4744        private boolean performActionClearSelection(int accessibilityId) {
4745            View target = findViewByAccessibilityId(accessibilityId);
4746            if (target == null) {
4747                return false;
4748            }
4749            if (!target.isSelected()) {
4750                return false;
4751            }
4752            target.setSelected(false);
4753            return !target.isSelected();
4754        }
4755
4756        private View findViewByAccessibilityId(int accessibilityId) {
4757            View root = ViewRootImpl.this.mView;
4758            if (root == null) {
4759                return null;
4760            }
4761            mFindByAccessibilityIdPredicate.init(accessibilityId);
4762            View foundView = root.findViewByPredicate(mFindByAccessibilityIdPredicate);
4763            return (foundView != null && foundView.isShown()) ? foundView : null;
4764        }
4765
4766        private final class FindByAccessibilitytIdPredicate implements Predicate<View> {
4767            public int mSerchedId;
4768
4769            public void init(int searchedId) {
4770                mSerchedId = searchedId;
4771            }
4772
4773            public boolean apply(View view) {
4774                return (view.getAccessibilityViewId() == mSerchedId);
4775            }
4776        }
4777    }
4778
4779    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
4780        public volatile boolean mIsPending;
4781
4782        public void run() {
4783            if (mView != null) {
4784                // Check again for accessibility state since this is executed delayed.
4785                AccessibilityManager accessibilityManager =
4786                    AccessibilityManager.getInstance(mView.mContext);
4787                if (accessibilityManager.isEnabled()) {
4788                    // Send the event directly since we do not want to append the
4789                    // source text because this is the text for the entire window
4790                    // and we just want to notify that the content has changed.
4791                    AccessibilityEvent event = AccessibilityEvent.obtain(
4792                            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
4793                    mView.onInitializeAccessibilityEvent(event);
4794                    accessibilityManager.sendAccessibilityEvent(event);
4795                }
4796                mIsPending = false;
4797            }
4798        }
4799    }
4800}
4801