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