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