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