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