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