ViewRootImpl.java revision 12d3a94397c33fdb773a1eaaaa13cab80bf0c571
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        }
640    }
641
642    void destroyHardwareResources() {
643        if (mAttachInfo.mHardwareRenderer != null) {
644            if (mAttachInfo.mHardwareRenderer.isEnabled()) {
645                mAttachInfo.mHardwareRenderer.destroyLayers(mView);
646            }
647            mAttachInfo.mHardwareRenderer.destroy(false);
648        }
649    }
650
651    void terminateHardwareResources() {
652        if (mAttachInfo.mHardwareRenderer != null) {
653            mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
654            mAttachInfo.mHardwareRenderer.destroy(false);
655        }
656    }
657
658    void destroyHardwareLayers() {
659        if (mThread != Thread.currentThread()) {
660            if (mAttachInfo.mHardwareRenderer != null &&
661                    mAttachInfo.mHardwareRenderer.isEnabled()) {
662                HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE);
663            }
664        } else {
665            if (mAttachInfo.mHardwareRenderer != null &&
666                    mAttachInfo.mHardwareRenderer.isEnabled()) {
667                mAttachInfo.mHardwareRenderer.destroyLayers(mView);
668            }
669        }
670    }
671
672    public void attachFunctor(int functor) {
673        if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
674            mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor);
675        }
676    }
677
678    public void detachFunctor(int functor) {
679        if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
680            mAttachInfo.mHardwareRenderer.detachFunctor(functor);
681        }
682    }
683
684    private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) {
685        mAttachInfo.mHardwareAccelerated = false;
686        mAttachInfo.mHardwareAccelerationRequested = false;
687
688        // Don't enable hardware acceleration when the application is in compatibility mode
689        if (mTranslator != null) return;
690
691        // Try to enable hardware acceleration if requested
692        final boolean hardwareAccelerated =
693                (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
694
695        if (hardwareAccelerated) {
696            if (!HardwareRenderer.isAvailable()) {
697                return;
698            }
699
700            // Persistent processes (including the system) should not do
701            // accelerated rendering on low-end devices.  In that case,
702            // sRendererDisabled will be set.  In addition, the system process
703            // itself should never do accelerated rendering.  In that case, both
704            // sRendererDisabled and sSystemRendererDisabled are set.  When
705            // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
706            // can be used by code on the system process to escape that and enable
707            // HW accelerated drawing.  (This is basically for the lock screen.)
708
709            final boolean fakeHwAccelerated = (attrs.privateFlags &
710                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
711            final boolean forceHwAccelerated = (attrs.privateFlags &
712                    WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
713
714            if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled
715                    && forceHwAccelerated)) {
716                // Don't enable hardware acceleration when we're not on the main thread
717                if (!HardwareRenderer.sSystemRendererDisabled &&
718                        Looper.getMainLooper() != Looper.myLooper()) {
719                    Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
720                            + "acceleration outside of the main thread, aborting");
721                    return;
722                }
723
724                final boolean renderThread = isRenderThreadRequested(context);
725                if (renderThread) {
726                    Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated");
727                }
728
729                if (mAttachInfo.mHardwareRenderer != null) {
730                    mAttachInfo.mHardwareRenderer.destroy(true);
731                }
732
733                final boolean translucent = attrs.format != PixelFormat.OPAQUE;
734                mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
735                mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
736                        = mAttachInfo.mHardwareRenderer != null;
737
738            } else if (fakeHwAccelerated) {
739                // The window had wanted to use hardware acceleration, but this
740                // is not allowed in its process.  By setting this flag, it can
741                // still render as if it was accelerated.  This is basically for
742                // the preview windows the window manager shows for launching
743                // applications, so they will look more like the app being launched.
744                mAttachInfo.mHardwareAccelerationRequested = true;
745            }
746        }
747    }
748
749    public View getView() {
750        return mView;
751    }
752
753    final WindowLeaked getLocation() {
754        return mLocation;
755    }
756
757    void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
758        synchronized (this) {
759            int oldSoftInputMode = mWindowAttributes.softInputMode;
760            // preserve compatible window flag if exists.
761            int compatibleWindowFlag =
762                mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
763            mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
764            mWindowAttributes.flags |= compatibleWindowFlag;
765
766            if (newView) {
767                mSoftInputMode = attrs.softInputMode;
768                requestLayout();
769            }
770            // Don't lose the mode we last auto-computed.
771            if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
772                    == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
773                mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
774                        & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
775                        | (oldSoftInputMode
776                                & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
777            }
778            mWindowAttributesChanged = true;
779            scheduleTraversals();
780        }
781    }
782
783    void handleAppVisibility(boolean visible) {
784        if (mAppVisible != visible) {
785            mAppVisible = visible;
786            scheduleTraversals();
787        }
788    }
789
790    void handleGetNewSurface() {
791        mNewSurfaceNeeded = true;
792        mFullRedrawNeeded = true;
793        scheduleTraversals();
794    }
795
796    void handleScreenStateChange(boolean on) {
797        if (on != mAttachInfo.mScreenOn) {
798            mAttachInfo.mScreenOn = on;
799            if (mView != null) {
800                mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF);
801            }
802            if (on) {
803                mFullRedrawNeeded = true;
804                scheduleTraversals();
805            }
806        }
807    }
808
809    /**
810     * {@inheritDoc}
811     */
812    public void requestFitSystemWindows() {
813        checkThread();
814        mFitSystemWindowsRequested = true;
815        scheduleTraversals();
816    }
817
818    /**
819     * {@inheritDoc}
820     */
821    public void requestLayout() {
822        checkThread();
823        mLayoutRequested = true;
824        scheduleTraversals();
825    }
826
827    /**
828     * {@inheritDoc}
829     */
830    public boolean isLayoutRequested() {
831        return mLayoutRequested;
832    }
833
834    void invalidate() {
835        mDirty.set(0, 0, mWidth, mHeight);
836        scheduleTraversals();
837    }
838
839    public void invalidateChild(View child, Rect dirty) {
840        invalidateChildInParent(null, dirty);
841    }
842
843    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
844        checkThread();
845        if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
846
847        if (dirty == null) {
848            invalidate();
849            return null;
850        }
851
852        if (mCurScrollY != 0 || mTranslator != null) {
853            mTempRect.set(dirty);
854            dirty = mTempRect;
855            if (mCurScrollY != 0) {
856                dirty.offset(0, -mCurScrollY);
857            }
858            if (mTranslator != null) {
859                mTranslator.translateRectInAppWindowToScreen(dirty);
860            }
861            if (mAttachInfo.mScalingRequired) {
862                dirty.inset(-1, -1);
863            }
864        }
865
866        final Rect localDirty = mDirty;
867        if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
868            mAttachInfo.mSetIgnoreDirtyState = true;
869            mAttachInfo.mIgnoreDirtyState = true;
870        }
871
872        // Add the new dirty rect to the current one
873        localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
874        // Intersect with the bounds of the window to skip
875        // updates that lie outside of the visible region
876        final float appScale = mAttachInfo.mApplicationScale;
877        localDirty.intersect(0, 0,
878                (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
879
880        if (!mWillDrawSoon) {
881            scheduleTraversals();
882        }
883
884        return null;
885    }
886
887    void setStopped(boolean stopped) {
888        if (mStopped != stopped) {
889            mStopped = stopped;
890            if (!stopped) {
891                scheduleTraversals();
892            }
893        }
894    }
895
896    public ViewParent getParent() {
897        return null;
898    }
899
900    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
901        if (child != mView) {
902            throw new RuntimeException("child is not mine, honest!");
903        }
904        // Note: don't apply scroll offset, because we want to know its
905        // visibility in the virtual canvas being given to the view hierarchy.
906        return r.intersect(0, 0, mWidth, mHeight);
907    }
908
909    public void bringChildToFront(View child) {
910    }
911
912    int getHostVisibility() {
913        return mAppVisible ? mView.getVisibility() : View.GONE;
914    }
915
916    void disposeResizeBuffer() {
917        if (mResizeBuffer != null) {
918            mResizeBuffer.destroy();
919            mResizeBuffer = null;
920        }
921    }
922
923    /**
924     * Add LayoutTransition to the list of transitions to be started in the next traversal.
925     * This list will be cleared after the transitions on the list are start()'ed. These
926     * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
927     * happens during the layout phase of traversal, which we want to complete before any of the
928     * animations are started (because those animations may side-effect properties that layout
929     * depends upon, like the bounding rectangles of the affected views). So we add the transition
930     * to the list and it is started just prior to starting the drawing phase of traversal.
931     *
932     * @param transition The LayoutTransition to be started on the next traversal.
933     *
934     * @hide
935     */
936    public void requestTransitionStart(LayoutTransition transition) {
937        if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
938            if (mPendingTransitions == null) {
939                 mPendingTransitions = new ArrayList<LayoutTransition>();
940            }
941            mPendingTransitions.add(transition);
942        }
943    }
944
945    void scheduleTraversals() {
946        if (!mTraversalScheduled) {
947            mTraversalScheduled = true;
948            mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
949            mChoreographer.postCallback(
950                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
951        }
952    }
953
954    void unscheduleTraversals() {
955        if (mTraversalScheduled) {
956            mTraversalScheduled = false;
957            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
958            mChoreographer.removeCallbacks(
959                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
960        }
961    }
962
963    void doTraversal() {
964        if (mTraversalScheduled) {
965            mTraversalScheduled = false;
966            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
967
968            doConsumeBatchedInput(false);
969            doProcessInputEvents();
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        mChoreographer.notifyDrawOccurred();
2011
2012        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2013        try {
2014            draw(fullRedrawNeeded);
2015        } finally {
2016            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2017        }
2018
2019        if (ViewDebug.DEBUG_LATENCY) {
2020            long now = System.nanoTime();
2021            Log.d(ViewDebug.DEBUG_LATENCY_TAG, "performDraw() took "
2022                    + ((now - drawStartTime) * 0.000001f)
2023                    + "ms.");
2024            mLastDrawFinishedTimeNanos = now;
2025        }
2026
2027        if (mReportNextDraw) {
2028            mReportNextDraw = false;
2029
2030            if (LOCAL_LOGV) {
2031                Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2032            }
2033            if (mSurfaceHolder != null && mSurface.isValid()) {
2034                mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2035                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2036                if (callbacks != null) {
2037                    for (SurfaceHolder.Callback c : callbacks) {
2038                        if (c instanceof SurfaceHolder.Callback2) {
2039                            ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
2040                                    mSurfaceHolder);
2041                        }
2042                    }
2043                }
2044            }
2045            try {
2046                sWindowSession.finishDrawing(mWindow);
2047            } catch (RemoteException e) {
2048            }
2049        }
2050    }
2051
2052    private void draw(boolean fullRedrawNeeded) {
2053        Surface surface = mSurface;
2054        if (surface == null || !surface.isValid()) {
2055            return;
2056        }
2057
2058        if (DEBUG_FPS) {
2059            trackFPS();
2060        }
2061
2062        if (!sFirstDrawComplete) {
2063            synchronized (sFirstDrawHandlers) {
2064                sFirstDrawComplete = true;
2065                final int count = sFirstDrawHandlers.size();
2066                for (int i = 0; i< count; i++) {
2067                    mHandler.post(sFirstDrawHandlers.get(i));
2068                }
2069            }
2070        }
2071
2072        scrollToRectOrFocus(null, false);
2073
2074        final AttachInfo attachInfo = mAttachInfo;
2075        if (attachInfo.mViewScrollChanged) {
2076            attachInfo.mViewScrollChanged = false;
2077            attachInfo.mTreeObserver.dispatchOnScrollChanged();
2078        }
2079
2080        int yoff;
2081        boolean animating = mScroller != null && mScroller.computeScrollOffset();
2082        if (animating) {
2083            yoff = mScroller.getCurrY();
2084        } else {
2085            yoff = mScrollY;
2086        }
2087        if (mCurScrollY != yoff) {
2088            mCurScrollY = yoff;
2089            fullRedrawNeeded = true;
2090        }
2091
2092        final float appScale = attachInfo.mApplicationScale;
2093        final boolean scalingRequired = attachInfo.mScalingRequired;
2094
2095        int resizeAlpha = 0;
2096        if (mResizeBuffer != null) {
2097            long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
2098            if (deltaTime < mResizeBufferDuration) {
2099                float amt = deltaTime/(float) mResizeBufferDuration;
2100                amt = mResizeInterpolator.getInterpolation(amt);
2101                animating = true;
2102                resizeAlpha = 255 - (int)(amt*255);
2103            } else {
2104                disposeResizeBuffer();
2105            }
2106        }
2107
2108        final Rect dirty = mDirty;
2109        if (mSurfaceHolder != null) {
2110            // The app owns the surface, we won't draw.
2111            dirty.setEmpty();
2112            if (animating) {
2113                if (mScroller != null) {
2114                    mScroller.abortAnimation();
2115                }
2116                disposeResizeBuffer();
2117            }
2118            return;
2119        }
2120
2121        if (fullRedrawNeeded) {
2122            attachInfo.mIgnoreDirtyState = true;
2123            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2124        }
2125
2126        if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2127            Log.v(TAG, "Draw " + mView + "/"
2128                    + mWindowAttributes.getTitle()
2129                    + ": dirty={" + dirty.left + "," + dirty.top
2130                    + "," + dirty.right + "," + dirty.bottom + "} surface="
2131                    + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2132                    appScale + ", width=" + mWidth + ", height=" + mHeight);
2133        }
2134
2135        attachInfo.mTreeObserver.dispatchOnDraw();
2136
2137        if (!dirty.isEmpty() || mIsAnimating) {
2138            if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) {
2139                // Draw with hardware renderer.
2140                mIsAnimating = false;
2141                mHardwareYOffset = yoff;
2142                mResizeAlpha = resizeAlpha;
2143
2144                mCurrentDirty.set(dirty);
2145                mCurrentDirty.union(mPreviousDirty);
2146                mPreviousDirty.set(dirty);
2147                dirty.setEmpty();
2148
2149                if (attachInfo.mHardwareRenderer.draw(mView, attachInfo, this,
2150                        animating ? null : mCurrentDirty)) {
2151                    mPreviousDirty.set(0, 0, mWidth, mHeight);
2152                }
2153            } else if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) {
2154                return;
2155            }
2156        }
2157
2158        if (animating) {
2159            mFullRedrawNeeded = true;
2160            scheduleTraversals();
2161        }
2162    }
2163
2164    /**
2165     * @return true if drawing was succesfull, false if an error occurred
2166     */
2167    private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff,
2168            boolean scalingRequired, Rect dirty) {
2169
2170        // Draw with software renderer.
2171        Canvas canvas;
2172        try {
2173            int left = dirty.left;
2174            int top = dirty.top;
2175            int right = dirty.right;
2176            int bottom = dirty.bottom;
2177
2178            final long lockCanvasStartTime;
2179            if (ViewDebug.DEBUG_LATENCY) {
2180                lockCanvasStartTime = System.nanoTime();
2181            }
2182
2183            canvas = mSurface.lockCanvas(dirty);
2184
2185            if (ViewDebug.DEBUG_LATENCY) {
2186                long now = System.nanoTime();
2187                Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- lockCanvas() took "
2188                        + ((now - lockCanvasStartTime) * 0.000001f) + "ms");
2189            }
2190
2191            if (left != dirty.left || top != dirty.top || right != dirty.right ||
2192                    bottom != dirty.bottom) {
2193                attachInfo.mIgnoreDirtyState = true;
2194            }
2195
2196            // TODO: Do this in native
2197            canvas.setDensity(mDensity);
2198        } catch (Surface.OutOfResourcesException e) {
2199            Log.e(TAG, "OutOfResourcesException locking surface", e);
2200            try {
2201                if (!sWindowSession.outOfMemory(mWindow)) {
2202                    Slog.w(TAG, "No processes killed for memory; killing self");
2203                    Process.killProcess(Process.myPid());
2204                }
2205            } catch (RemoteException ex) {
2206            }
2207            mLayoutRequested = true;    // ask wm for a new surface next time.
2208            return false;
2209        } catch (IllegalArgumentException e) {
2210            Log.e(TAG, "IllegalArgumentException locking surface", e);
2211            // Don't assume this is due to out of memory, it could be
2212            // something else, and if it is something else then we could
2213            // kill stuff (or ourself) for no reason.
2214            mLayoutRequested = true;    // ask wm for a new surface next time.
2215            return false;
2216        }
2217
2218        try {
2219            if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2220                Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
2221                        + canvas.getWidth() + ", h=" + canvas.getHeight());
2222                //canvas.drawARGB(255, 255, 0, 0);
2223            }
2224
2225            long startTime = 0L;
2226            if (ViewDebug.DEBUG_PROFILE_DRAWING) {
2227                startTime = SystemClock.elapsedRealtime();
2228            }
2229
2230            // If this bitmap's format includes an alpha channel, we
2231            // need to clear it before drawing so that the child will
2232            // properly re-composite its drawing on a transparent
2233            // background. This automatically respects the clip/dirty region
2234            // or
2235            // If we are applying an offset, we need to clear the area
2236            // where the offset doesn't appear to avoid having garbage
2237            // left in the blank areas.
2238            if (!canvas.isOpaque() || yoff != 0) {
2239                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2240            }
2241
2242            dirty.setEmpty();
2243            mIsAnimating = false;
2244            attachInfo.mDrawingTime = SystemClock.uptimeMillis();
2245            mView.mPrivateFlags |= View.DRAWN;
2246
2247            if (DEBUG_DRAW) {
2248                Context cxt = mView.getContext();
2249                Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
2250                        ", metrics=" + cxt.getResources().getDisplayMetrics() +
2251                        ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2252            }
2253            try {
2254                canvas.translate(0, -yoff);
2255                if (mTranslator != null) {
2256                    mTranslator.translateCanvas(canvas);
2257                }
2258                canvas.setScreenDensity(scalingRequired
2259                        ? DisplayMetrics.DENSITY_DEVICE : 0);
2260                attachInfo.mSetIgnoreDirtyState = false;
2261
2262                final long drawStartTime;
2263                if (ViewDebug.DEBUG_LATENCY) {
2264                    drawStartTime = System.nanoTime();
2265                }
2266
2267                mView.draw(canvas);
2268
2269                drawAccessibilityFocusedDrawableIfNeeded(canvas);
2270
2271                if (ViewDebug.DEBUG_LATENCY) {
2272                    long now = System.nanoTime();
2273                    Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- draw() took "
2274                            + ((now - drawStartTime) * 0.000001f) + "ms");
2275                }
2276            } finally {
2277                if (!attachInfo.mSetIgnoreDirtyState) {
2278                    // Only clear the flag if it was not set during the mView.draw() call
2279                    attachInfo.mIgnoreDirtyState = false;
2280                }
2281            }
2282
2283            if (false && ViewDebug.consistencyCheckEnabled) {
2284                mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
2285            }
2286
2287            if (ViewDebug.DEBUG_PROFILE_DRAWING) {
2288                EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
2289            }
2290        } finally {
2291            final long unlockCanvasAndPostStartTime;
2292            if (ViewDebug.DEBUG_LATENCY) {
2293                unlockCanvasAndPostStartTime = System.nanoTime();
2294            }
2295
2296            surface.unlockCanvasAndPost(canvas);
2297
2298            if (ViewDebug.DEBUG_LATENCY) {
2299                long now = System.nanoTime();
2300                Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- unlockCanvasAndPost() took "
2301                        + ((now - unlockCanvasAndPostStartTime) * 0.000001f) + "ms");
2302            }
2303
2304            if (LOCAL_LOGV) {
2305                Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
2306            }
2307        }
2308        return true;
2309    }
2310
2311    /**
2312     * We want to draw a highlight around the current accessibility focused.
2313     * Since adding a style for all possible view is not a viable option we
2314     * have this specialized drawing method.
2315     *
2316     * Note: We are doing this here to be able to draw the highlight for
2317     *       virtual views in addition to real ones.
2318     *
2319     * @param canvas The canvas on which to draw.
2320     */
2321    private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2322        if (!AccessibilityManager.getInstance(mView.mContext).isEnabled()) {
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            mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2346            bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
2347        }
2348        drawable.setBounds(bounds);
2349        drawable.draw(canvas);
2350    }
2351
2352    private Drawable getAccessibilityFocusedDrawable() {
2353        if (mAttachInfo != null) {
2354            // Lazily load the accessibility focus drawable.
2355            if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2356                TypedValue value = new TypedValue();
2357                final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2358                        R.attr.accessibilityFocusedDrawable, value, true);
2359                if (resolved) {
2360                    mAttachInfo.mAccessibilityFocusDrawable =
2361                        mView.mContext.getResources().getDrawable(value.resourceId);
2362                }
2363            }
2364            return mAttachInfo.mAccessibilityFocusDrawable;
2365        }
2366        return null;
2367    }
2368
2369    void invalidateDisplayLists() {
2370        final ArrayList<DisplayList> displayLists = mDisplayLists;
2371        final int count = displayLists.size();
2372
2373        for (int i = 0; i < count; i++) {
2374            displayLists.get(i).invalidate();
2375        }
2376
2377        displayLists.clear();
2378    }
2379
2380    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2381        final View.AttachInfo attachInfo = mAttachInfo;
2382        final Rect ci = attachInfo.mContentInsets;
2383        final Rect vi = attachInfo.mVisibleInsets;
2384        int scrollY = 0;
2385        boolean handled = false;
2386
2387        if (vi.left > ci.left || vi.top > ci.top
2388                || vi.right > ci.right || vi.bottom > ci.bottom) {
2389            // We'll assume that we aren't going to change the scroll
2390            // offset, since we want to avoid that unless it is actually
2391            // going to make the focus visible...  otherwise we scroll
2392            // all over the place.
2393            scrollY = mScrollY;
2394            // We can be called for two different situations: during a draw,
2395            // to update the scroll position if the focus has changed (in which
2396            // case 'rectangle' is null), or in response to a
2397            // requestChildRectangleOnScreen() call (in which case 'rectangle'
2398            // is non-null and we just want to scroll to whatever that
2399            // rectangle is).
2400            View focus = mRealFocusedView;
2401
2402            // When in touch mode, focus points to the previously focused view,
2403            // which may have been removed from the view hierarchy. The following
2404            // line checks whether the view is still in our hierarchy.
2405            if (focus == null || focus.mAttachInfo != mAttachInfo) {
2406                mRealFocusedView = null;
2407                return false;
2408            }
2409
2410            if (focus != mLastScrolledFocus) {
2411                // If the focus has changed, then ignore any requests to scroll
2412                // to a rectangle; first we want to make sure the entire focus
2413                // view is visible.
2414                rectangle = null;
2415            }
2416            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2417                    + " rectangle=" + rectangle + " ci=" + ci
2418                    + " vi=" + vi);
2419            if (focus == mLastScrolledFocus && !mScrollMayChange
2420                    && rectangle == null) {
2421                // Optimization: if the focus hasn't changed since last
2422                // time, and no layout has happened, then just leave things
2423                // as they are.
2424                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2425                        + mScrollY + " vi=" + vi.toShortString());
2426            } else if (focus != null) {
2427                // We need to determine if the currently focused view is
2428                // within the visible part of the window and, if not, apply
2429                // a pan so it can be seen.
2430                mLastScrolledFocus = focus;
2431                mScrollMayChange = false;
2432                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2433                // Try to find the rectangle from the focus view.
2434                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2435                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2436                            + mView.getWidth() + " h=" + mView.getHeight()
2437                            + " ci=" + ci.toShortString()
2438                            + " vi=" + vi.toShortString());
2439                    if (rectangle == null) {
2440                        focus.getFocusedRect(mTempRect);
2441                        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2442                                + ": focusRect=" + mTempRect.toShortString());
2443                        if (mView instanceof ViewGroup) {
2444                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2445                                    focus, mTempRect);
2446                        }
2447                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2448                                "Focus in window: focusRect="
2449                                + mTempRect.toShortString()
2450                                + " visRect=" + mVisRect.toShortString());
2451                    } else {
2452                        mTempRect.set(rectangle);
2453                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2454                                "Request scroll to rect: "
2455                                + mTempRect.toShortString()
2456                                + " visRect=" + mVisRect.toShortString());
2457                    }
2458                    if (mTempRect.intersect(mVisRect)) {
2459                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2460                                "Focus window visible rect: "
2461                                + mTempRect.toShortString());
2462                        if (mTempRect.height() >
2463                                (mView.getHeight()-vi.top-vi.bottom)) {
2464                            // If the focus simply is not going to fit, then
2465                            // best is probably just to leave things as-is.
2466                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2467                                    "Too tall; leaving scrollY=" + scrollY);
2468                        } else if ((mTempRect.top-scrollY) < vi.top) {
2469                            scrollY -= vi.top - (mTempRect.top-scrollY);
2470                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2471                                    "Top covered; scrollY=" + scrollY);
2472                        } else if ((mTempRect.bottom-scrollY)
2473                                > (mView.getHeight()-vi.bottom)) {
2474                            scrollY += (mTempRect.bottom-scrollY)
2475                                    - (mView.getHeight()-vi.bottom);
2476                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2477                                    "Bottom covered; scrollY=" + scrollY);
2478                        }
2479                        handled = true;
2480                    }
2481                }
2482            }
2483        }
2484
2485        if (scrollY != mScrollY) {
2486            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2487                    + mScrollY + " , new=" + scrollY);
2488            if (!immediate && mResizeBuffer == null) {
2489                if (mScroller == null) {
2490                    mScroller = new Scroller(mView.getContext());
2491                }
2492                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2493            } else if (mScroller != null) {
2494                mScroller.abortAnimation();
2495            }
2496            mScrollY = scrollY;
2497        }
2498
2499        return handled;
2500    }
2501
2502    void setAccessibilityFocusedHost(View host) {
2503        if (mAccessibilityFocusedHost != null && mAccessibilityFocusedVirtualView == null) {
2504            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2505        }
2506        mAccessibilityFocusedHost = host;
2507        mAccessibilityFocusedVirtualView = null;
2508    }
2509
2510    public void requestChildFocus(View child, View focused) {
2511        checkThread();
2512
2513        if (DEBUG_INPUT_RESIZE) {
2514            Log.v(TAG, "Request child focus: focus now " + focused);
2515        }
2516
2517        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused);
2518        scheduleTraversals();
2519
2520        mFocusedView = mRealFocusedView = focused;
2521    }
2522
2523    public void clearChildFocus(View child) {
2524        checkThread();
2525
2526        if (DEBUG_INPUT_RESIZE) {
2527            Log.v(TAG, "Clearing child focus");
2528        }
2529
2530        mOldFocusedView = mFocusedView;
2531
2532        // Invoke the listener only if there is no view to take focus
2533        if (focusSearch(null, View.FOCUS_FORWARD) == null) {
2534            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null);
2535        }
2536
2537        mFocusedView = mRealFocusedView = null;
2538    }
2539
2540    @Override
2541    public ViewParent getParentForAccessibility() {
2542        return null;
2543    }
2544
2545    public void focusableViewAvailable(View v) {
2546        checkThread();
2547        if (mView != null) {
2548            if (!mView.hasFocus()) {
2549                v.requestFocus();
2550            } else {
2551                // the one case where will transfer focus away from the current one
2552                // is if the current view is a view group that prefers to give focus
2553                // to its children first AND the view is a descendant of it.
2554                mFocusedView = mView.findFocus();
2555                boolean descendantsHaveDibsOnFocus =
2556                        (mFocusedView instanceof ViewGroup) &&
2557                            (((ViewGroup) mFocusedView).getDescendantFocusability() ==
2558                                    ViewGroup.FOCUS_AFTER_DESCENDANTS);
2559                if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
2560                    // If a view gets the focus, the listener will be invoked from requestChildFocus()
2561                    v.requestFocus();
2562                }
2563            }
2564        }
2565    }
2566
2567    public void recomputeViewAttributes(View child) {
2568        checkThread();
2569        if (mView == child) {
2570            mAttachInfo.mRecomputeGlobalAttributes = true;
2571            if (!mWillDrawSoon) {
2572                scheduleTraversals();
2573            }
2574        }
2575    }
2576
2577    void dispatchDetachedFromWindow() {
2578        if (mView != null && mView.mAttachInfo != null) {
2579            if (mAttachInfo.mHardwareRenderer != null &&
2580                    mAttachInfo.mHardwareRenderer.isEnabled()) {
2581                mAttachInfo.mHardwareRenderer.validate();
2582            }
2583            mView.dispatchDetachedFromWindow();
2584        }
2585
2586        mAccessibilityInteractionConnectionManager.ensureNoConnection();
2587        mAccessibilityManager.removeAccessibilityStateChangeListener(
2588                mAccessibilityInteractionConnectionManager);
2589        removeSendWindowContentChangedCallback();
2590
2591        destroyHardwareRenderer();
2592
2593        mView = null;
2594        mAttachInfo.mRootView = null;
2595        mAttachInfo.mSurface = null;
2596
2597        mSurface.release();
2598
2599        if (mInputQueueCallback != null && mInputQueue != null) {
2600            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2601            mInputQueueCallback = null;
2602            mInputQueue = null;
2603        } else if (mInputEventReceiver != null) {
2604            mInputEventReceiver.dispose();
2605            mInputEventReceiver = null;
2606        }
2607        try {
2608            sWindowSession.remove(mWindow);
2609        } catch (RemoteException e) {
2610        }
2611
2612        // Dispose the input channel after removing the window so the Window Manager
2613        // doesn't interpret the input channel being closed as an abnormal termination.
2614        if (mInputChannel != null) {
2615            mInputChannel.dispose();
2616            mInputChannel = null;
2617        }
2618
2619        unscheduleTraversals();
2620    }
2621
2622    void updateConfiguration(Configuration config, boolean force) {
2623        if (DEBUG_CONFIGURATION) Log.v(TAG,
2624                "Applying new config to window "
2625                + mWindowAttributes.getTitle()
2626                + ": " + config);
2627
2628        CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2629        if (ci != null) {
2630            config = new Configuration(config);
2631            ci.applyToConfiguration(config);
2632        }
2633
2634        synchronized (sConfigCallbacks) {
2635            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2636                sConfigCallbacks.get(i).onConfigurationChanged(config);
2637            }
2638        }
2639        if (mView != null) {
2640            // At this point the resources have been updated to
2641            // have the most recent config, whatever that is.  Use
2642            // the on in them which may be newer.
2643            config = mView.getResources().getConfiguration();
2644            if (force || mLastConfiguration.diff(config) != 0) {
2645                mLastConfiguration.setTo(config);
2646                mView.dispatchConfigurationChanged(config);
2647            }
2648        }
2649    }
2650
2651    /**
2652     * Return true if child is an ancestor of parent, (or equal to the parent).
2653     */
2654    static boolean isViewDescendantOf(View child, View parent) {
2655        if (child == parent) {
2656            return true;
2657        }
2658
2659        final ViewParent theParent = child.getParent();
2660        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2661    }
2662
2663    private static void forceLayout(View view) {
2664        view.forceLayout();
2665        if (view instanceof ViewGroup) {
2666            ViewGroup group = (ViewGroup) view;
2667            final int count = group.getChildCount();
2668            for (int i = 0; i < count; i++) {
2669                forceLayout(group.getChildAt(i));
2670            }
2671        }
2672    }
2673
2674    private final static int MSG_INVALIDATE = 1;
2675    private final static int MSG_INVALIDATE_RECT = 2;
2676    private final static int MSG_DIE = 3;
2677    private final static int MSG_RESIZED = 4;
2678    private final static int MSG_RESIZED_REPORT = 5;
2679    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
2680    private final static int MSG_DISPATCH_KEY = 7;
2681    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
2682    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
2683    private final static int MSG_IME_FINISHED_EVENT = 10;
2684    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
2685    private final static int MSG_FINISH_INPUT_CONNECTION = 12;
2686    private final static int MSG_CHECK_FOCUS = 13;
2687    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
2688    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
2689    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
2690    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
2691    private final static int MSG_UPDATE_CONFIGURATION = 18;
2692    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
2693    private final static int MSG_DISPATCH_SCREEN_STATE = 20;
2694    private final static int MSG_INVALIDATE_DISPLAY_LIST = 21;
2695    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 22;
2696    private final static int MSG_DISPATCH_DONE_ANIMATING = 23;
2697
2698    final class ViewRootHandler extends Handler {
2699        @Override
2700        public String getMessageName(Message message) {
2701            switch (message.what) {
2702                case MSG_INVALIDATE:
2703                    return "MSG_INVALIDATE";
2704                case MSG_INVALIDATE_RECT:
2705                    return "MSG_INVALIDATE_RECT";
2706                case MSG_DIE:
2707                    return "MSG_DIE";
2708                case MSG_RESIZED:
2709                    return "MSG_RESIZED";
2710                case MSG_RESIZED_REPORT:
2711                    return "MSG_RESIZED_REPORT";
2712                case MSG_WINDOW_FOCUS_CHANGED:
2713                    return "MSG_WINDOW_FOCUS_CHANGED";
2714                case MSG_DISPATCH_KEY:
2715                    return "MSG_DISPATCH_KEY";
2716                case MSG_DISPATCH_APP_VISIBILITY:
2717                    return "MSG_DISPATCH_APP_VISIBILITY";
2718                case MSG_DISPATCH_GET_NEW_SURFACE:
2719                    return "MSG_DISPATCH_GET_NEW_SURFACE";
2720                case MSG_IME_FINISHED_EVENT:
2721                    return "MSG_IME_FINISHED_EVENT";
2722                case MSG_DISPATCH_KEY_FROM_IME:
2723                    return "MSG_DISPATCH_KEY_FROM_IME";
2724                case MSG_FINISH_INPUT_CONNECTION:
2725                    return "MSG_FINISH_INPUT_CONNECTION";
2726                case MSG_CHECK_FOCUS:
2727                    return "MSG_CHECK_FOCUS";
2728                case MSG_CLOSE_SYSTEM_DIALOGS:
2729                    return "MSG_CLOSE_SYSTEM_DIALOGS";
2730                case MSG_DISPATCH_DRAG_EVENT:
2731                    return "MSG_DISPATCH_DRAG_EVENT";
2732                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
2733                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
2734                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
2735                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
2736                case MSG_UPDATE_CONFIGURATION:
2737                    return "MSG_UPDATE_CONFIGURATION";
2738                case MSG_PROCESS_INPUT_EVENTS:
2739                    return "MSG_PROCESS_INPUT_EVENTS";
2740                case MSG_DISPATCH_SCREEN_STATE:
2741                    return "MSG_DISPATCH_SCREEN_STATE";
2742                case MSG_INVALIDATE_DISPLAY_LIST:
2743                    return "MSG_INVALIDATE_DISPLAY_LIST";
2744                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
2745                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
2746                case MSG_DISPATCH_DONE_ANIMATING:
2747                    return "MSG_DISPATCH_DONE_ANIMATING";
2748            }
2749            return super.getMessageName(message);
2750        }
2751
2752        @Override
2753        public void handleMessage(Message msg) {
2754            switch (msg.what) {
2755            case MSG_INVALIDATE:
2756                ((View) msg.obj).invalidate();
2757                break;
2758            case MSG_INVALIDATE_RECT:
2759                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2760                info.target.invalidate(info.left, info.top, info.right, info.bottom);
2761                info.release();
2762                break;
2763            case MSG_IME_FINISHED_EVENT:
2764                handleImeFinishedEvent(msg.arg1, msg.arg2 != 0);
2765                break;
2766            case MSG_PROCESS_INPUT_EVENTS:
2767                mProcessInputEventsScheduled = false;
2768                doProcessInputEvents();
2769                break;
2770            case MSG_DISPATCH_APP_VISIBILITY:
2771                handleAppVisibility(msg.arg1 != 0);
2772                break;
2773            case MSG_DISPATCH_GET_NEW_SURFACE:
2774                handleGetNewSurface();
2775                break;
2776            case MSG_RESIZED:
2777                ResizedInfo ri = (ResizedInfo)msg.obj;
2778
2779                if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
2780                        && mPendingContentInsets.equals(ri.coveredInsets)
2781                        && mPendingVisibleInsets.equals(ri.visibleInsets)
2782                        && ((ResizedInfo)msg.obj).newConfig == null) {
2783                    break;
2784                }
2785                // fall through...
2786            case MSG_RESIZED_REPORT:
2787                if (mAdded) {
2788                    Configuration config = ((ResizedInfo)msg.obj).newConfig;
2789                    if (config != null) {
2790                        updateConfiguration(config, false);
2791                    }
2792                    mWinFrame.left = 0;
2793                    mWinFrame.right = msg.arg1;
2794                    mWinFrame.top = 0;
2795                    mWinFrame.bottom = msg.arg2;
2796                    mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
2797                    mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
2798                    if (msg.what == MSG_RESIZED_REPORT) {
2799                        mReportNextDraw = true;
2800                    }
2801
2802                    if (mView != null) {
2803                        forceLayout(mView);
2804                    }
2805                    requestLayout();
2806                }
2807                break;
2808            case MSG_WINDOW_FOCUS_CHANGED: {
2809                if (mAdded) {
2810                    boolean hasWindowFocus = msg.arg1 != 0;
2811                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
2812
2813                    profileRendering(hasWindowFocus);
2814
2815                    if (hasWindowFocus) {
2816                        boolean inTouchMode = msg.arg2 != 0;
2817                        ensureTouchModeLocally(inTouchMode);
2818
2819                        if (mAttachInfo.mHardwareRenderer != null &&
2820                                mSurface != null && mSurface.isValid()) {
2821                            mFullRedrawNeeded = true;
2822                            try {
2823                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2824                                        mHolder);
2825                            } catch (Surface.OutOfResourcesException e) {
2826                                Log.e(TAG, "OutOfResourcesException locking surface", e);
2827                                try {
2828                                    if (!sWindowSession.outOfMemory(mWindow)) {
2829                                        Slog.w(TAG, "No processes killed for memory; killing self");
2830                                        Process.killProcess(Process.myPid());
2831                                    }
2832                                } catch (RemoteException ex) {
2833                                }
2834                                // Retry in a bit.
2835                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
2836                                return;
2837                            }
2838                        }
2839                    }
2840
2841                    mLastWasImTarget = WindowManager.LayoutParams
2842                            .mayUseInputMethod(mWindowAttributes.flags);
2843
2844                    InputMethodManager imm = InputMethodManager.peekInstance();
2845                    if (mView != null) {
2846                        if (hasWindowFocus && imm != null && mLastWasImTarget) {
2847                            imm.startGettingWindowFocus(mView);
2848                        }
2849                        mAttachInfo.mKeyDispatchState.reset();
2850                        mView.dispatchWindowFocusChanged(hasWindowFocus);
2851                    }
2852
2853                    // Note: must be done after the focus change callbacks,
2854                    // so all of the view state is set up correctly.
2855                    if (hasWindowFocus) {
2856                        if (imm != null && mLastWasImTarget) {
2857                            imm.onWindowFocus(mView, mView.findFocus(),
2858                                    mWindowAttributes.softInputMode,
2859                                    !mHasHadWindowFocus, mWindowAttributes.flags);
2860                        }
2861                        // Clear the forward bit.  We can just do this directly, since
2862                        // the window manager doesn't care about it.
2863                        mWindowAttributes.softInputMode &=
2864                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2865                        ((WindowManager.LayoutParams)mView.getLayoutParams())
2866                                .softInputMode &=
2867                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2868                        mHasHadWindowFocus = true;
2869                    }
2870
2871                    if (mView != null && mAccessibilityManager.isEnabled()) {
2872                        if (hasWindowFocus) {
2873                            mView.sendAccessibilityEvent(
2874                                    AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2875                            // Give accessibility focus to the view that has input
2876                            // focus if such, otherwise to the first one.
2877                            if (mView instanceof ViewGroup) {
2878                                ViewGroup viewGroup = (ViewGroup) mView;
2879                                View focused = viewGroup.findFocus();
2880                                if (focused != null) {
2881                                    focused.requestAccessibilityFocus();
2882                                }
2883                            }
2884                            // There is no accessibility focus, despite our effort
2885                            // above, now just give it to the first view.
2886                            if (mAccessibilityFocusedHost == null) {
2887                                mView.requestAccessibilityFocus();
2888                            }
2889                        } else {
2890                            // Clear accessibility focus when the window loses input focus.
2891                            setAccessibilityFocusedHost(null);
2892                        }
2893                    }
2894                }
2895            } break;
2896            case MSG_DIE:
2897                doDie();
2898                break;
2899            case MSG_DISPATCH_KEY: {
2900                KeyEvent event = (KeyEvent)msg.obj;
2901                enqueueInputEvent(event, null, 0, true);
2902            } break;
2903            case MSG_DISPATCH_KEY_FROM_IME: {
2904                if (LOCAL_LOGV) Log.v(
2905                    TAG, "Dispatching key "
2906                    + msg.obj + " from IME to " + mView);
2907                KeyEvent event = (KeyEvent)msg.obj;
2908                if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2909                    // The IME is trying to say this event is from the
2910                    // system!  Bad bad bad!
2911                    //noinspection UnusedAssignment
2912                    event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
2913                }
2914                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
2915            } break;
2916            case MSG_FINISH_INPUT_CONNECTION: {
2917                InputMethodManager imm = InputMethodManager.peekInstance();
2918                if (imm != null) {
2919                    imm.reportFinishInputConnection((InputConnection)msg.obj);
2920                }
2921            } break;
2922            case MSG_CHECK_FOCUS: {
2923                InputMethodManager imm = InputMethodManager.peekInstance();
2924                if (imm != null) {
2925                    imm.checkFocus();
2926                }
2927            } break;
2928            case MSG_CLOSE_SYSTEM_DIALOGS: {
2929                if (mView != null) {
2930                    mView.onCloseSystemDialogs((String)msg.obj);
2931                }
2932            } break;
2933            case MSG_DISPATCH_DRAG_EVENT:
2934            case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
2935                DragEvent event = (DragEvent)msg.obj;
2936                event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
2937                handleDragEvent(event);
2938            } break;
2939            case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
2940                handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj);
2941            } break;
2942            case MSG_UPDATE_CONFIGURATION: {
2943                Configuration config = (Configuration)msg.obj;
2944                if (config.isOtherSeqNewer(mLastConfiguration)) {
2945                    config = mLastConfiguration;
2946                }
2947                updateConfiguration(config, false);
2948            } break;
2949            case MSG_DISPATCH_SCREEN_STATE: {
2950                if (mView != null) {
2951                    handleScreenStateChange(msg.arg1 == 1);
2952                }
2953            } break;
2954            case MSG_INVALIDATE_DISPLAY_LIST: {
2955                invalidateDisplayLists();
2956            } break;
2957            case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
2958                setAccessibilityFocusedHost(null);
2959            } break;
2960            case MSG_DISPATCH_DONE_ANIMATING: {
2961                handleDispatchDoneAnimating();
2962            } break;
2963            }
2964        }
2965    }
2966
2967    final ViewRootHandler mHandler = new ViewRootHandler();
2968
2969    /**
2970     * Something in the current window tells us we need to change the touch mode.  For
2971     * example, we are not in touch mode, and the user touches the screen.
2972     *
2973     * If the touch mode has changed, tell the window manager, and handle it locally.
2974     *
2975     * @param inTouchMode Whether we want to be in touch mode.
2976     * @return True if the touch mode changed and focus changed was changed as a result
2977     */
2978    boolean ensureTouchMode(boolean inTouchMode) {
2979        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2980                + "touch mode is " + mAttachInfo.mInTouchMode);
2981        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2982
2983        // tell the window manager
2984        try {
2985            sWindowSession.setInTouchMode(inTouchMode);
2986        } catch (RemoteException e) {
2987            throw new RuntimeException(e);
2988        }
2989
2990        // handle the change
2991        return ensureTouchModeLocally(inTouchMode);
2992    }
2993
2994    /**
2995     * Ensure that the touch mode for this window is set, and if it is changing,
2996     * take the appropriate action.
2997     * @param inTouchMode Whether we want to be in touch mode.
2998     * @return True if the touch mode changed and focus changed was changed as a result
2999     */
3000    private boolean ensureTouchModeLocally(boolean inTouchMode) {
3001        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3002                + "touch mode is " + mAttachInfo.mInTouchMode);
3003
3004        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3005
3006        mAttachInfo.mInTouchMode = inTouchMode;
3007        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3008
3009        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3010    }
3011
3012    private boolean enterTouchMode() {
3013        if (mView != null) {
3014            if (mView.hasFocus()) {
3015                // note: not relying on mFocusedView here because this could
3016                // be when the window is first being added, and mFocused isn't
3017                // set yet.
3018                final View focused = mView.findFocus();
3019                if (focused != null) {
3020                    if (focused.isFocusableInTouchMode()) {
3021                        return true;
3022                    }
3023                    final ViewGroup ancestorToTakeFocus =
3024                            findAncestorToTakeFocusInTouchMode(focused);
3025                    if (ancestorToTakeFocus != null) {
3026                        // there is an ancestor that wants focus after its descendants that
3027                        // is focusable in touch mode.. give it focus
3028                        return ancestorToTakeFocus.requestFocus();
3029                    }
3030                }
3031                // nothing appropriate to have focus in touch mode, clear it out
3032                mView.unFocus();
3033                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
3034                mFocusedView = null;
3035                mOldFocusedView = null;
3036                return true;
3037            }
3038        }
3039        return false;
3040    }
3041
3042    /**
3043     * Find an ancestor of focused that wants focus after its descendants and is
3044     * focusable in touch mode.
3045     * @param focused The currently focused view.
3046     * @return An appropriate view, or null if no such view exists.
3047     */
3048    private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3049        ViewParent parent = focused.getParent();
3050        while (parent instanceof ViewGroup) {
3051            final ViewGroup vgParent = (ViewGroup) parent;
3052            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3053                    && vgParent.isFocusableInTouchMode()) {
3054                return vgParent;
3055            }
3056            if (vgParent.isRootNamespace()) {
3057                return null;
3058            } else {
3059                parent = vgParent.getParent();
3060            }
3061        }
3062        return null;
3063    }
3064
3065    private boolean leaveTouchMode() {
3066        if (mView != null) {
3067            boolean inputFocusValid = false;
3068            if (mView.hasFocus()) {
3069                // i learned the hard way to not trust mFocusedView :)
3070                mFocusedView = mView.findFocus();
3071                if (!(mFocusedView instanceof ViewGroup)) {
3072                    // some view has focus, let it keep it
3073                    inputFocusValid = true;
3074                } else if (((ViewGroup) mFocusedView).getDescendantFocusability() !=
3075                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3076                    // some view group has focus, and doesn't prefer its children
3077                    // over itself for focus, so let them keep it.
3078                    inputFocusValid = true;
3079                }
3080            }
3081            // In accessibility mode we always have a view that has the
3082            // accessibility focus and input focus follows it, i.e. we
3083            // try to give input focus to the accessibility focused view.
3084            if (!AccessibilityManager.getInstance(mView.mContext).isEnabled()) {
3085                // If the current input focus is not valid, find the best view to give
3086                // focus to in this brave new non-touch-mode world.
3087                if (!inputFocusValid) {
3088                    final View focused = focusSearch(null, View.FOCUS_DOWN);
3089                    if (focused != null) {
3090                        return focused.requestFocus(View.FOCUS_DOWN);
3091                    }
3092                }
3093            } else {
3094                // If the current input focus is not valid clear it but do not
3095                // give it to another view since the accessibility focus is
3096                // leading now and the input one follows.
3097                if (!inputFocusValid) {
3098                    if (mFocusedView != null) {
3099                        mView.unFocus();
3100                        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, null);
3101                        mFocusedView = null;
3102                        mOldFocusedView = null;
3103                        return true;
3104                    }
3105                }
3106            }
3107        }
3108        return false;
3109    }
3110
3111    private void deliverInputEvent(QueuedInputEvent q) {
3112        if (ViewDebug.DEBUG_LATENCY) {
3113            q.mDeliverTimeNanos = System.nanoTime();
3114        }
3115
3116        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
3117        try {
3118            if (q.mEvent instanceof KeyEvent) {
3119                deliverKeyEvent(q);
3120            } else {
3121                final int source = q.mEvent.getSource();
3122                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3123                    deliverPointerEvent(q);
3124                } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3125                    deliverTrackballEvent(q);
3126                } else {
3127                    deliverGenericMotionEvent(q);
3128                }
3129            }
3130        } finally {
3131            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3132        }
3133    }
3134
3135    private void deliverPointerEvent(QueuedInputEvent q) {
3136        final MotionEvent event = (MotionEvent)q.mEvent;
3137        final boolean isTouchEvent = event.isTouchEvent();
3138        if (mInputEventConsistencyVerifier != null) {
3139            if (isTouchEvent) {
3140                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
3141            } else {
3142                mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3143            }
3144        }
3145
3146        // If there is no view, then the event will not be handled.
3147        if (mView == null || !mAdded) {
3148            finishInputEvent(q, false);
3149            return;
3150        }
3151
3152        // Translate the pointer event for compatibility, if needed.
3153        if (mTranslator != null) {
3154            mTranslator.translateEventInScreenToAppWindow(event);
3155        }
3156
3157        // Enter touch mode on down or scroll.
3158        final int action = event.getAction();
3159        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3160            ensureTouchMode(true);
3161        }
3162
3163        // Offset the scroll position.
3164        if (mCurScrollY != 0) {
3165            event.offsetLocation(0, mCurScrollY);
3166        }
3167        if (MEASURE_LATENCY) {
3168            lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
3169        }
3170
3171        // Remember the touch position for possible drag-initiation.
3172        if (isTouchEvent) {
3173            mLastTouchPoint.x = event.getRawX();
3174            mLastTouchPoint.y = event.getRawY();
3175        }
3176
3177        // Dispatch touch to view hierarchy.
3178        boolean handled = mView.dispatchPointerEvent(event);
3179        if (MEASURE_LATENCY) {
3180            lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
3181        }
3182        if (handled) {
3183            finishInputEvent(q, true);
3184            return;
3185        }
3186
3187        // Pointer event was unhandled.
3188        finishInputEvent(q, false);
3189    }
3190
3191    private void deliverTrackballEvent(QueuedInputEvent q) {
3192        final MotionEvent event = (MotionEvent)q.mEvent;
3193        if (mInputEventConsistencyVerifier != null) {
3194            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
3195        }
3196
3197        // If there is no view, then the event will not be handled.
3198        if (mView == null || !mAdded) {
3199            finishInputEvent(q, false);
3200            return;
3201        }
3202
3203        // Deliver the trackball event to the view.
3204        if (mView.dispatchTrackballEvent(event)) {
3205            // If we reach this, we delivered a trackball event to mView and
3206            // mView consumed it. Because we will not translate the trackball
3207            // event into a key event, touch mode will not exit, so we exit
3208            // touch mode here.
3209            ensureTouchMode(false);
3210
3211            finishInputEvent(q, true);
3212            mLastTrackballTime = Integer.MIN_VALUE;
3213            return;
3214        }
3215
3216        // Translate the trackball event into DPAD keys and try to deliver those.
3217        final TrackballAxis x = mTrackballAxisX;
3218        final TrackballAxis y = mTrackballAxisY;
3219
3220        long curTime = SystemClock.uptimeMillis();
3221        if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
3222            // It has been too long since the last movement,
3223            // so restart at the beginning.
3224            x.reset(0);
3225            y.reset(0);
3226            mLastTrackballTime = curTime;
3227        }
3228
3229        final int action = event.getAction();
3230        final int metaState = event.getMetaState();
3231        switch (action) {
3232            case MotionEvent.ACTION_DOWN:
3233                x.reset(2);
3234                y.reset(2);
3235                enqueueInputEvent(new KeyEvent(curTime, curTime,
3236                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3237                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3238                        InputDevice.SOURCE_KEYBOARD));
3239                break;
3240            case MotionEvent.ACTION_UP:
3241                x.reset(2);
3242                y.reset(2);
3243                enqueueInputEvent(new KeyEvent(curTime, curTime,
3244                        KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3245                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3246                        InputDevice.SOURCE_KEYBOARD));
3247                break;
3248        }
3249
3250        if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
3251                + x.step + " dir=" + x.dir + " acc=" + x.acceleration
3252                + " move=" + event.getX()
3253                + " / Y=" + y.position + " step="
3254                + y.step + " dir=" + y.dir + " acc=" + y.acceleration
3255                + " move=" + event.getY());
3256        final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
3257        final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
3258
3259        // Generate DPAD events based on the trackball movement.
3260        // We pick the axis that has moved the most as the direction of
3261        // the DPAD.  When we generate DPAD events for one axis, then the
3262        // other axis is reset -- we don't want to perform DPAD jumps due
3263        // to slight movements in the trackball when making major movements
3264        // along the other axis.
3265        int keycode = 0;
3266        int movement = 0;
3267        float accel = 1;
3268        if (xOff > yOff) {
3269            movement = x.generate((2/event.getXPrecision()));
3270            if (movement != 0) {
3271                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
3272                        : KeyEvent.KEYCODE_DPAD_LEFT;
3273                accel = x.acceleration;
3274                y.reset(2);
3275            }
3276        } else if (yOff > 0) {
3277            movement = y.generate((2/event.getYPrecision()));
3278            if (movement != 0) {
3279                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
3280                        : KeyEvent.KEYCODE_DPAD_UP;
3281                accel = y.acceleration;
3282                x.reset(2);
3283            }
3284        }
3285
3286        if (keycode != 0) {
3287            if (movement < 0) movement = -movement;
3288            int accelMovement = (int)(movement * accel);
3289            if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
3290                    + " accelMovement=" + accelMovement
3291                    + " accel=" + accel);
3292            if (accelMovement > movement) {
3293                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3294                        + keycode);
3295                movement--;
3296                int repeatCount = accelMovement - movement;
3297                enqueueInputEvent(new KeyEvent(curTime, curTime,
3298                        KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
3299                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3300                        InputDevice.SOURCE_KEYBOARD));
3301            }
3302            while (movement > 0) {
3303                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3304                        + keycode);
3305                movement--;
3306                curTime = SystemClock.uptimeMillis();
3307                enqueueInputEvent(new KeyEvent(curTime, curTime,
3308                        KeyEvent.ACTION_DOWN, keycode, 0, metaState,
3309                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3310                        InputDevice.SOURCE_KEYBOARD));
3311                enqueueInputEvent(new KeyEvent(curTime, curTime,
3312                        KeyEvent.ACTION_UP, keycode, 0, metaState,
3313                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3314                        InputDevice.SOURCE_KEYBOARD));
3315            }
3316            mLastTrackballTime = curTime;
3317        }
3318
3319        // Unfortunately we can't tell whether the application consumed the keys, so
3320        // we always consider the trackball event handled.
3321        finishInputEvent(q, true);
3322    }
3323
3324    private void deliverGenericMotionEvent(QueuedInputEvent q) {
3325        final MotionEvent event = (MotionEvent)q.mEvent;
3326        if (mInputEventConsistencyVerifier != null) {
3327            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3328        }
3329
3330        final int source = event.getSource();
3331        final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
3332
3333        // If there is no view, then the event will not be handled.
3334        if (mView == null || !mAdded) {
3335            if (isJoystick) {
3336                updateJoystickDirection(event, false);
3337            }
3338            finishInputEvent(q, false);
3339            return;
3340        }
3341
3342        // Deliver the event to the view.
3343        if (mView.dispatchGenericMotionEvent(event)) {
3344            if (isJoystick) {
3345                updateJoystickDirection(event, false);
3346            }
3347            finishInputEvent(q, true);
3348            return;
3349        }
3350
3351        if (isJoystick) {
3352            // Translate the joystick event into DPAD keys and try to deliver those.
3353            updateJoystickDirection(event, true);
3354            finishInputEvent(q, true);
3355        } else {
3356            finishInputEvent(q, false);
3357        }
3358    }
3359
3360    private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
3361        final long time = event.getEventTime();
3362        final int metaState = event.getMetaState();
3363        final int deviceId = event.getDeviceId();
3364        final int source = event.getSource();
3365
3366        int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
3367        if (xDirection == 0) {
3368            xDirection = joystickAxisValueToDirection(event.getX());
3369        }
3370
3371        int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
3372        if (yDirection == 0) {
3373            yDirection = joystickAxisValueToDirection(event.getY());
3374        }
3375
3376        if (xDirection != mLastJoystickXDirection) {
3377            if (mLastJoystickXKeyCode != 0) {
3378                enqueueInputEvent(new KeyEvent(time, time,
3379                        KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
3380                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3381                mLastJoystickXKeyCode = 0;
3382            }
3383
3384            mLastJoystickXDirection = xDirection;
3385
3386            if (xDirection != 0 && synthesizeNewKeys) {
3387                mLastJoystickXKeyCode = xDirection > 0
3388                        ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3389                enqueueInputEvent(new KeyEvent(time, time,
3390                        KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3391                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3392            }
3393        }
3394
3395        if (yDirection != mLastJoystickYDirection) {
3396            if (mLastJoystickYKeyCode != 0) {
3397                enqueueInputEvent(new KeyEvent(time, time,
3398                        KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3399                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3400                mLastJoystickYKeyCode = 0;
3401            }
3402
3403            mLastJoystickYDirection = yDirection;
3404
3405            if (yDirection != 0 && synthesizeNewKeys) {
3406                mLastJoystickYKeyCode = yDirection > 0
3407                        ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3408                enqueueInputEvent(new KeyEvent(time, time,
3409                        KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3410                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3411            }
3412        }
3413    }
3414
3415    private static int joystickAxisValueToDirection(float value) {
3416        if (value >= 0.5f) {
3417            return 1;
3418        } else if (value <= -0.5f) {
3419            return -1;
3420        } else {
3421            return 0;
3422        }
3423    }
3424
3425    /**
3426     * Returns true if the key is used for keyboard navigation.
3427     * @param keyEvent The key event.
3428     * @return True if the key is used for keyboard navigation.
3429     */
3430    private static boolean isNavigationKey(KeyEvent keyEvent) {
3431        switch (keyEvent.getKeyCode()) {
3432        case KeyEvent.KEYCODE_DPAD_LEFT:
3433        case KeyEvent.KEYCODE_DPAD_RIGHT:
3434        case KeyEvent.KEYCODE_DPAD_UP:
3435        case KeyEvent.KEYCODE_DPAD_DOWN:
3436        case KeyEvent.KEYCODE_DPAD_CENTER:
3437        case KeyEvent.KEYCODE_PAGE_UP:
3438        case KeyEvent.KEYCODE_PAGE_DOWN:
3439        case KeyEvent.KEYCODE_MOVE_HOME:
3440        case KeyEvent.KEYCODE_MOVE_END:
3441        case KeyEvent.KEYCODE_TAB:
3442        case KeyEvent.KEYCODE_SPACE:
3443        case KeyEvent.KEYCODE_ENTER:
3444            return true;
3445        }
3446        return false;
3447    }
3448
3449    /**
3450     * Returns true if the key is used for typing.
3451     * @param keyEvent The key event.
3452     * @return True if the key is used for typing.
3453     */
3454    private static boolean isTypingKey(KeyEvent keyEvent) {
3455        return keyEvent.getUnicodeChar() > 0;
3456    }
3457
3458    /**
3459     * See if the key event means we should leave touch mode (and leave touch mode if so).
3460     * @param event The key event.
3461     * @return Whether this key event should be consumed (meaning the act of
3462     *   leaving touch mode alone is considered the event).
3463     */
3464    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3465        // Only relevant in touch mode.
3466        if (!mAttachInfo.mInTouchMode) {
3467            return false;
3468        }
3469
3470        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3471        final int action = event.getAction();
3472        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3473            return false;
3474        }
3475
3476        // Don't leave touch mode if the IME told us not to.
3477        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3478            return false;
3479        }
3480
3481        // If the key can be used for keyboard navigation then leave touch mode
3482        // and select a focused view if needed (in ensureTouchMode).
3483        // When a new focused view is selected, we consume the navigation key because
3484        // navigation doesn't make much sense unless a view already has focus so
3485        // the key's purpose is to set focus.
3486        if (isNavigationKey(event)) {
3487            return ensureTouchMode(false);
3488        }
3489
3490        // If the key can be used for typing then leave touch mode
3491        // and select a focused view if needed (in ensureTouchMode).
3492        // Always allow the view to process the typing key.
3493        if (isTypingKey(event)) {
3494            ensureTouchMode(false);
3495            return false;
3496        }
3497
3498        return false;
3499    }
3500
3501    private void deliverKeyEvent(QueuedInputEvent q) {
3502        final KeyEvent event = (KeyEvent)q.mEvent;
3503        if (mInputEventConsistencyVerifier != null) {
3504            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3505        }
3506
3507        if ((q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3508            // If there is no view, then the event will not be handled.
3509            if (mView == null || !mAdded) {
3510                finishInputEvent(q, false);
3511                return;
3512            }
3513
3514            if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3515
3516            // Perform predispatching before the IME.
3517            if (mView.dispatchKeyEventPreIme(event)) {
3518                finishInputEvent(q, true);
3519                return;
3520            }
3521
3522            // Dispatch to the IME before propagating down the view hierarchy.
3523            // The IME will eventually call back into handleImeFinishedEvent.
3524            if (mLastWasImTarget) {
3525                InputMethodManager imm = InputMethodManager.peekInstance();
3526                if (imm != null) {
3527                    final int seq = event.getSequenceNumber();
3528                    if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3529                            + seq + " event=" + event);
3530                    imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
3531                    return;
3532                }
3533            }
3534        }
3535
3536        // Not dispatching to IME, continue with post IME actions.
3537        deliverKeyEventPostIme(q);
3538    }
3539
3540    void handleImeFinishedEvent(int seq, boolean handled) {
3541        final QueuedInputEvent q = mCurrentInputEvent;
3542        if (q != null && q.mEvent.getSequenceNumber() == seq) {
3543            final KeyEvent event = (KeyEvent)q.mEvent;
3544            if (DEBUG_IMF) {
3545                Log.v(TAG, "IME finished event: seq=" + seq
3546                        + " handled=" + handled + " event=" + event);
3547            }
3548            if (handled) {
3549                finishInputEvent(q, true);
3550            } else {
3551                deliverKeyEventPostIme(q);
3552            }
3553        } else {
3554            if (DEBUG_IMF) {
3555                Log.v(TAG, "IME finished event: seq=" + seq
3556                        + " handled=" + handled + ", event not found!");
3557            }
3558        }
3559    }
3560
3561    private void deliverKeyEventPostIme(QueuedInputEvent q) {
3562        final KeyEvent event = (KeyEvent)q.mEvent;
3563        if (ViewDebug.DEBUG_LATENCY) {
3564            q.mDeliverPostImeTimeNanos = System.nanoTime();
3565        }
3566
3567        // If the view went away, then the event will not be handled.
3568        if (mView == null || !mAdded) {
3569            finishInputEvent(q, false);
3570            return;
3571        }
3572
3573        // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3574        if (checkForLeavingTouchModeAndConsume(event)) {
3575            finishInputEvent(q, true);
3576            return;
3577        }
3578
3579        // Make sure the fallback event policy sees all keys that will be delivered to the
3580        // view hierarchy.
3581        mFallbackEventHandler.preDispatchKeyEvent(event);
3582
3583        // Deliver the key to the view hierarchy.
3584        if (mView.dispatchKeyEvent(event)) {
3585            finishInputEvent(q, true);
3586            return;
3587        }
3588
3589        // If the Control modifier is held, try to interpret the key as a shortcut.
3590        if (event.getAction() == KeyEvent.ACTION_DOWN
3591                && event.isCtrlPressed()
3592                && event.getRepeatCount() == 0
3593                && !KeyEvent.isModifierKey(event.getKeyCode())) {
3594            if (mView.dispatchKeyShortcutEvent(event)) {
3595                finishInputEvent(q, true);
3596                return;
3597            }
3598        }
3599
3600        // Apply the fallback event policy.
3601        if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3602            finishInputEvent(q, true);
3603            return;
3604        }
3605
3606        // Handle automatic focus changes.
3607        if (event.getAction() == KeyEvent.ACTION_DOWN) {
3608            int direction = 0;
3609            switch (event.getKeyCode()) {
3610                case KeyEvent.KEYCODE_DPAD_LEFT:
3611                    if (event.hasNoModifiers()) {
3612                        direction = View.FOCUS_LEFT;
3613                    }
3614                    break;
3615                case KeyEvent.KEYCODE_DPAD_RIGHT:
3616                    if (event.hasNoModifiers()) {
3617                        direction = View.FOCUS_RIGHT;
3618                    }
3619                    break;
3620                case KeyEvent.KEYCODE_DPAD_UP:
3621                    if (event.hasNoModifiers()) {
3622                        direction = View.FOCUS_UP;
3623                    }
3624                    break;
3625                case KeyEvent.KEYCODE_DPAD_DOWN:
3626                    if (event.hasNoModifiers()) {
3627                        direction = View.FOCUS_DOWN;
3628                    }
3629                    break;
3630                case KeyEvent.KEYCODE_TAB:
3631                    if (event.hasNoModifiers()) {
3632                        direction = View.FOCUS_FORWARD;
3633                    } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3634                        direction = View.FOCUS_BACKWARD;
3635                    }
3636                    break;
3637            }
3638            if (direction != 0) {
3639                View focused = mView.findFocus();
3640                if (focused != null) {
3641                    View v = focused.focusSearch(direction);
3642                    if (v != null && v != focused) {
3643                        // do the math the get the interesting rect
3644                        // of previous focused into the coord system of
3645                        // newly focused view
3646                        focused.getFocusedRect(mTempRect);
3647                        if (mView instanceof ViewGroup) {
3648                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3649                                    focused, mTempRect);
3650                            ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3651                                    v, mTempRect);
3652                        }
3653                        if (v.requestFocus(direction, mTempRect)) {
3654                            playSoundEffect(SoundEffectConstants
3655                                    .getContantForFocusDirection(direction));
3656                            finishInputEvent(q, true);
3657                            return;
3658                        }
3659                    }
3660
3661                    // Give the focused view a last chance to handle the dpad key.
3662                    if (mView.dispatchUnhandledMove(focused, direction)) {
3663                        finishInputEvent(q, true);
3664                        return;
3665                    }
3666                }
3667            }
3668        }
3669
3670        // Key was unhandled.
3671        finishInputEvent(q, false);
3672    }
3673
3674    /* drag/drop */
3675    void setLocalDragState(Object obj) {
3676        mLocalDragState = obj;
3677    }
3678
3679    private void handleDragEvent(DragEvent event) {
3680        // From the root, only drag start/end/location are dispatched.  entered/exited
3681        // are determined and dispatched by the viewgroup hierarchy, who then report
3682        // that back here for ultimate reporting back to the framework.
3683        if (mView != null && mAdded) {
3684            final int what = event.mAction;
3685
3686            if (what == DragEvent.ACTION_DRAG_EXITED) {
3687                // A direct EXITED event means that the window manager knows we've just crossed
3688                // a window boundary, so the current drag target within this one must have
3689                // just been exited.  Send it the usual notifications and then we're done
3690                // for now.
3691                mView.dispatchDragEvent(event);
3692            } else {
3693                // Cache the drag description when the operation starts, then fill it in
3694                // on subsequent calls as a convenience
3695                if (what == DragEvent.ACTION_DRAG_STARTED) {
3696                    mCurrentDragView = null;    // Start the current-recipient tracking
3697                    mDragDescription = event.mClipDescription;
3698                } else {
3699                    event.mClipDescription = mDragDescription;
3700                }
3701
3702                // For events with a [screen] location, translate into window coordinates
3703                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3704                    mDragPoint.set(event.mX, event.mY);
3705                    if (mTranslator != null) {
3706                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3707                    }
3708
3709                    if (mCurScrollY != 0) {
3710                        mDragPoint.offset(0, mCurScrollY);
3711                    }
3712
3713                    event.mX = mDragPoint.x;
3714                    event.mY = mDragPoint.y;
3715                }
3716
3717                // Remember who the current drag target is pre-dispatch
3718                final View prevDragView = mCurrentDragView;
3719
3720                // Now dispatch the drag/drop event
3721                boolean result = mView.dispatchDragEvent(event);
3722
3723                // If we changed apparent drag target, tell the OS about it
3724                if (prevDragView != mCurrentDragView) {
3725                    try {
3726                        if (prevDragView != null) {
3727                            sWindowSession.dragRecipientExited(mWindow);
3728                        }
3729                        if (mCurrentDragView != null) {
3730                            sWindowSession.dragRecipientEntered(mWindow);
3731                        }
3732                    } catch (RemoteException e) {
3733                        Slog.e(TAG, "Unable to note drag target change");
3734                    }
3735                }
3736
3737                // Report the drop result when we're done
3738                if (what == DragEvent.ACTION_DROP) {
3739                    mDragDescription = null;
3740                    try {
3741                        Log.i(TAG, "Reporting drop result: " + result);
3742                        sWindowSession.reportDropResult(mWindow, result);
3743                    } catch (RemoteException e) {
3744                        Log.e(TAG, "Unable to report drop result");
3745                    }
3746                }
3747
3748                // When the drag operation ends, release any local state object
3749                // that may have been in use
3750                if (what == DragEvent.ACTION_DRAG_ENDED) {
3751                    setLocalDragState(null);
3752                }
3753            }
3754        }
3755        event.recycle();
3756    }
3757
3758    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
3759        if (mSeq != args.seq) {
3760            // The sequence has changed, so we need to update our value and make
3761            // sure to do a traversal afterward so the window manager is given our
3762            // most recent data.
3763            mSeq = args.seq;
3764            mAttachInfo.mForceReportNewAttributes = true;
3765            scheduleTraversals();
3766        }
3767        if (mView == null) return;
3768        if (args.localChanges != 0) {
3769            if (mAttachInfo != null) {
3770                mAttachInfo.mRecomputeGlobalAttributes = true;
3771            }
3772            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
3773            scheduleTraversals();
3774        }
3775        mView.dispatchSystemUiVisibilityChanged(args.globalVisibility);
3776    }
3777
3778    public void handleDispatchDoneAnimating() {
3779        if (mWindowsAnimating) {
3780            mWindowsAnimating = false;
3781            if (!mDirty.isEmpty() || mIsAnimating)  {
3782                scheduleTraversals();
3783            }
3784        }
3785    }
3786
3787    public void getLastTouchPoint(Point outLocation) {
3788        outLocation.x = (int) mLastTouchPoint.x;
3789        outLocation.y = (int) mLastTouchPoint.y;
3790    }
3791
3792    public void setDragFocus(View newDragTarget) {
3793        if (mCurrentDragView != newDragTarget) {
3794            mCurrentDragView = newDragTarget;
3795        }
3796    }
3797
3798    private AudioManager getAudioManager() {
3799        if (mView == null) {
3800            throw new IllegalStateException("getAudioManager called when there is no mView");
3801        }
3802        if (mAudioManager == null) {
3803            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3804        }
3805        return mAudioManager;
3806    }
3807
3808    public AccessibilityInteractionController getAccessibilityInteractionController() {
3809        if (mView == null) {
3810            throw new IllegalStateException("getAccessibilityInteractionController"
3811                    + " called when there is no mView");
3812        }
3813        if (mAccessibilityInteractionController == null) {
3814            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
3815        }
3816        return mAccessibilityInteractionController;
3817    }
3818
3819    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3820            boolean insetsPending) throws RemoteException {
3821
3822        float appScale = mAttachInfo.mApplicationScale;
3823        boolean restore = false;
3824        if (params != null && mTranslator != null) {
3825            restore = true;
3826            params.backup();
3827            mTranslator.translateWindowLayout(params);
3828        }
3829        if (params != null) {
3830            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
3831        }
3832        mPendingConfiguration.seq = 0;
3833        //Log.d(TAG, ">>>>>> CALLING relayout");
3834        if (params != null && mOrigWindowType != params.type) {
3835            // For compatibility with old apps, don't crash here.
3836            if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
3837                Slog.w(TAG, "Window type can not be changed after "
3838                        + "the window is added; ignoring change of " + mView);
3839                params.type = mOrigWindowType;
3840            }
3841        }
3842        int relayoutResult = sWindowSession.relayout(
3843                mWindow, mSeq, params,
3844                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3845                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
3846                viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0,
3847                mWinFrame, mPendingContentInsets, mPendingVisibleInsets,
3848                mPendingConfiguration, mSurface);
3849        //Log.d(TAG, "<<<<<< BACK FROM relayout");
3850        if (restore) {
3851            params.restore();
3852        }
3853
3854        if (mTranslator != null) {
3855            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3856            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3857            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
3858        }
3859        return relayoutResult;
3860    }
3861
3862    /**
3863     * {@inheritDoc}
3864     */
3865    public void playSoundEffect(int effectId) {
3866        checkThread();
3867
3868        try {
3869            final AudioManager audioManager = getAudioManager();
3870
3871            switch (effectId) {
3872                case SoundEffectConstants.CLICK:
3873                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3874                    return;
3875                case SoundEffectConstants.NAVIGATION_DOWN:
3876                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3877                    return;
3878                case SoundEffectConstants.NAVIGATION_LEFT:
3879                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3880                    return;
3881                case SoundEffectConstants.NAVIGATION_RIGHT:
3882                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3883                    return;
3884                case SoundEffectConstants.NAVIGATION_UP:
3885                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3886                    return;
3887                default:
3888                    throw new IllegalArgumentException("unknown effect id " + effectId +
3889                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
3890            }
3891        } catch (IllegalStateException e) {
3892            // Exception thrown by getAudioManager() when mView is null
3893            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3894            e.printStackTrace();
3895        }
3896    }
3897
3898    /**
3899     * {@inheritDoc}
3900     */
3901    public boolean performHapticFeedback(int effectId, boolean always) {
3902        try {
3903            return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3904        } catch (RemoteException e) {
3905            return false;
3906        }
3907    }
3908
3909    /**
3910     * {@inheritDoc}
3911     */
3912    public View focusSearch(View focused, int direction) {
3913        checkThread();
3914        if (!(mView instanceof ViewGroup)) {
3915            return null;
3916        }
3917        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3918    }
3919
3920    public void debug() {
3921        mView.debug();
3922    }
3923
3924    public void dumpGfxInfo(int[] info) {
3925        if (mView != null) {
3926            getGfxInfo(mView, info);
3927        } else {
3928            info[0] = info[1] = 0;
3929        }
3930    }
3931
3932    private static void getGfxInfo(View view, int[] info) {
3933        DisplayList displayList = view.mDisplayList;
3934        info[0]++;
3935        if (displayList != null) {
3936            info[1] += displayList.getSize();
3937        }
3938
3939        if (view instanceof ViewGroup) {
3940            ViewGroup group = (ViewGroup) view;
3941
3942            int count = group.getChildCount();
3943            for (int i = 0; i < count; i++) {
3944                getGfxInfo(group.getChildAt(i), info);
3945            }
3946        }
3947    }
3948
3949    public void die(boolean immediate) {
3950        if (immediate) {
3951            doDie();
3952        } else {
3953            destroyHardwareRenderer();
3954            mHandler.sendEmptyMessage(MSG_DIE);
3955        }
3956    }
3957
3958    void doDie() {
3959        checkThread();
3960        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
3961        synchronized (this) {
3962            if (mAdded) {
3963                dispatchDetachedFromWindow();
3964            }
3965
3966            if (mAdded && !mFirst) {
3967                destroyHardwareRenderer();
3968
3969                if (mView != null) {
3970                    int viewVisibility = mView.getVisibility();
3971                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3972                    if (mWindowAttributesChanged || viewVisibilityChanged) {
3973                        // If layout params have been changed, first give them
3974                        // to the window manager to make sure it has the correct
3975                        // animation info.
3976                        try {
3977                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3978                                    & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) {
3979                                sWindowSession.finishDrawing(mWindow);
3980                            }
3981                        } catch (RemoteException e) {
3982                        }
3983                    }
3984
3985                    mSurface.release();
3986                }
3987            }
3988
3989            mAdded = false;
3990        }
3991    }
3992
3993    public void requestUpdateConfiguration(Configuration config) {
3994        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
3995        mHandler.sendMessage(msg);
3996    }
3997
3998    private void destroyHardwareRenderer() {
3999        AttachInfo attachInfo = mAttachInfo;
4000        HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer;
4001
4002        if (hardwareRenderer != null) {
4003            if (mView != null) {
4004                hardwareRenderer.destroyHardwareResources(mView);
4005            }
4006            hardwareRenderer.destroy(true);
4007            hardwareRenderer.setRequested(false);
4008
4009            attachInfo.mHardwareRenderer = null;
4010            attachInfo.mHardwareAccelerated = false;
4011        }
4012    }
4013
4014    void dispatchImeFinishedEvent(int seq, boolean handled) {
4015        Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT);
4016        msg.arg1 = seq;
4017        msg.arg2 = handled ? 1 : 0;
4018        msg.setAsynchronous(true);
4019        mHandler.sendMessage(msg);
4020    }
4021
4022    public void dispatchFinishInputConnection(InputConnection connection) {
4023        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
4024        mHandler.sendMessage(msg);
4025    }
4026
4027    public void dispatchResized(int w, int h, Rect coveredInsets,
4028            Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4029        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
4030                + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
4031                + " visibleInsets=" + visibleInsets.toShortString()
4032                + " reportDraw=" + reportDraw);
4033        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED);
4034        if (mTranslator != null) {
4035            mTranslator.translateRectInScreenToAppWindow(coveredInsets);
4036            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
4037            w *= mTranslator.applicationInvertedScale;
4038            h *= mTranslator.applicationInvertedScale;
4039        }
4040        msg.arg1 = w;
4041        msg.arg2 = h;
4042        ResizedInfo ri = new ResizedInfo();
4043        ri.coveredInsets = new Rect(coveredInsets);
4044        ri.visibleInsets = new Rect(visibleInsets);
4045        ri.newConfig = newConfig;
4046        msg.obj = ri;
4047        mHandler.sendMessage(msg);
4048    }
4049
4050    /**
4051     * Represents a pending input event that is waiting in a queue.
4052     *
4053     * Input events are processed in serial order by the timestamp specified by
4054     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
4055     * one input event to the application at a time and waits for the application
4056     * to finish handling it before delivering the next one.
4057     *
4058     * However, because the application or IME can synthesize and inject multiple
4059     * key events at a time without going through the input dispatcher, we end up
4060     * needing a queue on the application's side.
4061     */
4062    private static final class QueuedInputEvent {
4063        public static final int FLAG_DELIVER_POST_IME = 1;
4064
4065        public QueuedInputEvent mNext;
4066
4067        public InputEvent mEvent;
4068        public InputEventReceiver mReceiver;
4069        public int mFlags;
4070
4071        // Used for latency calculations.
4072        public long mReceiveTimeNanos;
4073        public long mDeliverTimeNanos;
4074        public long mDeliverPostImeTimeNanos;
4075    }
4076
4077    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
4078            InputEventReceiver receiver, int flags) {
4079        QueuedInputEvent q = mQueuedInputEventPool;
4080        if (q != null) {
4081            mQueuedInputEventPoolSize -= 1;
4082            mQueuedInputEventPool = q.mNext;
4083            q.mNext = null;
4084        } else {
4085            q = new QueuedInputEvent();
4086        }
4087
4088        q.mEvent = event;
4089        q.mReceiver = receiver;
4090        q.mFlags = flags;
4091        return q;
4092    }
4093
4094    private void recycleQueuedInputEvent(QueuedInputEvent q) {
4095        q.mEvent = null;
4096        q.mReceiver = null;
4097
4098        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
4099            mQueuedInputEventPoolSize += 1;
4100            q.mNext = mQueuedInputEventPool;
4101            mQueuedInputEventPool = q;
4102        }
4103    }
4104
4105    void enqueueInputEvent(InputEvent event) {
4106        enqueueInputEvent(event, null, 0, false);
4107    }
4108
4109    void enqueueInputEvent(InputEvent event,
4110            InputEventReceiver receiver, int flags, boolean processImmediately) {
4111        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
4112
4113        if (ViewDebug.DEBUG_LATENCY) {
4114            q.mReceiveTimeNanos = System.nanoTime();
4115            q.mDeliverTimeNanos = 0;
4116            q.mDeliverPostImeTimeNanos = 0;
4117        }
4118
4119        // Always enqueue the input event in order, regardless of its time stamp.
4120        // We do this because the application or the IME may inject key events
4121        // in response to touch events and we want to ensure that the injected keys
4122        // are processed in the order they were received and we cannot trust that
4123        // the time stamp of injected events are monotonic.
4124        QueuedInputEvent last = mFirstPendingInputEvent;
4125        if (last == null) {
4126            mFirstPendingInputEvent = q;
4127        } else {
4128            while (last.mNext != null) {
4129                last = last.mNext;
4130            }
4131            last.mNext = q;
4132        }
4133
4134        if (processImmediately) {
4135            doProcessInputEvents();
4136        } else {
4137            scheduleProcessInputEvents();
4138        }
4139    }
4140
4141    private void scheduleProcessInputEvents() {
4142        if (!mProcessInputEventsScheduled) {
4143            mProcessInputEventsScheduled = true;
4144            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
4145            msg.setAsynchronous(true);
4146            mHandler.sendMessage(msg);
4147        }
4148    }
4149
4150    void doProcessInputEvents() {
4151        while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) {
4152            QueuedInputEvent q = mFirstPendingInputEvent;
4153            mFirstPendingInputEvent = q.mNext;
4154            q.mNext = null;
4155            mCurrentInputEvent = q;
4156            deliverInputEvent(q);
4157        }
4158
4159        // We are done processing all input events that we can process right now
4160        // so we can clear the pending flag immediately.
4161        if (mProcessInputEventsScheduled) {
4162            mProcessInputEventsScheduled = false;
4163            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
4164        }
4165    }
4166
4167    private void finishInputEvent(QueuedInputEvent q, boolean handled) {
4168        if (q != mCurrentInputEvent) {
4169            throw new IllegalStateException("finished input event out of order");
4170        }
4171
4172        if (ViewDebug.DEBUG_LATENCY) {
4173            final long now = System.nanoTime();
4174            final long eventTime = q.mEvent.getEventTimeNano();
4175            final StringBuilder msg = new StringBuilder();
4176            msg.append("Spent ");
4177            msg.append((now - q.mReceiveTimeNanos) * 0.000001f);
4178            msg.append("ms processing ");
4179            if (q.mEvent instanceof KeyEvent) {
4180                final KeyEvent  keyEvent = (KeyEvent)q.mEvent;
4181                msg.append("key event, action=");
4182                msg.append(KeyEvent.actionToString(keyEvent.getAction()));
4183            } else {
4184                final MotionEvent motionEvent = (MotionEvent)q.mEvent;
4185                msg.append("motion event, action=");
4186                msg.append(MotionEvent.actionToString(motionEvent.getAction()));
4187                msg.append(", historySize=");
4188                msg.append(motionEvent.getHistorySize());
4189            }
4190            msg.append(", handled=");
4191            msg.append(handled);
4192            msg.append(", received at +");
4193            msg.append((q.mReceiveTimeNanos - eventTime) * 0.000001f);
4194            if (q.mDeliverTimeNanos != 0) {
4195                msg.append("ms, delivered at +");
4196                msg.append((q.mDeliverTimeNanos - eventTime) * 0.000001f);
4197            }
4198            if (q.mDeliverPostImeTimeNanos != 0) {
4199                msg.append("ms, delivered post IME at +");
4200                msg.append((q.mDeliverPostImeTimeNanos - eventTime) * 0.000001f);
4201            }
4202            msg.append("ms, finished at +");
4203            msg.append((now - eventTime) * 0.000001f);
4204            msg.append("ms.");
4205            Log.d(ViewDebug.DEBUG_LATENCY_TAG, msg.toString());
4206        }
4207
4208        if (q.mReceiver != null) {
4209            q.mReceiver.finishInputEvent(q.mEvent, handled);
4210        } else {
4211            q.mEvent.recycleIfNeededAfterDispatch();
4212        }
4213
4214        recycleQueuedInputEvent(q);
4215
4216        mCurrentInputEvent = null;
4217        if (mFirstPendingInputEvent != null) {
4218            scheduleProcessInputEvents();
4219        }
4220    }
4221
4222    void scheduleConsumeBatchedInput() {
4223        if (!mConsumeBatchedInputScheduled) {
4224            mConsumeBatchedInputScheduled = true;
4225            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
4226                    mConsumedBatchedInputRunnable, null);
4227        }
4228    }
4229
4230    void unscheduleConsumeBatchedInput() {
4231        if (mConsumeBatchedInputScheduled) {
4232            mConsumeBatchedInputScheduled = false;
4233            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
4234                    mConsumedBatchedInputRunnable, null);
4235        }
4236    }
4237
4238    void doConsumeBatchedInput(boolean callback) {
4239        if (mConsumeBatchedInputScheduled) {
4240            mConsumeBatchedInputScheduled = false;
4241            if (!callback) {
4242                mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
4243                        mConsumedBatchedInputRunnable, null);
4244            }
4245        }
4246
4247        // Always consume batched input events even if not scheduled, because there
4248        // might be new input there waiting for us that we have no noticed yet because
4249        // the Looper has not had a chance to run again.
4250        if (mInputEventReceiver != null) {
4251            mInputEventReceiver.consumeBatchedInputEvents();
4252        }
4253    }
4254
4255    final class TraversalRunnable implements Runnable {
4256        @Override
4257        public void run() {
4258            doTraversal();
4259        }
4260    }
4261    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
4262
4263    final class WindowInputEventReceiver extends InputEventReceiver {
4264        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
4265            super(inputChannel, looper);
4266        }
4267
4268        @Override
4269        public void onInputEvent(InputEvent event) {
4270            enqueueInputEvent(event, this, 0, true);
4271        }
4272
4273        @Override
4274        public void onBatchedInputEventPending() {
4275            scheduleConsumeBatchedInput();
4276        }
4277
4278        @Override
4279        public void dispose() {
4280            unscheduleConsumeBatchedInput();
4281            super.dispose();
4282        }
4283    }
4284    WindowInputEventReceiver mInputEventReceiver;
4285
4286    final class ConsumeBatchedInputRunnable implements Runnable {
4287        @Override
4288        public void run() {
4289            doConsumeBatchedInput(true);
4290            doProcessInputEvents();
4291        }
4292    }
4293    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
4294            new ConsumeBatchedInputRunnable();
4295    boolean mConsumeBatchedInputScheduled;
4296
4297    final class InvalidateOnAnimationRunnable implements Runnable {
4298        private boolean mPosted;
4299        private ArrayList<View> mViews = new ArrayList<View>();
4300        private ArrayList<AttachInfo.InvalidateInfo> mViewRects =
4301                new ArrayList<AttachInfo.InvalidateInfo>();
4302        private View[] mTempViews;
4303        private AttachInfo.InvalidateInfo[] mTempViewRects;
4304
4305        public void addView(View view) {
4306            synchronized (this) {
4307                mViews.add(view);
4308                postIfNeededLocked();
4309            }
4310        }
4311
4312        public void addViewRect(AttachInfo.InvalidateInfo info) {
4313            synchronized (this) {
4314                mViewRects.add(info);
4315                postIfNeededLocked();
4316            }
4317        }
4318
4319        public void removeView(View view) {
4320            synchronized (this) {
4321                mViews.remove(view);
4322
4323                for (int i = mViewRects.size(); i-- > 0; ) {
4324                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
4325                    if (info.target == view) {
4326                        mViewRects.remove(i);
4327                        info.release();
4328                    }
4329                }
4330
4331                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
4332                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
4333                    mPosted = false;
4334                }
4335            }
4336        }
4337
4338        @Override
4339        public void run() {
4340            final int viewCount;
4341            final int viewRectCount;
4342            synchronized (this) {
4343                mPosted = false;
4344
4345                viewCount = mViews.size();
4346                if (viewCount != 0) {
4347                    mTempViews = mViews.toArray(mTempViews != null
4348                            ? mTempViews : new View[viewCount]);
4349                    mViews.clear();
4350                }
4351
4352                viewRectCount = mViewRects.size();
4353                if (viewRectCount != 0) {
4354                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
4355                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
4356                    mViewRects.clear();
4357                }
4358            }
4359
4360            for (int i = 0; i < viewCount; i++) {
4361                mTempViews[i].invalidate();
4362            }
4363
4364            for (int i = 0; i < viewRectCount; i++) {
4365                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
4366                info.target.invalidate(info.left, info.top, info.right, info.bottom);
4367                info.release();
4368            }
4369        }
4370
4371        private void postIfNeededLocked() {
4372            if (!mPosted) {
4373                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
4374                mPosted = true;
4375            }
4376        }
4377    }
4378    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
4379            new InvalidateOnAnimationRunnable();
4380
4381    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
4382        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
4383        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4384    }
4385
4386    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
4387            long delayMilliseconds) {
4388        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
4389        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4390    }
4391
4392    public void dispatchInvalidateOnAnimation(View view) {
4393        mInvalidateOnAnimationRunnable.addView(view);
4394    }
4395
4396    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
4397        mInvalidateOnAnimationRunnable.addViewRect(info);
4398    }
4399
4400    public void invalidateDisplayList(DisplayList displayList) {
4401        mDisplayLists.add(displayList);
4402
4403        mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST);
4404        Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST);
4405        mHandler.sendMessage(msg);
4406    }
4407
4408    public void cancelInvalidate(View view) {
4409        mHandler.removeMessages(MSG_INVALIDATE, view);
4410        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
4411        // them to the pool
4412        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
4413        mInvalidateOnAnimationRunnable.removeView(view);
4414    }
4415
4416    public void dispatchKey(KeyEvent event) {
4417        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event);
4418        msg.setAsynchronous(true);
4419        mHandler.sendMessage(msg);
4420    }
4421
4422    public void dispatchKeyFromIme(KeyEvent event) {
4423        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
4424        msg.setAsynchronous(true);
4425        mHandler.sendMessage(msg);
4426    }
4427
4428    public void dispatchUnhandledKey(KeyEvent event) {
4429        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4430            final KeyCharacterMap kcm = event.getKeyCharacterMap();
4431            final int keyCode = event.getKeyCode();
4432            final int metaState = event.getMetaState();
4433
4434            KeyEvent fallbackEvent = null;
4435            synchronized (mFallbackAction) {
4436                // Check for fallback actions specified by the key character map.
4437                if (kcm.getFallbackAction(keyCode, metaState, mFallbackAction)) {
4438                    int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
4439                    fallbackEvent = KeyEvent.obtain(
4440                            event.getDownTime(), event.getEventTime(),
4441                            event.getAction(), mFallbackAction.keyCode,
4442                            event.getRepeatCount(), mFallbackAction.metaState,
4443                            event.getDeviceId(), event.getScanCode(),
4444                            flags, event.getSource(), null);
4445                }
4446            }
4447            if (fallbackEvent != null) {
4448                dispatchKey(fallbackEvent);
4449            }
4450        }
4451    }
4452
4453    public void dispatchAppVisibility(boolean visible) {
4454        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
4455        msg.arg1 = visible ? 1 : 0;
4456        mHandler.sendMessage(msg);
4457    }
4458
4459    public void dispatchScreenStateChange(boolean on) {
4460        Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE);
4461        msg.arg1 = on ? 1 : 0;
4462        mHandler.sendMessage(msg);
4463    }
4464
4465    public void dispatchGetNewSurface() {
4466        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
4467        mHandler.sendMessage(msg);
4468    }
4469
4470    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4471        Message msg = Message.obtain();
4472        msg.what = MSG_WINDOW_FOCUS_CHANGED;
4473        msg.arg1 = hasFocus ? 1 : 0;
4474        msg.arg2 = inTouchMode ? 1 : 0;
4475        mHandler.sendMessage(msg);
4476    }
4477
4478    public void dispatchCloseSystemDialogs(String reason) {
4479        Message msg = Message.obtain();
4480        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
4481        msg.obj = reason;
4482        mHandler.sendMessage(msg);
4483    }
4484
4485    public void dispatchDragEvent(DragEvent event) {
4486        final int what;
4487        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
4488            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
4489            mHandler.removeMessages(what);
4490        } else {
4491            what = MSG_DISPATCH_DRAG_EVENT;
4492        }
4493        Message msg = mHandler.obtainMessage(what, event);
4494        mHandler.sendMessage(msg);
4495    }
4496
4497    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4498            int localValue, int localChanges) {
4499        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
4500        args.seq = seq;
4501        args.globalVisibility = globalVisibility;
4502        args.localValue = localValue;
4503        args.localChanges = localChanges;
4504        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
4505    }
4506
4507    public void dispatchDoneAnimating() {
4508        mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
4509    }
4510
4511    public void dispatchCheckFocus() {
4512        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
4513            // This will result in a call to checkFocus() below.
4514            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
4515        }
4516    }
4517
4518    /**
4519     * Post a callback to send a
4520     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4521     * This event is send at most once every
4522     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
4523     */
4524    private void postSendWindowContentChangedCallback(View source) {
4525        if (mSendWindowContentChangedAccessibilityEvent == null) {
4526            mSendWindowContentChangedAccessibilityEvent =
4527                new SendWindowContentChangedAccessibilityEvent();
4528        }
4529        View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource;
4530        if (oldSource == null) {
4531            mSendWindowContentChangedAccessibilityEvent.mSource = source;
4532            mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent,
4533                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
4534        } else {
4535            mSendWindowContentChangedAccessibilityEvent.mSource =
4536                    getCommonPredecessor(oldSource, source);
4537        }
4538    }
4539
4540    /**
4541     * Remove a posted callback to send a
4542     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4543     */
4544    private void removeSendWindowContentChangedCallback() {
4545        if (mSendWindowContentChangedAccessibilityEvent != null) {
4546            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
4547        }
4548    }
4549
4550    public boolean showContextMenuForChild(View originalView) {
4551        return false;
4552    }
4553
4554    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
4555        return null;
4556    }
4557
4558    public void createContextMenu(ContextMenu menu) {
4559    }
4560
4561    public void childDrawableStateChanged(View child) {
4562    }
4563
4564    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
4565        if (mView == null) {
4566            return false;
4567        }
4568        mAccessibilityManager.sendAccessibilityEvent(event);
4569        return true;
4570    }
4571
4572    @Override
4573    public void childAccessibilityStateChanged(View child) {
4574        postSendWindowContentChangedCallback(child);
4575    }
4576
4577    private View getCommonPredecessor(View first, View second) {
4578        if (mAttachInfo != null) {
4579            if (mTempHashSet == null) {
4580                mTempHashSet = new HashSet<View>();
4581            }
4582            HashSet<View> seen = mTempHashSet;
4583            seen.clear();
4584            View firstCurrent = first;
4585            while (firstCurrent != null) {
4586                seen.add(firstCurrent);
4587                ViewParent firstCurrentParent = firstCurrent.mParent;
4588                if (firstCurrentParent instanceof View) {
4589                    firstCurrent = (View) firstCurrentParent;
4590                } else {
4591                    firstCurrent = null;
4592                }
4593            }
4594            View secondCurrent = second;
4595            while (secondCurrent != null) {
4596                if (seen.contains(secondCurrent)) {
4597                    seen.clear();
4598                    return secondCurrent;
4599                }
4600                ViewParent secondCurrentParent = secondCurrent.mParent;
4601                if (secondCurrentParent instanceof View) {
4602                    secondCurrent = (View) secondCurrentParent;
4603                } else {
4604                    secondCurrent = null;
4605                }
4606            }
4607            seen.clear();
4608        }
4609        return null;
4610    }
4611
4612    void checkThread() {
4613        if (mThread != Thread.currentThread()) {
4614            throw new CalledFromWrongThreadException(
4615                    "Only the original thread that created a view hierarchy can touch its views.");
4616        }
4617    }
4618
4619    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
4620        // ViewAncestor never intercepts touch event, so this can be a no-op
4621    }
4622
4623    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
4624            boolean immediate) {
4625        return scrollToRectOrFocus(rectangle, immediate);
4626    }
4627
4628    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
4629        // Do nothing.
4630    }
4631
4632    class TakenSurfaceHolder extends BaseSurfaceHolder {
4633        @Override
4634        public boolean onAllowLockCanvas() {
4635            return mDrawingAllowed;
4636        }
4637
4638        @Override
4639        public void onRelayoutContainer() {
4640            // Not currently interesting -- from changing between fixed and layout size.
4641        }
4642
4643        public void setFormat(int format) {
4644            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
4645        }
4646
4647        public void setType(int type) {
4648            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
4649        }
4650
4651        @Override
4652        public void onUpdateSurface() {
4653            // We take care of format and type changes on our own.
4654            throw new IllegalStateException("Shouldn't be here");
4655        }
4656
4657        public boolean isCreating() {
4658            return mIsCreating;
4659        }
4660
4661        @Override
4662        public void setFixedSize(int width, int height) {
4663            throw new UnsupportedOperationException(
4664                    "Currently only support sizing from layout");
4665        }
4666
4667        public void setKeepScreenOn(boolean screenOn) {
4668            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
4669        }
4670    }
4671
4672    static class InputMethodCallback extends IInputMethodCallback.Stub {
4673        private WeakReference<ViewRootImpl> mViewAncestor;
4674
4675        public InputMethodCallback(ViewRootImpl viewAncestor) {
4676            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4677        }
4678
4679        public void finishedEvent(int seq, boolean handled) {
4680            final ViewRootImpl viewAncestor = mViewAncestor.get();
4681            if (viewAncestor != null) {
4682                viewAncestor.dispatchImeFinishedEvent(seq, handled);
4683            }
4684        }
4685
4686        public void sessionCreated(IInputMethodSession session) {
4687            // Stub -- not for use in the client.
4688        }
4689    }
4690
4691    static class W extends IWindow.Stub {
4692        private final WeakReference<ViewRootImpl> mViewAncestor;
4693
4694        W(ViewRootImpl viewAncestor) {
4695            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4696        }
4697
4698        public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
4699                boolean reportDraw, Configuration newConfig) {
4700            final ViewRootImpl viewAncestor = mViewAncestor.get();
4701            if (viewAncestor != null) {
4702                viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw,
4703                        newConfig);
4704            }
4705        }
4706
4707        public void dispatchAppVisibility(boolean visible) {
4708            final ViewRootImpl viewAncestor = mViewAncestor.get();
4709            if (viewAncestor != null) {
4710                viewAncestor.dispatchAppVisibility(visible);
4711            }
4712        }
4713
4714        public void dispatchScreenState(boolean on) {
4715            final ViewRootImpl viewAncestor = mViewAncestor.get();
4716            if (viewAncestor != null) {
4717                viewAncestor.dispatchScreenStateChange(on);
4718            }
4719        }
4720
4721        public void dispatchGetNewSurface() {
4722            final ViewRootImpl viewAncestor = mViewAncestor.get();
4723            if (viewAncestor != null) {
4724                viewAncestor.dispatchGetNewSurface();
4725            }
4726        }
4727
4728        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4729            final ViewRootImpl viewAncestor = mViewAncestor.get();
4730            if (viewAncestor != null) {
4731                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
4732            }
4733        }
4734
4735        private static int checkCallingPermission(String permission) {
4736            try {
4737                return ActivityManagerNative.getDefault().checkPermission(
4738                        permission, Binder.getCallingPid(), Binder.getCallingUid());
4739            } catch (RemoteException e) {
4740                return PackageManager.PERMISSION_DENIED;
4741            }
4742        }
4743
4744        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
4745            final ViewRootImpl viewAncestor = mViewAncestor.get();
4746            if (viewAncestor != null) {
4747                final View view = viewAncestor.mView;
4748                if (view != null) {
4749                    if (checkCallingPermission(Manifest.permission.DUMP) !=
4750                            PackageManager.PERMISSION_GRANTED) {
4751                        throw new SecurityException("Insufficient permissions to invoke"
4752                                + " executeCommand() from pid=" + Binder.getCallingPid()
4753                                + ", uid=" + Binder.getCallingUid());
4754                    }
4755
4756                    OutputStream clientStream = null;
4757                    try {
4758                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
4759                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
4760                    } catch (IOException e) {
4761                        e.printStackTrace();
4762                    } finally {
4763                        if (clientStream != null) {
4764                            try {
4765                                clientStream.close();
4766                            } catch (IOException e) {
4767                                e.printStackTrace();
4768                            }
4769                        }
4770                    }
4771                }
4772            }
4773        }
4774
4775        public void closeSystemDialogs(String reason) {
4776            final ViewRootImpl viewAncestor = mViewAncestor.get();
4777            if (viewAncestor != null) {
4778                viewAncestor.dispatchCloseSystemDialogs(reason);
4779            }
4780        }
4781
4782        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
4783                boolean sync) {
4784            if (sync) {
4785                try {
4786                    sWindowSession.wallpaperOffsetsComplete(asBinder());
4787                } catch (RemoteException e) {
4788                }
4789            }
4790        }
4791
4792        public void dispatchWallpaperCommand(String action, int x, int y,
4793                int z, Bundle extras, boolean sync) {
4794            if (sync) {
4795                try {
4796                    sWindowSession.wallpaperCommandComplete(asBinder(), null);
4797                } catch (RemoteException e) {
4798                }
4799            }
4800        }
4801
4802        /* Drag/drop */
4803        public void dispatchDragEvent(DragEvent event) {
4804            final ViewRootImpl viewAncestor = mViewAncestor.get();
4805            if (viewAncestor != null) {
4806                viewAncestor.dispatchDragEvent(event);
4807            }
4808        }
4809
4810        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4811                int localValue, int localChanges) {
4812            final ViewRootImpl viewAncestor = mViewAncestor.get();
4813            if (viewAncestor != null) {
4814                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
4815                        localValue, localChanges);
4816            }
4817        }
4818
4819        public void doneAnimating() {
4820            final ViewRootImpl viewAncestor = mViewAncestor.get();
4821            if (viewAncestor != null) {
4822                viewAncestor.dispatchDoneAnimating();
4823            }
4824        }
4825    }
4826
4827    /**
4828     * Maintains state information for a single trackball axis, generating
4829     * discrete (DPAD) movements based on raw trackball motion.
4830     */
4831    static final class TrackballAxis {
4832        /**
4833         * The maximum amount of acceleration we will apply.
4834         */
4835        static final float MAX_ACCELERATION = 20;
4836
4837        /**
4838         * The maximum amount of time (in milliseconds) between events in order
4839         * for us to consider the user to be doing fast trackball movements,
4840         * and thus apply an acceleration.
4841         */
4842        static final long FAST_MOVE_TIME = 150;
4843
4844        /**
4845         * Scaling factor to the time (in milliseconds) between events to how
4846         * much to multiple/divide the current acceleration.  When movement
4847         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4848         * FAST_MOVE_TIME it divides it.
4849         */
4850        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4851
4852        float position;
4853        float absPosition;
4854        float acceleration = 1;
4855        long lastMoveTime = 0;
4856        int step;
4857        int dir;
4858        int nonAccelMovement;
4859
4860        void reset(int _step) {
4861            position = 0;
4862            acceleration = 1;
4863            lastMoveTime = 0;
4864            step = _step;
4865            dir = 0;
4866        }
4867
4868        /**
4869         * Add trackball movement into the state.  If the direction of movement
4870         * has been reversed, the state is reset before adding the
4871         * movement (so that you don't have to compensate for any previously
4872         * collected movement before see the result of the movement in the
4873         * new direction).
4874         *
4875         * @return Returns the absolute value of the amount of movement
4876         * collected so far.
4877         */
4878        float collect(float off, long time, String axis) {
4879            long normTime;
4880            if (off > 0) {
4881                normTime = (long)(off * FAST_MOVE_TIME);
4882                if (dir < 0) {
4883                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4884                    position = 0;
4885                    step = 0;
4886                    acceleration = 1;
4887                    lastMoveTime = 0;
4888                }
4889                dir = 1;
4890            } else if (off < 0) {
4891                normTime = (long)((-off) * FAST_MOVE_TIME);
4892                if (dir > 0) {
4893                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4894                    position = 0;
4895                    step = 0;
4896                    acceleration = 1;
4897                    lastMoveTime = 0;
4898                }
4899                dir = -1;
4900            } else {
4901                normTime = 0;
4902            }
4903
4904            // The number of milliseconds between each movement that is
4905            // considered "normal" and will not result in any acceleration
4906            // or deceleration, scaled by the offset we have here.
4907            if (normTime > 0) {
4908                long delta = time - lastMoveTime;
4909                lastMoveTime = time;
4910                float acc = acceleration;
4911                if (delta < normTime) {
4912                    // The user is scrolling rapidly, so increase acceleration.
4913                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4914                    if (scale > 1) acc *= scale;
4915                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4916                            + off + " normTime=" + normTime + " delta=" + delta
4917                            + " scale=" + scale + " acc=" + acc);
4918                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4919                } else {
4920                    // The user is scrolling slowly, so decrease acceleration.
4921                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4922                    if (scale > 1) acc /= scale;
4923                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4924                            + off + " normTime=" + normTime + " delta=" + delta
4925                            + " scale=" + scale + " acc=" + acc);
4926                    acceleration = acc > 1 ? acc : 1;
4927                }
4928            }
4929            position += off;
4930            return (absPosition = Math.abs(position));
4931        }
4932
4933        /**
4934         * Generate the number of discrete movement events appropriate for
4935         * the currently collected trackball movement.
4936         *
4937         * @param precision The minimum movement required to generate the
4938         * first discrete movement.
4939         *
4940         * @return Returns the number of discrete movements, either positive
4941         * or negative, or 0 if there is not enough trackball movement yet
4942         * for a discrete movement.
4943         */
4944        int generate(float precision) {
4945            int movement = 0;
4946            nonAccelMovement = 0;
4947            do {
4948                final int dir = position >= 0 ? 1 : -1;
4949                switch (step) {
4950                    // If we are going to execute the first step, then we want
4951                    // to do this as soon as possible instead of waiting for
4952                    // a full movement, in order to make things look responsive.
4953                    case 0:
4954                        if (absPosition < precision) {
4955                            return movement;
4956                        }
4957                        movement += dir;
4958                        nonAccelMovement += dir;
4959                        step = 1;
4960                        break;
4961                    // If we have generated the first movement, then we need
4962                    // to wait for the second complete trackball motion before
4963                    // generating the second discrete movement.
4964                    case 1:
4965                        if (absPosition < 2) {
4966                            return movement;
4967                        }
4968                        movement += dir;
4969                        nonAccelMovement += dir;
4970                        position += dir > 0 ? -2 : 2;
4971                        absPosition = Math.abs(position);
4972                        step = 2;
4973                        break;
4974                    // After the first two, we generate discrete movements
4975                    // consistently with the trackball, applying an acceleration
4976                    // if the trackball is moving quickly.  This is a simple
4977                    // acceleration on top of what we already compute based
4978                    // on how quickly the wheel is being turned, to apply
4979                    // a longer increasing acceleration to continuous movement
4980                    // in one direction.
4981                    default:
4982                        if (absPosition < 1) {
4983                            return movement;
4984                        }
4985                        movement += dir;
4986                        position += dir >= 0 ? -1 : 1;
4987                        absPosition = Math.abs(position);
4988                        float acc = acceleration;
4989                        acc *= 1.1f;
4990                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4991                        break;
4992                }
4993            } while (true);
4994        }
4995    }
4996
4997    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
4998        public CalledFromWrongThreadException(String msg) {
4999            super(msg);
5000        }
5001    }
5002
5003    private SurfaceHolder mHolder = new SurfaceHolder() {
5004        // we only need a SurfaceHolder for opengl. it would be nice
5005        // to implement everything else though, especially the callback
5006        // support (opengl doesn't make use of it right now, but eventually
5007        // will).
5008        public Surface getSurface() {
5009            return mSurface;
5010        }
5011
5012        public boolean isCreating() {
5013            return false;
5014        }
5015
5016        public void addCallback(Callback callback) {
5017        }
5018
5019        public void removeCallback(Callback callback) {
5020        }
5021
5022        public void setFixedSize(int width, int height) {
5023        }
5024
5025        public void setSizeFromLayout() {
5026        }
5027
5028        public void setFormat(int format) {
5029        }
5030
5031        public void setType(int type) {
5032        }
5033
5034        public void setKeepScreenOn(boolean screenOn) {
5035        }
5036
5037        public Canvas lockCanvas() {
5038            return null;
5039        }
5040
5041        public Canvas lockCanvas(Rect dirty) {
5042            return null;
5043        }
5044
5045        public void unlockCanvasAndPost(Canvas canvas) {
5046        }
5047        public Rect getSurfaceFrame() {
5048            return null;
5049        }
5050    };
5051
5052    static RunQueue getRunQueue() {
5053        RunQueue rq = sRunQueues.get();
5054        if (rq != null) {
5055            return rq;
5056        }
5057        rq = new RunQueue();
5058        sRunQueues.set(rq);
5059        return rq;
5060    }
5061
5062    /**
5063     * The run queue is used to enqueue pending work from Views when no Handler is
5064     * attached.  The work is executed during the next call to performTraversals on
5065     * the thread.
5066     * @hide
5067     */
5068    static final class RunQueue {
5069        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
5070
5071        void post(Runnable action) {
5072            postDelayed(action, 0);
5073        }
5074
5075        void postDelayed(Runnable action, long delayMillis) {
5076            HandlerAction handlerAction = new HandlerAction();
5077            handlerAction.action = action;
5078            handlerAction.delay = delayMillis;
5079
5080            synchronized (mActions) {
5081                mActions.add(handlerAction);
5082            }
5083        }
5084
5085        void removeCallbacks(Runnable action) {
5086            final HandlerAction handlerAction = new HandlerAction();
5087            handlerAction.action = action;
5088
5089            synchronized (mActions) {
5090                final ArrayList<HandlerAction> actions = mActions;
5091
5092                while (actions.remove(handlerAction)) {
5093                    // Keep going
5094                }
5095            }
5096        }
5097
5098        void executeActions(Handler handler) {
5099            synchronized (mActions) {
5100                final ArrayList<HandlerAction> actions = mActions;
5101                final int count = actions.size();
5102
5103                for (int i = 0; i < count; i++) {
5104                    final HandlerAction handlerAction = actions.get(i);
5105                    handler.postDelayed(handlerAction.action, handlerAction.delay);
5106                }
5107
5108                actions.clear();
5109            }
5110        }
5111
5112        private static class HandlerAction {
5113            Runnable action;
5114            long delay;
5115
5116            @Override
5117            public boolean equals(Object o) {
5118                if (this == o) return true;
5119                if (o == null || getClass() != o.getClass()) return false;
5120
5121                HandlerAction that = (HandlerAction) o;
5122                return !(action != null ? !action.equals(that.action) : that.action != null);
5123
5124            }
5125
5126            @Override
5127            public int hashCode() {
5128                int result = action != null ? action.hashCode() : 0;
5129                result = 31 * result + (int) (delay ^ (delay >>> 32));
5130                return result;
5131            }
5132        }
5133    }
5134
5135    /**
5136     * Class for managing the accessibility interaction connection
5137     * based on the global accessibility state.
5138     */
5139    final class AccessibilityInteractionConnectionManager
5140            implements AccessibilityStateChangeListener {
5141        public void onAccessibilityStateChanged(boolean enabled) {
5142            if (enabled) {
5143                ensureConnection();
5144                if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
5145                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
5146                    View focusedView = mView.findFocus();
5147                    if (focusedView != null && focusedView != mView) {
5148                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5149                    }
5150                }
5151            } else {
5152                ensureNoConnection();
5153                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
5154            }
5155        }
5156
5157        public void ensureConnection() {
5158            if (mAttachInfo != null) {
5159                final boolean registered =
5160                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5161                if (!registered) {
5162                    mAttachInfo.mAccessibilityWindowId =
5163                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
5164                                new AccessibilityInteractionConnection(ViewRootImpl.this));
5165                }
5166            }
5167        }
5168
5169        public void ensureNoConnection() {
5170            final boolean registered =
5171                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5172            if (registered) {
5173                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED;
5174                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
5175            }
5176        }
5177    }
5178
5179    /**
5180     * This class is an interface this ViewAncestor provides to the
5181     * AccessibilityManagerService to the latter can interact with
5182     * the view hierarchy in this ViewAncestor.
5183     */
5184    static final class AccessibilityInteractionConnection
5185            extends IAccessibilityInteractionConnection.Stub {
5186        private final WeakReference<ViewRootImpl> mViewRootImpl;
5187
5188        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
5189            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
5190        }
5191
5192        @Override
5193        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
5194                int interactionId, IAccessibilityInteractionConnectionCallback callback,
5195                int flags, int interrogatingPid, long interrogatingTid) {
5196            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5197            if (viewRootImpl != null && viewRootImpl.mView != null) {
5198                viewRootImpl.getAccessibilityInteractionController()
5199                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
5200                        interactionId, callback, flags, interrogatingPid, interrogatingTid);
5201            } else {
5202                // We cannot make the call and notify the caller so it does not wait.
5203                try {
5204                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5205                } catch (RemoteException re) {
5206                    /* best effort - ignore */
5207                }
5208            }
5209        }
5210
5211        @Override
5212        public void performAccessibilityAction(long accessibilityNodeId, int action,
5213                Bundle arguments, int interactionId,
5214                IAccessibilityInteractionConnectionCallback callback, int flags,
5215                int interogatingPid, long interrogatingTid) {
5216            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5217            if (viewRootImpl != null && viewRootImpl.mView != null) {
5218                viewRootImpl.getAccessibilityInteractionController()
5219                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
5220                            interactionId, callback, flags, interogatingPid, interrogatingTid);
5221            } else {
5222                // We cannot make the call and notify the caller so it does not wait.
5223                try {
5224                    callback.setPerformAccessibilityActionResult(false, interactionId);
5225                } catch (RemoteException re) {
5226                    /* best effort - ignore */
5227                }
5228            }
5229        }
5230
5231        @Override
5232        public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId,
5233                int interactionId, IAccessibilityInteractionConnectionCallback callback,
5234                int flags, int interrogatingPid, long interrogatingTid) {
5235            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5236            if (viewRootImpl != null && viewRootImpl.mView != null) {
5237                viewRootImpl.getAccessibilityInteractionController()
5238                    .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId,
5239                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
5240            } else {
5241                // We cannot make the call and notify the caller so it does not wait.
5242                try {
5243                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5244                } catch (RemoteException re) {
5245                    /* best effort - ignore */
5246                }
5247            }
5248        }
5249
5250        @Override
5251        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
5252                int interactionId, IAccessibilityInteractionConnectionCallback callback,
5253                int flags, int interrogatingPid, long interrogatingTid) {
5254            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5255            if (viewRootImpl != null && viewRootImpl.mView != null) {
5256                viewRootImpl.getAccessibilityInteractionController()
5257                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
5258                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
5259            } else {
5260                // We cannot make the call and notify the caller so it does not wait.
5261                try {
5262                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5263                } catch (RemoteException re) {
5264                    /* best effort - ignore */
5265                }
5266            }
5267        }
5268
5269        @Override
5270        public void findFocus(long accessibilityNodeId, int interactionId, int focusType,
5271                IAccessibilityInteractionConnectionCallback callback,  int flags,
5272                int interrogatingPid, long interrogatingTid) {
5273            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5274            if (viewRootImpl != null && viewRootImpl.mView != null) {
5275                viewRootImpl.getAccessibilityInteractionController()
5276                    .findFocusClientThread(accessibilityNodeId, interactionId, focusType,
5277                            callback, flags, interrogatingPid, interrogatingTid);
5278            } else {
5279                // We cannot make the call and notify the caller so it does not wait.
5280                try {
5281                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5282                } catch (RemoteException re) {
5283                    /* best effort - ignore */
5284                }
5285            }
5286        }
5287
5288        @Override
5289        public void focusSearch(long accessibilityNodeId, int interactionId, int direction,
5290                IAccessibilityInteractionConnectionCallback callback, int flags,
5291                int interrogatingPid, long interrogatingTid) {
5292            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5293            if (viewRootImpl != null && viewRootImpl.mView != null) {
5294                viewRootImpl.getAccessibilityInteractionController()
5295                    .focusSearchClientThread(accessibilityNodeId, interactionId, direction,
5296                            callback, flags, interrogatingPid, interrogatingTid);
5297            } else {
5298                // We cannot make the call and notify the caller so it does not wait.
5299                try {
5300                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5301                } catch (RemoteException re) {
5302                    /* best effort - ignore */
5303                }
5304            }
5305        }
5306    }
5307
5308    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
5309        public View mSource;
5310
5311        public void run() {
5312            if (mSource != null) {
5313                mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
5314                mSource.resetAccessibilityStateChanged();
5315                mSource = null;
5316            }
5317        }
5318    }
5319}
5320