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