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