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