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