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