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