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