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