ViewRootImpl.java revision 678a1252b4f3cdc18d20b411c05a4320d1d9b719
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.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.ClipDescription;
25import android.content.ComponentCallbacks;
26import android.content.ComponentCallbacks2;
27import android.content.Context;
28import android.content.Intent;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.PackageManager;
31import android.content.res.CompatibilityInfo;
32import android.content.res.Configuration;
33import android.content.res.Resources;
34import android.graphics.Canvas;
35import android.graphics.Paint;
36import android.graphics.PixelFormat;
37import android.graphics.Point;
38import android.graphics.PointF;
39import android.graphics.PorterDuff;
40import android.graphics.Rect;
41import android.graphics.Region;
42import android.graphics.drawable.Drawable;
43import android.media.AudioManager;
44import android.os.Binder;
45import android.os.Bundle;
46import android.os.Debug;
47import android.os.Handler;
48import android.os.Looper;
49import android.os.Message;
50import android.os.ParcelFileDescriptor;
51import android.os.PowerManager;
52import android.os.Process;
53import android.os.RemoteException;
54import android.os.SystemClock;
55import android.os.SystemProperties;
56import android.os.Trace;
57import android.os.UserHandle;
58import android.util.AndroidRuntimeException;
59import android.util.DisplayMetrics;
60import android.util.Log;
61import android.util.Slog;
62import android.util.TypedValue;
63import android.view.View.AttachInfo;
64import android.view.View.MeasureSpec;
65import android.view.accessibility.AccessibilityEvent;
66import android.view.accessibility.AccessibilityManager;
67import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
68import android.view.accessibility.AccessibilityNodeInfo;
69import android.view.accessibility.AccessibilityNodeProvider;
70import android.view.accessibility.IAccessibilityInteractionConnection;
71import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
72import android.view.animation.AccelerateDecelerateInterpolator;
73import android.view.animation.Interpolator;
74import android.view.inputmethod.InputConnection;
75import android.view.inputmethod.InputMethodManager;
76import android.widget.Scroller;
77
78import com.android.internal.R;
79import com.android.internal.os.SomeArgs;
80import com.android.internal.policy.PolicyManager;
81import com.android.internal.view.BaseSurfaceHolder;
82import com.android.internal.view.RootViewSurfaceTaker;
83
84import java.io.IOException;
85import java.io.OutputStream;
86import java.lang.ref.WeakReference;
87import java.util.ArrayList;
88import java.util.HashSet;
89
90/**
91 * The top of a view hierarchy, implementing the needed protocol between View
92 * and the WindowManager.  This is for the most part an internal implementation
93 * detail of {@link WindowManagerGlobal}.
94 *
95 * {@hide}
96 */
97@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
98public final class ViewRootImpl implements ViewParent,
99        View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
100    private static final String TAG = "ViewRootImpl";
101    private static final boolean DBG = false;
102    private static final boolean LOCAL_LOGV = false;
103    /** @noinspection PointlessBooleanExpression*/
104    private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
105    private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
106    private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
107    private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
108    private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
109    private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
110    private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
111    private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
112    private static final boolean DEBUG_FPS = false;
113    private static final boolean DEBUG_INPUT_PROCESSING = false || LOCAL_LOGV;
114
115    private static final boolean USE_RENDER_THREAD = false;
116
117    /**
118     * Set this system property to true to force the view hierarchy to render
119     * at 60 Hz. This can be used to measure the potential framerate.
120     */
121    private static final String PROPERTY_PROFILE_RENDERING = "viewancestor.profile_rendering";
122
123    /**
124     * Maximum time we allow the user to roll the trackball enough to generate
125     * a key event, before resetting the counters.
126     */
127    static final int MAX_TRACKBALL_DELAY = 250;
128
129    static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
130
131    static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
132    static boolean sFirstDrawComplete = false;
133
134    static final ArrayList<ComponentCallbacks> sConfigCallbacks
135            = new ArrayList<ComponentCallbacks>();
136
137    private static boolean sUseRenderThread = false;
138    private static boolean sRenderThreadQueried = false;
139    private static final Object[] sRenderThreadQueryLock = new Object[0];
140
141    final Context mContext;
142    final IWindowSession mWindowSession;
143    final Display mDisplay;
144    final String mBasePackageName;
145
146    final int[] mTmpLocation = new int[2];
147
148    final TypedValue mTmpValue = new TypedValue();
149
150    final Thread mThread;
151
152    final WindowLeaked mLocation;
153
154    final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
155
156    final W mWindow;
157
158    final int mTargetSdkVersion;
159
160    int mSeq;
161
162    View mView;
163
164    View mAccessibilityFocusedHost;
165    AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
166
167    int mViewVisibility;
168    boolean mAppVisible = true;
169    int mOrigWindowType = -1;
170
171    // Set to true if the owner of this window is in the stopped state,
172    // so the window should no longer be active.
173    boolean mStopped = false;
174
175    boolean mLastInCompatMode = false;
176
177    SurfaceHolder.Callback2 mSurfaceHolderCallback;
178    BaseSurfaceHolder mSurfaceHolder;
179    boolean mIsCreating;
180    boolean mDrawingAllowed;
181
182    final Region mTransparentRegion;
183    final Region mPreviousTransparentRegion;
184
185    int mWidth;
186    int mHeight;
187    Rect mDirty;
188    final Rect mCurrentDirty = new Rect();
189    boolean mIsAnimating;
190
191    CompatibilityInfo.Translator mTranslator;
192
193    final View.AttachInfo mAttachInfo;
194    InputChannel mInputChannel;
195    InputQueue.Callback mInputQueueCallback;
196    InputQueue mInputQueue;
197    FallbackEventHandler mFallbackEventHandler;
198    Choreographer mChoreographer;
199
200    final Rect mTempRect; // used in the transaction to not thrash the heap.
201    final Rect mVisRect; // used to retrieve visible rect of focused view.
202
203    boolean mTraversalScheduled;
204    int mTraversalBarrier;
205    boolean mWillDrawSoon;
206    /** Set to true while in performTraversals for detecting when die(true) is called from internal
207     * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
208    boolean mIsInTraversal;
209    boolean mFitSystemWindowsRequested;
210    boolean mLayoutRequested;
211    boolean mFirst;
212    boolean mReportNextDraw;
213    boolean mFullRedrawNeeded;
214    boolean mNewSurfaceNeeded;
215    boolean mHasHadWindowFocus;
216    boolean mLastWasImTarget;
217    boolean mWindowsAnimating;
218    boolean mIsDrawing;
219    int mLastSystemUiVisibility;
220    int mClientWindowLayoutFlags;
221    boolean mLastOverscanRequested;
222
223    // Pool of queued input events.
224    private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
225    private QueuedInputEvent mQueuedInputEventPool;
226    private int mQueuedInputEventPoolSize;
227
228    /* Input event queue.
229     * Pending input events are input events waiting to be delivered to the input stages
230     * and handled by the application.
231     */
232    QueuedInputEvent mPendingInputEventHead;
233    QueuedInputEvent mPendingInputEventTail;
234    int mPendingInputEventCount;
235    boolean mProcessInputEventsScheduled;
236    String mPendingInputEventQueueLengthCounterName = "pq";
237
238    InputStage mFirstInputStage;
239    InputStage mFirstPostImeInputStage;
240
241    boolean mWindowAttributesChanged = false;
242    int mWindowAttributesChangesFlag = 0;
243
244    // These can be accessed by any thread, must be protected with a lock.
245    // Surface can never be reassigned or cleared (use Surface.clear()).
246    private final Surface mSurface = new Surface();
247
248    boolean mAdded;
249    boolean mAddedTouchMode;
250
251    final CompatibilityInfoHolder mCompatibilityInfo;
252
253    // These are accessed by multiple threads.
254    final Rect mWinFrame; // frame given by window manager.
255
256    final Rect mPendingOverscanInsets = new Rect();
257    final Rect mPendingVisibleInsets = new Rect();
258    final Rect mPendingContentInsets = new Rect();
259    final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
260            = new ViewTreeObserver.InternalInsetsInfo();
261
262    final Rect mFitSystemWindowsInsets = new Rect();
263
264    final Configuration mLastConfiguration = new Configuration();
265    final Configuration mPendingConfiguration = new Configuration();
266
267    boolean mScrollMayChange;
268    int mSoftInputMode;
269    WeakReference<View> mLastScrolledFocus;
270    int mScrollY;
271    int mCurScrollY;
272    Scroller mScroller;
273    HardwareLayer mResizeBuffer;
274    long mResizeBufferStartTime;
275    int mResizeBufferDuration;
276    static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
277    private ArrayList<LayoutTransition> mPendingTransitions;
278
279    final ViewConfiguration mViewConfiguration;
280
281    /* Drag/drop */
282    ClipDescription mDragDescription;
283    View mCurrentDragView;
284    volatile Object mLocalDragState;
285    final PointF mDragPoint = new PointF();
286    final PointF mLastTouchPoint = new PointF();
287
288    private boolean mProfileRendering;
289    private Choreographer.FrameCallback mRenderProfiler;
290    private boolean mRenderProfilingEnabled;
291
292    // Variables to track frames per second, enabled via DEBUG_FPS flag
293    private long mFpsStartTime = -1;
294    private long mFpsPrevTime = -1;
295    private int mFpsNumFrames;
296
297    private final ArrayList<DisplayList> mDisplayLists = new ArrayList<DisplayList>();
298
299    /**
300     * see {@link #playSoundEffect(int)}
301     */
302    AudioManager mAudioManager;
303
304    final AccessibilityManager mAccessibilityManager;
305
306    AccessibilityInteractionController mAccessibilityInteractionController;
307
308    AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
309
310    SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
311
312    HashSet<View> mTempHashSet;
313
314    private final int mDensity;
315    private final int mNoncompatDensity;
316
317    private boolean mInLayout = false;
318    ArrayList<View> mLayoutRequesters = new ArrayList<View>();
319    boolean mHandlingLayoutInLayoutRequest = false;
320
321    private int mViewLayoutDirectionInitial;
322
323    /**
324     * Consistency verifier for debugging purposes.
325     */
326    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
327            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
328                    new InputEventConsistencyVerifier(this, 0) : null;
329
330    static final class SystemUiVisibilityInfo {
331        int seq;
332        int globalVisibility;
333        int localValue;
334        int localChanges;
335    }
336
337    public ViewRootImpl(Context context, Display display) {
338        mContext = context;
339        mWindowSession = WindowManagerGlobal.getWindowSession();
340        mDisplay = display;
341        mBasePackageName = context.getBasePackageName();
342
343        CompatibilityInfoHolder cih = display.getCompatibilityInfo();
344        mCompatibilityInfo = cih != null ? cih : new CompatibilityInfoHolder();
345
346        mThread = Thread.currentThread();
347        mLocation = new WindowLeaked(null);
348        mLocation.fillInStackTrace();
349        mWidth = -1;
350        mHeight = -1;
351        mDirty = new Rect();
352        mTempRect = new Rect();
353        mVisRect = new Rect();
354        mWinFrame = new Rect();
355        mWindow = new W(this);
356        mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
357        mViewVisibility = View.GONE;
358        mTransparentRegion = new Region();
359        mPreviousTransparentRegion = new Region();
360        mFirst = true; // true for the first time the view is added
361        mAdded = false;
362        mAccessibilityManager = AccessibilityManager.getInstance(context);
363        mAccessibilityInteractionConnectionManager =
364            new AccessibilityInteractionConnectionManager();
365        mAccessibilityManager.addAccessibilityStateChangeListener(
366                mAccessibilityInteractionConnectionManager);
367        mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
368        mViewConfiguration = ViewConfiguration.get(context);
369        mDensity = context.getResources().getDisplayMetrics().densityDpi;
370        mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
371        mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
372        mChoreographer = Choreographer.getInstance();
373
374        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
375        mAttachInfo.mScreenOn = powerManager.isScreenOn();
376        loadSystemProperties();
377    }
378
379    /**
380     * @return True if the application requests the use of a separate render thread,
381     *         false otherwise
382     */
383    private static boolean isRenderThreadRequested(Context context) {
384        if (USE_RENDER_THREAD) {
385            synchronized (sRenderThreadQueryLock) {
386                if (!sRenderThreadQueried) {
387                    final PackageManager packageManager = context.getPackageManager();
388                    final String packageName = context.getApplicationInfo().packageName;
389                    try {
390                        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName,
391                                PackageManager.GET_META_DATA);
392                        if (applicationInfo.metaData != null) {
393                            sUseRenderThread = applicationInfo.metaData.getBoolean(
394                                    "android.graphics.renderThread", false);
395                        }
396                    } catch (PackageManager.NameNotFoundException e) {
397                    } finally {
398                        sRenderThreadQueried = true;
399                    }
400                }
401                return sUseRenderThread;
402            }
403        } else {
404            return false;
405        }
406    }
407
408    public static void addFirstDrawHandler(Runnable callback) {
409        synchronized (sFirstDrawHandlers) {
410            if (!sFirstDrawComplete) {
411                sFirstDrawHandlers.add(callback);
412            }
413        }
414    }
415
416    public static void addConfigCallback(ComponentCallbacks callback) {
417        synchronized (sConfigCallbacks) {
418            sConfigCallbacks.add(callback);
419        }
420    }
421
422    // FIXME for perf testing only
423    private boolean mProfile = false;
424
425    /**
426     * Call this to profile the next traversal call.
427     * FIXME for perf testing only. Remove eventually
428     */
429    public void profile() {
430        mProfile = true;
431    }
432
433    /**
434     * Indicates whether we are in touch mode. Calling this method triggers an IPC
435     * call and should be avoided whenever possible.
436     *
437     * @return True, if the device is in touch mode, false otherwise.
438     *
439     * @hide
440     */
441    static boolean isInTouchMode() {
442        IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
443        if (windowSession != null) {
444            try {
445                return windowSession.getInTouchMode();
446            } catch (RemoteException e) {
447            }
448        }
449        return false;
450    }
451
452    /**
453     * We have one child
454     */
455    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
456        synchronized (this) {
457            if (mView == null) {
458                mView = view;
459                mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
460                mFallbackEventHandler.setView(view);
461                mWindowAttributes.copyFrom(attrs);
462                if (mWindowAttributes.packageName == null) {
463                    mWindowAttributes.packageName = mBasePackageName;
464                }
465                attrs = mWindowAttributes;
466                // Keep track of the actual window flags supplied by the client.
467                mClientWindowLayoutFlags = attrs.flags;
468
469                setAccessibilityFocus(null, null);
470
471                if (view instanceof RootViewSurfaceTaker) {
472                    mSurfaceHolderCallback =
473                            ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
474                    if (mSurfaceHolderCallback != null) {
475                        mSurfaceHolder = new TakenSurfaceHolder();
476                        mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
477                    }
478                }
479
480                CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
481                mTranslator = compatibilityInfo.getTranslator();
482
483                // If the application owns the surface, don't enable hardware acceleration
484                if (mSurfaceHolder == null) {
485                    enableHardwareAcceleration(mView.getContext(), attrs);
486                }
487
488                boolean restore = false;
489                if (mTranslator != null) {
490                    mSurface.setCompatibilityTranslator(mTranslator);
491                    restore = true;
492                    attrs.backup();
493                    mTranslator.translateWindowLayout(attrs);
494                }
495                if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
496
497                if (!compatibilityInfo.supportsScreen()) {
498                    attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
499                    mLastInCompatMode = true;
500                }
501
502                mSoftInputMode = attrs.softInputMode;
503                mWindowAttributesChanged = true;
504                mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
505                mAttachInfo.mRootView = view;
506                mAttachInfo.mScalingRequired = mTranslator != null;
507                mAttachInfo.mApplicationScale =
508                        mTranslator == null ? 1.0f : mTranslator.applicationScale;
509                if (panelParentView != null) {
510                    mAttachInfo.mPanelParentWindowToken
511                            = panelParentView.getApplicationWindowToken();
512                }
513                mAdded = true;
514                int res; /* = WindowManagerImpl.ADD_OKAY; */
515
516                // Schedule the first layout -before- adding to the window
517                // manager, to make sure we do the relayout before receiving
518                // any other events from the system.
519                requestLayout();
520                if ((mWindowAttributes.inputFeatures
521                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
522                    mInputChannel = new InputChannel();
523                }
524                try {
525                    mOrigWindowType = mWindowAttributes.type;
526                    mAttachInfo.mRecomputeGlobalAttributes = true;
527                    collectViewAttributes();
528                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
529                            getHostVisibility(), mDisplay.getDisplayId(),
530                            mAttachInfo.mContentInsets, mInputChannel);
531                } catch (RemoteException e) {
532                    mAdded = false;
533                    mView = null;
534                    mAttachInfo.mRootView = null;
535                    mInputChannel = null;
536                    mFallbackEventHandler.setView(null);
537                    unscheduleTraversals();
538                    setAccessibilityFocus(null, null);
539                    throw new RuntimeException("Adding window failed", e);
540                } finally {
541                    if (restore) {
542                        attrs.restore();
543                    }
544                }
545
546                if (mTranslator != null) {
547                    mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
548                }
549                mPendingOverscanInsets.set(0, 0, 0, 0);
550                mPendingContentInsets.set(mAttachInfo.mContentInsets);
551                mPendingVisibleInsets.set(0, 0, 0, 0);
552                if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
553                if (res < WindowManagerGlobal.ADD_OKAY) {
554                    mAttachInfo.mRootView = null;
555                    mAdded = false;
556                    mFallbackEventHandler.setView(null);
557                    unscheduleTraversals();
558                    setAccessibilityFocus(null, null);
559                    switch (res) {
560                        case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
561                        case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
562                            throw new WindowManager.BadTokenException(
563                                "Unable to add window -- token " + attrs.token
564                                + " is not valid; is your activity running?");
565                        case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
566                            throw new WindowManager.BadTokenException(
567                                "Unable to add window -- token " + attrs.token
568                                + " is not for an application");
569                        case WindowManagerGlobal.ADD_APP_EXITING:
570                            throw new WindowManager.BadTokenException(
571                                "Unable to add window -- app for token " + attrs.token
572                                + " is exiting");
573                        case WindowManagerGlobal.ADD_DUPLICATE_ADD:
574                            throw new WindowManager.BadTokenException(
575                                "Unable to add window -- window " + mWindow
576                                + " has already been added");
577                        case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
578                            // Silently ignore -- we would have just removed it
579                            // right away, anyway.
580                            return;
581                        case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
582                            throw new WindowManager.BadTokenException(
583                                "Unable to add window " + mWindow +
584                                " -- another window of this type already exists");
585                        case WindowManagerGlobal.ADD_PERMISSION_DENIED:
586                            throw new WindowManager.BadTokenException(
587                                "Unable to add window " + mWindow +
588                                " -- permission denied for this window type");
589                        case WindowManagerGlobal.ADD_INVALID_DISPLAY:
590                            throw new WindowManager.InvalidDisplayException(
591                                "Unable to add window " + mWindow +
592                                " -- the specified display can not be found");
593                    }
594                    throw new RuntimeException(
595                        "Unable to add window -- unknown error code " + res);
596                }
597
598                if (view instanceof RootViewSurfaceTaker) {
599                    mInputQueueCallback =
600                        ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
601                }
602                if (mInputChannel != null) {
603                    if (mInputQueueCallback != null) {
604                        mInputQueue = new InputQueue(mInputChannel);
605                        mInputQueueCallback.onInputQueueCreated(mInputQueue);
606                    } else {
607                        mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
608                                Looper.myLooper());
609                    }
610                }
611
612                view.assignParent(this);
613                mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
614                mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
615
616                if (mAccessibilityManager.isEnabled()) {
617                    mAccessibilityInteractionConnectionManager.ensureConnection();
618                }
619
620                if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
621                    view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
622                }
623
624                // Set up the input pipeline.
625                CharSequence counterSuffix = attrs.getTitle();
626                InputStage syntheticStage = new SyntheticInputStage();
627                InputStage viewPostImeStage = new ViewPostImeInputStage(syntheticStage);
628                InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
629                        "aq:native-post-ime:" + counterSuffix);
630                InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
631                InputStage imeStage = new ImeInputStage(earlyPostImeStage,
632                        "aq:ime:" + counterSuffix);
633                InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
634                InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
635                        "aq:native-pre-ime:" + counterSuffix);
636
637                mFirstInputStage = nativePreImeStage;
638                mFirstPostImeInputStage = earlyPostImeStage;
639                mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
640            }
641        }
642    }
643
644    void destroyHardwareResources() {
645        if (mAttachInfo.mHardwareRenderer != null) {
646            if (mAttachInfo.mHardwareRenderer.isEnabled()) {
647                mAttachInfo.mHardwareRenderer.destroyLayers(mView);
648            }
649            mAttachInfo.mHardwareRenderer.destroy(false);
650        }
651    }
652
653    void terminateHardwareResources() {
654        if (mAttachInfo.mHardwareRenderer != null) {
655            mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
656            mAttachInfo.mHardwareRenderer.destroy(false);
657        }
658    }
659
660    void destroyHardwareLayers() {
661        if (mThread != Thread.currentThread()) {
662            if (mAttachInfo.mHardwareRenderer != null &&
663                    mAttachInfo.mHardwareRenderer.isEnabled()) {
664                HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE);
665            }
666        } else {
667            if (mAttachInfo.mHardwareRenderer != null &&
668                    mAttachInfo.mHardwareRenderer.isEnabled()) {
669                mAttachInfo.mHardwareRenderer.destroyLayers(mView);
670            }
671        }
672    }
673
674    void pushHardwareLayerUpdate(HardwareLayer layer) {
675        if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
676            mAttachInfo.mHardwareRenderer.pushLayerUpdate(layer);
677        }
678    }
679
680    public boolean attachFunctor(int functor) {
681        //noinspection SimplifiableIfStatement
682        if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
683            return mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor);
684        }
685        return false;
686    }
687
688    public void detachFunctor(int functor) {
689        if (mAttachInfo.mHardwareRenderer != null) {
690            mAttachInfo.mHardwareRenderer.detachFunctor(functor);
691        }
692    }
693
694    private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) {
695        mAttachInfo.mHardwareAccelerated = false;
696        mAttachInfo.mHardwareAccelerationRequested = false;
697
698        // Don't enable hardware acceleration when the application is in compatibility mode
699        if (mTranslator != null) return;
700
701        // Try to enable hardware acceleration if requested
702        final boolean hardwareAccelerated =
703                (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
704
705        if (hardwareAccelerated) {
706            if (!HardwareRenderer.isAvailable()) {
707                return;
708            }
709
710            // Persistent processes (including the system) should not do
711            // accelerated rendering on low-end devices.  In that case,
712            // sRendererDisabled will be set.  In addition, the system process
713            // itself should never do accelerated rendering.  In that case, both
714            // sRendererDisabled and sSystemRendererDisabled are set.  When
715            // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
716            // can be used by code on the system process to escape that and enable
717            // HW accelerated drawing.  (This is basically for the lock screen.)
718
719            final boolean fakeHwAccelerated = (attrs.privateFlags &
720                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
721            final boolean forceHwAccelerated = (attrs.privateFlags &
722                    WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
723
724            if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled
725                    && forceHwAccelerated)) {
726                // Don't enable hardware acceleration when we're not on the main thread
727                if (!HardwareRenderer.sSystemRendererDisabled &&
728                        Looper.getMainLooper() != Looper.myLooper()) {
729                    Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
730                            + "acceleration outside of the main thread, aborting");
731                    return;
732                }
733
734                final boolean renderThread = isRenderThreadRequested(context);
735                if (renderThread) {
736                    Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated");
737                }
738
739                if (mAttachInfo.mHardwareRenderer != null) {
740                    mAttachInfo.mHardwareRenderer.destroy(true);
741                }
742
743                final boolean translucent = attrs.format != PixelFormat.OPAQUE;
744                mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
745                if (mAttachInfo.mHardwareRenderer != null) {
746                    mAttachInfo.mHardwareRenderer.setName(attrs.getTitle().toString());
747                    mAttachInfo.mHardwareAccelerated =
748                            mAttachInfo.mHardwareAccelerationRequested = true;
749                }
750            } else if (fakeHwAccelerated) {
751                // The window had wanted to use hardware acceleration, but this
752                // is not allowed in its process.  By setting this flag, it can
753                // still render as if it was accelerated.  This is basically for
754                // the preview windows the window manager shows for launching
755                // applications, so they will look more like the app being launched.
756                mAttachInfo.mHardwareAccelerationRequested = true;
757            }
758        }
759    }
760
761    public View getView() {
762        return mView;
763    }
764
765    final WindowLeaked getLocation() {
766        return mLocation;
767    }
768
769    void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
770        synchronized (this) {
771            int oldSoftInputMode = mWindowAttributes.softInputMode;
772            // Keep track of the actual window flags supplied by the client.
773            mClientWindowLayoutFlags = attrs.flags;
774            // preserve compatible window flag if exists.
775            int compatibleWindowFlag =
776                mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
777            // transfer over system UI visibility values as they carry current state.
778            attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
779            attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
780            mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
781            if (mWindowAttributes.packageName == null) {
782                mWindowAttributes.packageName = mBasePackageName;
783            }
784            mWindowAttributes.flags |= compatibleWindowFlag;
785
786            applyKeepScreenOnFlag(mWindowAttributes);
787
788            if (newView) {
789                mSoftInputMode = attrs.softInputMode;
790                requestLayout();
791            }
792            // Don't lose the mode we last auto-computed.
793            if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
794                    == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
795                mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
796                        & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
797                        | (oldSoftInputMode
798                                & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
799            }
800            mWindowAttributesChanged = true;
801            scheduleTraversals();
802        }
803    }
804
805    void handleAppVisibility(boolean visible) {
806        if (mAppVisible != visible) {
807            mAppVisible = visible;
808            scheduleTraversals();
809        }
810    }
811
812    void handleGetNewSurface() {
813        mNewSurfaceNeeded = true;
814        mFullRedrawNeeded = true;
815        scheduleTraversals();
816    }
817
818    void handleScreenStateChange(boolean on) {
819        if (on != mAttachInfo.mScreenOn) {
820            mAttachInfo.mScreenOn = on;
821            if (mView != null) {
822                mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF);
823            }
824            if (on) {
825                mFullRedrawNeeded = true;
826                scheduleTraversals();
827            }
828        }
829    }
830
831    @Override
832    public void requestFitSystemWindows() {
833        checkThread();
834        mFitSystemWindowsRequested = true;
835        scheduleTraversals();
836    }
837
838    @Override
839    public void requestLayout() {
840        if (!mHandlingLayoutInLayoutRequest) {
841            checkThread();
842            mLayoutRequested = true;
843            scheduleTraversals();
844        }
845    }
846
847    @Override
848    public boolean isLayoutRequested() {
849        return mLayoutRequested;
850    }
851
852    void invalidate() {
853        mDirty.set(0, 0, mWidth, mHeight);
854        scheduleTraversals();
855    }
856
857    void invalidateWorld(View view) {
858        view.invalidate();
859        if (view instanceof ViewGroup) {
860            ViewGroup parent = (ViewGroup) view;
861            for (int i = 0; i < parent.getChildCount(); i++) {
862                invalidateWorld(parent.getChildAt(i));
863            }
864        }
865    }
866
867    @Override
868    public void invalidateChild(View child, Rect dirty) {
869        invalidateChildInParent(null, dirty);
870    }
871
872    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
873        checkThread();
874        if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
875
876        if (dirty == null) {
877            invalidate();
878            return null;
879        } else if (dirty.isEmpty() && !mIsAnimating) {
880            return null;
881        }
882
883        if (mCurScrollY != 0 || mTranslator != null) {
884            mTempRect.set(dirty);
885            dirty = mTempRect;
886            if (mCurScrollY != 0) {
887                dirty.offset(0, -mCurScrollY);
888            }
889            if (mTranslator != null) {
890                mTranslator.translateRectInAppWindowToScreen(dirty);
891            }
892            if (mAttachInfo.mScalingRequired) {
893                dirty.inset(-1, -1);
894            }
895        }
896
897        final Rect localDirty = mDirty;
898        if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
899            mAttachInfo.mSetIgnoreDirtyState = true;
900            mAttachInfo.mIgnoreDirtyState = true;
901        }
902
903        // Add the new dirty rect to the current one
904        localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
905        // Intersect with the bounds of the window to skip
906        // updates that lie outside of the visible region
907        final float appScale = mAttachInfo.mApplicationScale;
908        final boolean intersected = localDirty.intersect(0, 0,
909                (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
910        if (!intersected) {
911            localDirty.setEmpty();
912        }
913        if (!mWillDrawSoon && (intersected || mIsAnimating)) {
914            scheduleTraversals();
915        }
916
917        return null;
918    }
919
920    void setStopped(boolean stopped) {
921        if (mStopped != stopped) {
922            mStopped = stopped;
923            if (!stopped) {
924                scheduleTraversals();
925            }
926        }
927    }
928
929    public ViewParent getParent() {
930        return null;
931    }
932
933    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
934        if (child != mView) {
935            throw new RuntimeException("child is not mine, honest!");
936        }
937        // Note: don't apply scroll offset, because we want to know its
938        // visibility in the virtual canvas being given to the view hierarchy.
939        return r.intersect(0, 0, mWidth, mHeight);
940    }
941
942    public void bringChildToFront(View child) {
943    }
944
945    int getHostVisibility() {
946        return mAppVisible ? mView.getVisibility() : View.GONE;
947    }
948
949    void disposeResizeBuffer() {
950        if (mResizeBuffer != null) {
951            mResizeBuffer.destroy();
952            mResizeBuffer = null;
953        }
954    }
955
956    /**
957     * Add LayoutTransition to the list of transitions to be started in the next traversal.
958     * This list will be cleared after the transitions on the list are start()'ed. These
959     * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
960     * happens during the layout phase of traversal, which we want to complete before any of the
961     * animations are started (because those animations may side-effect properties that layout
962     * depends upon, like the bounding rectangles of the affected views). So we add the transition
963     * to the list and it is started just prior to starting the drawing phase of traversal.
964     *
965     * @param transition The LayoutTransition to be started on the next traversal.
966     *
967     * @hide
968     */
969    public void requestTransitionStart(LayoutTransition transition) {
970        if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
971            if (mPendingTransitions == null) {
972                 mPendingTransitions = new ArrayList<LayoutTransition>();
973            }
974            mPendingTransitions.add(transition);
975        }
976    }
977
978    void scheduleTraversals() {
979        if (!mTraversalScheduled) {
980            mTraversalScheduled = true;
981            mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
982            mChoreographer.postCallback(
983                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
984            scheduleConsumeBatchedInput();
985        }
986    }
987
988    void unscheduleTraversals() {
989        if (mTraversalScheduled) {
990            mTraversalScheduled = false;
991            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
992            mChoreographer.removeCallbacks(
993                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
994        }
995    }
996
997    void doTraversal() {
998        if (mTraversalScheduled) {
999            mTraversalScheduled = false;
1000            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
1001
1002            if (mProfile) {
1003                Debug.startMethodTracing("ViewAncestor");
1004            }
1005
1006            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
1007            try {
1008                performTraversals();
1009            } finally {
1010                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1011            }
1012
1013            if (mProfile) {
1014                Debug.stopMethodTracing();
1015                mProfile = false;
1016            }
1017        }
1018    }
1019
1020    private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1021        // Update window's global keep screen on flag: if a view has requested
1022        // that the screen be kept on, then it is always set; otherwise, it is
1023        // set to whatever the client last requested for the global state.
1024        if (mAttachInfo.mKeepScreenOn) {
1025            params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1026        } else {
1027            params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1028                    | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1029        }
1030    }
1031
1032    private boolean collectViewAttributes() {
1033        final View.AttachInfo attachInfo = mAttachInfo;
1034        if (attachInfo.mRecomputeGlobalAttributes) {
1035            //Log.i(TAG, "Computing view hierarchy attributes!");
1036            attachInfo.mRecomputeGlobalAttributes = false;
1037            boolean oldScreenOn = attachInfo.mKeepScreenOn;
1038            attachInfo.mKeepScreenOn = false;
1039            attachInfo.mSystemUiVisibility = 0;
1040            attachInfo.mHasSystemUiListeners = false;
1041            mView.dispatchCollectViewAttributes(attachInfo, 0);
1042            attachInfo.mSystemUiVisibility &= ~attachInfo.mDisabledSystemUiVisibility;
1043            WindowManager.LayoutParams params = mWindowAttributes;
1044            if (attachInfo.mKeepScreenOn != oldScreenOn
1045                    || attachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1046                    || attachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
1047                applyKeepScreenOnFlag(params);
1048                params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
1049                params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners;
1050                mView.dispatchWindowSystemUiVisiblityChanged(attachInfo.mSystemUiVisibility);
1051                return true;
1052            }
1053        }
1054        return false;
1055    }
1056
1057    private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1058            final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1059        int childWidthMeasureSpec;
1060        int childHeightMeasureSpec;
1061        boolean windowSizeMayChange = false;
1062
1063        if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
1064                "Measuring " + host + " in display " + desiredWindowWidth
1065                + "x" + desiredWindowHeight + "...");
1066
1067        boolean goodMeasure = false;
1068        if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1069            // On large screens, we don't want to allow dialogs to just
1070            // stretch to fill the entire width of the screen to display
1071            // one line of text.  First try doing the layout at a smaller
1072            // size to see if it will fit.
1073            final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1074            res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1075            int baseSize = 0;
1076            if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1077                baseSize = (int)mTmpValue.getDimension(packageMetrics);
1078            }
1079            if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
1080            if (baseSize != 0 && desiredWindowWidth > baseSize) {
1081                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1082                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1083                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1084                if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1085                        + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1086                if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1087                    goodMeasure = true;
1088                } else {
1089                    // Didn't fit in that size... try expanding a bit.
1090                    baseSize = (baseSize+desiredWindowWidth)/2;
1091                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
1092                            + baseSize);
1093                    childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1094                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1095                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1096                            + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1097                    if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1098                        if (DEBUG_DIALOG) Log.v(TAG, "Good!");
1099                        goodMeasure = true;
1100                    }
1101                }
1102            }
1103        }
1104
1105        if (!goodMeasure) {
1106            childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1107            childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1108            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1109            if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1110                windowSizeMayChange = true;
1111            }
1112        }
1113
1114        if (DBG) {
1115            System.out.println("======================================");
1116            System.out.println("performTraversals -- after measure");
1117            host.debug();
1118        }
1119
1120        return windowSizeMayChange;
1121    }
1122
1123    private void performTraversals() {
1124        // cache mView since it is used so much below...
1125        final View host = mView;
1126
1127        if (DBG) {
1128            System.out.println("======================================");
1129            System.out.println("performTraversals");
1130            host.debug();
1131        }
1132
1133        if (host == null || !mAdded)
1134            return;
1135
1136        mIsInTraversal = true;
1137        mWillDrawSoon = true;
1138        boolean windowSizeMayChange = false;
1139        boolean newSurface = false;
1140        boolean surfaceChanged = false;
1141        WindowManager.LayoutParams lp = mWindowAttributes;
1142
1143        int desiredWindowWidth;
1144        int desiredWindowHeight;
1145
1146        final View.AttachInfo attachInfo = mAttachInfo;
1147
1148        final int viewVisibility = getHostVisibility();
1149        boolean viewVisibilityChanged = mViewVisibility != viewVisibility
1150                || mNewSurfaceNeeded;
1151
1152        WindowManager.LayoutParams params = null;
1153        if (mWindowAttributesChanged) {
1154            mWindowAttributesChanged = false;
1155            surfaceChanged = true;
1156            params = lp;
1157        }
1158        CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
1159        if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1160            params = lp;
1161            mFullRedrawNeeded = true;
1162            mLayoutRequested = true;
1163            if (mLastInCompatMode) {
1164                params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
1165                mLastInCompatMode = false;
1166            } else {
1167                params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
1168                mLastInCompatMode = true;
1169            }
1170        }
1171
1172        mWindowAttributesChangesFlag = 0;
1173
1174        Rect frame = mWinFrame;
1175        if (mFirst) {
1176            mFullRedrawNeeded = true;
1177            mLayoutRequested = true;
1178
1179            if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
1180                // NOTE -- system code, won't try to do compat mode.
1181                Point size = new Point();
1182                mDisplay.getRealSize(size);
1183                desiredWindowWidth = size.x;
1184                desiredWindowHeight = size.y;
1185            } else {
1186                DisplayMetrics packageMetrics =
1187                    mView.getContext().getResources().getDisplayMetrics();
1188                desiredWindowWidth = packageMetrics.widthPixels;
1189                desiredWindowHeight = packageMetrics.heightPixels;
1190            }
1191
1192            // For the very first time, tell the view hierarchy that it
1193            // is attached to the window.  Note that at this point the surface
1194            // object is not initialized to its backing store, but soon it
1195            // will be (assuming the window is visible).
1196            attachInfo.mSurface = mSurface;
1197            // We used to use the following condition to choose 32 bits drawing caches:
1198            // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1199            // However, windows are now always 32 bits by default, so choose 32 bits
1200            attachInfo.mUse32BitDrawingCache = true;
1201            attachInfo.mHasWindowFocus = false;
1202            attachInfo.mWindowVisibility = viewVisibility;
1203            attachInfo.mRecomputeGlobalAttributes = false;
1204            viewVisibilityChanged = false;
1205            mLastConfiguration.setTo(host.getResources().getConfiguration());
1206            mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1207            // Set the layout direction if it has not been set before (inherit is the default)
1208            if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1209                host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1210            }
1211            host.dispatchAttachedToWindow(attachInfo, 0);
1212            attachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
1213            mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1214            host.fitSystemWindows(mFitSystemWindowsInsets);
1215            //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
1216
1217        } else {
1218            desiredWindowWidth = frame.width();
1219            desiredWindowHeight = frame.height();
1220            if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
1221                if (DEBUG_ORIENTATION) Log.v(TAG,
1222                        "View " + host + " resized to: " + frame);
1223                mFullRedrawNeeded = true;
1224                mLayoutRequested = true;
1225                windowSizeMayChange = true;
1226            }
1227        }
1228
1229        if (viewVisibilityChanged) {
1230            attachInfo.mWindowVisibility = viewVisibility;
1231            host.dispatchWindowVisibilityChanged(viewVisibility);
1232            if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1233                destroyHardwareResources();
1234            }
1235            if (viewVisibility == View.GONE) {
1236                // After making a window gone, we will count it as being
1237                // shown for the first time the next time it gets focus.
1238                mHasHadWindowFocus = false;
1239            }
1240        }
1241
1242        // Execute enqueued actions on every traversal in case a detached view enqueued an action
1243        getRunQueue().executeActions(attachInfo.mHandler);
1244
1245        boolean insetsChanged = false;
1246
1247        boolean layoutRequested = mLayoutRequested && !mStopped;
1248        if (layoutRequested) {
1249
1250            final Resources res = mView.getContext().getResources();
1251
1252            if (mFirst) {
1253                // make sure touch mode code executes by setting cached value
1254                // to opposite of the added touch mode.
1255                mAttachInfo.mInTouchMode = !mAddedTouchMode;
1256                ensureTouchModeLocally(mAddedTouchMode);
1257            } else {
1258                if (!mPendingOverscanInsets.equals(mAttachInfo.mOverscanInsets)) {
1259                    insetsChanged = true;
1260                }
1261                if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
1262                    insetsChanged = true;
1263                }
1264                if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
1265                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1266                    if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1267                            + mAttachInfo.mVisibleInsets);
1268                }
1269                if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1270                        || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
1271                    windowSizeMayChange = true;
1272
1273                    if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
1274                        // NOTE -- system code, won't try to do compat mode.
1275                        Point size = new Point();
1276                        mDisplay.getRealSize(size);
1277                        desiredWindowWidth = size.x;
1278                        desiredWindowHeight = size.y;
1279                    } else {
1280                        DisplayMetrics packageMetrics = res.getDisplayMetrics();
1281                        desiredWindowWidth = packageMetrics.widthPixels;
1282                        desiredWindowHeight = packageMetrics.heightPixels;
1283                    }
1284                }
1285            }
1286
1287            // Ask host how big it wants to be
1288            windowSizeMayChange |= measureHierarchy(host, lp, res,
1289                    desiredWindowWidth, desiredWindowHeight);
1290        }
1291
1292        if (collectViewAttributes()) {
1293            params = lp;
1294        }
1295        if (attachInfo.mForceReportNewAttributes) {
1296            attachInfo.mForceReportNewAttributes = false;
1297            params = lp;
1298        }
1299
1300        if (mFirst || attachInfo.mViewVisibilityChanged) {
1301            attachInfo.mViewVisibilityChanged = false;
1302            int resizeMode = mSoftInputMode &
1303                    WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1304            // If we are in auto resize mode, then we need to determine
1305            // what mode to use now.
1306            if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1307                final int N = attachInfo.mScrollContainers.size();
1308                for (int i=0; i<N; i++) {
1309                    if (attachInfo.mScrollContainers.get(i).isShown()) {
1310                        resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1311                    }
1312                }
1313                if (resizeMode == 0) {
1314                    resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1315                }
1316                if ((lp.softInputMode &
1317                        WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1318                    lp.softInputMode = (lp.softInputMode &
1319                            ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1320                            resizeMode;
1321                    params = lp;
1322                }
1323            }
1324        }
1325
1326        if (params != null) {
1327            if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1328                if (!PixelFormat.formatHasAlpha(params.format)) {
1329                    params.format = PixelFormat.TRANSLUCENT;
1330                }
1331            }
1332            mAttachInfo.mOverscanRequested = (params.flags
1333                    & WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN) != 0;
1334        }
1335
1336        if (mFitSystemWindowsRequested) {
1337            mFitSystemWindowsRequested = false;
1338            mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1339            mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1340            host.fitSystemWindows(mFitSystemWindowsInsets);
1341            if (mLayoutRequested) {
1342                // Short-circuit catching a new layout request here, so
1343                // we don't need to go through two layout passes when things
1344                // change due to fitting system windows, which can happen a lot.
1345                windowSizeMayChange |= measureHierarchy(host, lp,
1346                        mView.getContext().getResources(),
1347                        desiredWindowWidth, desiredWindowHeight);
1348            }
1349        }
1350
1351        if (layoutRequested) {
1352            // Clear this now, so that if anything requests a layout in the
1353            // rest of this function we will catch it and re-run a full
1354            // layout pass.
1355            mLayoutRequested = false;
1356        }
1357
1358        boolean windowShouldResize = layoutRequested && windowSizeMayChange
1359            && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
1360                || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1361                        frame.width() < desiredWindowWidth && frame.width() != mWidth)
1362                || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1363                        frame.height() < desiredWindowHeight && frame.height() != mHeight));
1364
1365        final boolean computesInternalInsets =
1366                attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
1367
1368        boolean insetsPending = false;
1369        int relayoutResult = 0;
1370
1371        if (mFirst || windowShouldResize || insetsChanged ||
1372                viewVisibilityChanged || params != null) {
1373
1374            if (viewVisibility == View.VISIBLE) {
1375                // If this window is giving internal insets to the window
1376                // manager, and it is being added or changing its visibility,
1377                // then we want to first give the window manager "fake"
1378                // insets to cause it to effectively ignore the content of
1379                // the window during layout.  This avoids it briefly causing
1380                // other windows to resize/move based on the raw frame of the
1381                // window, waiting until we can finish laying out this window
1382                // and get back to the window manager with the ultimately
1383                // computed insets.
1384                insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1385            }
1386
1387            if (mSurfaceHolder != null) {
1388                mSurfaceHolder.mSurfaceLock.lock();
1389                mDrawingAllowed = true;
1390            }
1391
1392            boolean hwInitialized = false;
1393            boolean contentInsetsChanged = false;
1394            boolean hadSurface = mSurface.isValid();
1395
1396            try {
1397                if (DEBUG_LAYOUT) {
1398                    Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1399                            host.getMeasuredHeight() + ", params=" + params);
1400                }
1401
1402                final int surfaceGenerationId = mSurface.getGenerationId();
1403                relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1404                mWindowsAnimating |=
1405                        (relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0;
1406
1407                if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1408                        + " overscan=" + mPendingOverscanInsets.toShortString()
1409                        + " content=" + mPendingContentInsets.toShortString()
1410                        + " visible=" + mPendingVisibleInsets.toShortString()
1411                        + " surface=" + mSurface);
1412
1413                if (mPendingConfiguration.seq != 0) {
1414                    if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1415                            + mPendingConfiguration);
1416                    updateConfiguration(mPendingConfiguration, !mFirst);
1417                    mPendingConfiguration.seq = 0;
1418                }
1419
1420                final boolean overscanInsetsChanged = !mPendingOverscanInsets.equals(
1421                        mAttachInfo.mOverscanInsets);
1422                contentInsetsChanged = !mPendingContentInsets.equals(
1423                        mAttachInfo.mContentInsets);
1424                final boolean visibleInsetsChanged = !mPendingVisibleInsets.equals(
1425                        mAttachInfo.mVisibleInsets);
1426                if (contentInsetsChanged) {
1427                    if (mWidth > 0 && mHeight > 0 && lp != null &&
1428                            ((lp.systemUiVisibility|lp.subtreeSystemUiVisibility)
1429                                    & View.SYSTEM_UI_LAYOUT_FLAGS) == 0 &&
1430                            mSurface != null && mSurface.isValid() &&
1431                            !mAttachInfo.mTurnOffWindowResizeAnim &&
1432                            mAttachInfo.mHardwareRenderer != null &&
1433                            mAttachInfo.mHardwareRenderer.isEnabled() &&
1434                            mAttachInfo.mHardwareRenderer.validate() &&
1435                            lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
1436
1437                        disposeResizeBuffer();
1438
1439                        boolean completed = false;
1440                        HardwareCanvas hwRendererCanvas = mAttachInfo.mHardwareRenderer.getCanvas();
1441                        HardwareCanvas layerCanvas = null;
1442                        try {
1443                            if (mResizeBuffer == null) {
1444                                mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
1445                                        mWidth, mHeight, false);
1446                            } else if (mResizeBuffer.getWidth() != mWidth ||
1447                                    mResizeBuffer.getHeight() != mHeight) {
1448                                mResizeBuffer.resize(mWidth, mHeight);
1449                            }
1450                            // TODO: should handle create/resize failure
1451                            layerCanvas = mResizeBuffer.start(hwRendererCanvas);
1452                            final int restoreCount = layerCanvas.save();
1453
1454                            int yoff;
1455                            final boolean scrolling = mScroller != null
1456                                    && mScroller.computeScrollOffset();
1457                            if (scrolling) {
1458                                yoff = mScroller.getCurrY();
1459                                mScroller.abortAnimation();
1460                            } else {
1461                                yoff = mScrollY;
1462                            }
1463
1464                            layerCanvas.translate(0, -yoff);
1465                            if (mTranslator != null) {
1466                                mTranslator.translateCanvas(layerCanvas);
1467                            }
1468
1469                            DisplayList displayList = mView.mDisplayList;
1470                            if (displayList != null) {
1471                                layerCanvas.drawDisplayList(displayList, null,
1472                                        DisplayList.FLAG_CLIP_CHILDREN);
1473                            } else {
1474                                mView.draw(layerCanvas);
1475                            }
1476
1477                            drawAccessibilityFocusedDrawableIfNeeded(layerCanvas);
1478
1479                            mResizeBufferStartTime = SystemClock.uptimeMillis();
1480                            mResizeBufferDuration = mView.getResources().getInteger(
1481                                    com.android.internal.R.integer.config_mediumAnimTime);
1482                            completed = true;
1483
1484                            layerCanvas.restoreToCount(restoreCount);
1485                        } catch (OutOfMemoryError e) {
1486                            Log.w(TAG, "Not enough memory for content change anim buffer", e);
1487                        } finally {
1488                            if (mResizeBuffer != null) {
1489                                mResizeBuffer.end(hwRendererCanvas);
1490                                if (!completed) {
1491                                    mResizeBuffer.destroy();
1492                                    mResizeBuffer = null;
1493                                }
1494                            }
1495                        }
1496                    }
1497                    mAttachInfo.mContentInsets.set(mPendingContentInsets);
1498                    if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1499                            + mAttachInfo.mContentInsets);
1500                }
1501                if (overscanInsetsChanged) {
1502                    mAttachInfo.mOverscanInsets.set(mPendingOverscanInsets);
1503                    if (DEBUG_LAYOUT) Log.v(TAG, "Overscan insets changing to: "
1504                            + mAttachInfo.mOverscanInsets);
1505                    // Need to relayout with content insets.
1506                    contentInsetsChanged = true;
1507                }
1508                if (contentInsetsChanged || mLastSystemUiVisibility !=
1509                        mAttachInfo.mSystemUiVisibility || mFitSystemWindowsRequested
1510                        || mLastOverscanRequested != mAttachInfo.mOverscanRequested) {
1511                    mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1512                    mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1513                    mFitSystemWindowsRequested = false;
1514                    mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1515                    host.fitSystemWindows(mFitSystemWindowsInsets);
1516                }
1517                if (visibleInsetsChanged) {
1518                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1519                    if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1520                            + mAttachInfo.mVisibleInsets);
1521                }
1522
1523                if (!hadSurface) {
1524                    if (mSurface.isValid()) {
1525                        // If we are creating a new surface, then we need to
1526                        // completely redraw it.  Also, when we get to the
1527                        // point of drawing it we will hold off and schedule
1528                        // a new traversal instead.  This is so we can tell the
1529                        // window manager about all of the windows being displayed
1530                        // before actually drawing them, so it can display then
1531                        // all at once.
1532                        newSurface = true;
1533                        mFullRedrawNeeded = true;
1534                        mPreviousTransparentRegion.setEmpty();
1535
1536                        if (mAttachInfo.mHardwareRenderer != null) {
1537                            try {
1538                                hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
1539                                        mHolder.getSurface());
1540                            } catch (Surface.OutOfResourcesException e) {
1541                                handleOutOfResourcesException(e);
1542                                return;
1543                            }
1544                        }
1545                    }
1546                } else if (!mSurface.isValid()) {
1547                    // If the surface has been removed, then reset the scroll
1548                    // positions.
1549                    if (mLastScrolledFocus != null) {
1550                        mLastScrolledFocus.clear();
1551                    }
1552                    mScrollY = mCurScrollY = 0;
1553                    if (mScroller != null) {
1554                        mScroller.abortAnimation();
1555                    }
1556                    disposeResizeBuffer();
1557                    // Our surface is gone
1558                    if (mAttachInfo.mHardwareRenderer != null &&
1559                            mAttachInfo.mHardwareRenderer.isEnabled()) {
1560                        mAttachInfo.mHardwareRenderer.destroy(true);
1561                    }
1562                } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1563                        mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1564                    mFullRedrawNeeded = true;
1565                    try {
1566                        mAttachInfo.mHardwareRenderer.updateSurface(mHolder.getSurface());
1567                    } catch (Surface.OutOfResourcesException e) {
1568                        handleOutOfResourcesException(e);
1569                        return;
1570                    }
1571                }
1572            } catch (RemoteException e) {
1573            }
1574
1575            if (DEBUG_ORIENTATION) Log.v(
1576                    TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1577
1578            attachInfo.mWindowLeft = frame.left;
1579            attachInfo.mWindowTop = frame.top;
1580
1581            // !!FIXME!! This next section handles the case where we did not get the
1582            // window size we asked for. We should avoid this by getting a maximum size from
1583            // the window session beforehand.
1584            if (mWidth != frame.width() || mHeight != frame.height()) {
1585                mWidth = frame.width();
1586                mHeight = frame.height();
1587            }
1588
1589            if (mSurfaceHolder != null) {
1590                // The app owns the surface; tell it about what is going on.
1591                if (mSurface.isValid()) {
1592                    // XXX .copyFrom() doesn't work!
1593                    //mSurfaceHolder.mSurface.copyFrom(mSurface);
1594                    mSurfaceHolder.mSurface = mSurface;
1595                }
1596                mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1597                mSurfaceHolder.mSurfaceLock.unlock();
1598                if (mSurface.isValid()) {
1599                    if (!hadSurface) {
1600                        mSurfaceHolder.ungetCallbacks();
1601
1602                        mIsCreating = true;
1603                        mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1604                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1605                        if (callbacks != null) {
1606                            for (SurfaceHolder.Callback c : callbacks) {
1607                                c.surfaceCreated(mSurfaceHolder);
1608                            }
1609                        }
1610                        surfaceChanged = true;
1611                    }
1612                    if (surfaceChanged) {
1613                        mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1614                                lp.format, mWidth, mHeight);
1615                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1616                        if (callbacks != null) {
1617                            for (SurfaceHolder.Callback c : callbacks) {
1618                                c.surfaceChanged(mSurfaceHolder, lp.format,
1619                                        mWidth, mHeight);
1620                            }
1621                        }
1622                    }
1623                    mIsCreating = false;
1624                } else if (hadSurface) {
1625                    mSurfaceHolder.ungetCallbacks();
1626                    SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1627                    mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1628                    if (callbacks != null) {
1629                        for (SurfaceHolder.Callback c : callbacks) {
1630                            c.surfaceDestroyed(mSurfaceHolder);
1631                        }
1632                    }
1633                    mSurfaceHolder.mSurfaceLock.lock();
1634                    try {
1635                        mSurfaceHolder.mSurface = new Surface();
1636                    } finally {
1637                        mSurfaceHolder.mSurfaceLock.unlock();
1638                    }
1639                }
1640            }
1641
1642            if (mAttachInfo.mHardwareRenderer != null &&
1643                    mAttachInfo.mHardwareRenderer.isEnabled()) {
1644                if (hwInitialized || windowShouldResize ||
1645                        mWidth != mAttachInfo.mHardwareRenderer.getWidth() ||
1646                        mHeight != mAttachInfo.mHardwareRenderer.getHeight()) {
1647                    mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
1648                    if (!hwInitialized) {
1649                        mAttachInfo.mHardwareRenderer.invalidate(mHolder.getSurface());
1650                        mFullRedrawNeeded = true;
1651                    }
1652                }
1653            }
1654
1655            if (!mStopped) {
1656                boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1657                        (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
1658                if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1659                        || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1660                    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1661                    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1662
1663                    if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed!  mWidth="
1664                            + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1665                            + " mHeight=" + mHeight
1666                            + " measuredHeight=" + host.getMeasuredHeight()
1667                            + " coveredInsetsChanged=" + contentInsetsChanged);
1668
1669                     // Ask host how big it wants to be
1670                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1671
1672                    // Implementation of weights from WindowManager.LayoutParams
1673                    // We just grow the dimensions as needed and re-measure if
1674                    // needs be
1675                    int width = host.getMeasuredWidth();
1676                    int height = host.getMeasuredHeight();
1677                    boolean measureAgain = false;
1678
1679                    if (lp.horizontalWeight > 0.0f) {
1680                        width += (int) ((mWidth - width) * lp.horizontalWeight);
1681                        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1682                                MeasureSpec.EXACTLY);
1683                        measureAgain = true;
1684                    }
1685                    if (lp.verticalWeight > 0.0f) {
1686                        height += (int) ((mHeight - height) * lp.verticalWeight);
1687                        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1688                                MeasureSpec.EXACTLY);
1689                        measureAgain = true;
1690                    }
1691
1692                    if (measureAgain) {
1693                        if (DEBUG_LAYOUT) Log.v(TAG,
1694                                "And hey let's measure once more: width=" + width
1695                                + " height=" + height);
1696                        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1697                    }
1698
1699                    layoutRequested = true;
1700                }
1701            }
1702        } else {
1703            // Not the first pass and no window/insets/visibility change but the window
1704            // may have moved and we need check that and if so to update the left and right
1705            // in the attach info. We translate only the window frame since on window move
1706            // the window manager tells us only for the new frame but the insets are the
1707            // same and we do not want to translate them more than once.
1708
1709            // TODO: Well, we are checking whether the frame has changed similarly
1710            // to how this is done for the insets. This is however incorrect since
1711            // the insets and the frame are translated. For example, the old frame
1712            // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
1713            // reported frame is (2, 2 - 2, 2) which implies no change but this is not
1714            // true since we are comparing a not translated value to a translated one.
1715            // This scenario is rare but we may want to fix that.
1716
1717            final boolean windowMoved = (attachInfo.mWindowLeft != frame.left
1718                    || attachInfo.mWindowTop != frame.top);
1719            if (windowMoved) {
1720                if (mTranslator != null) {
1721                    mTranslator.translateRectInScreenToAppWinFrame(frame);
1722                }
1723                attachInfo.mWindowLeft = frame.left;
1724                attachInfo.mWindowTop = frame.top;
1725            }
1726        }
1727
1728        final boolean didLayout = layoutRequested && !mStopped;
1729        boolean triggerGlobalLayoutListener = didLayout
1730                || attachInfo.mRecomputeGlobalAttributes;
1731        if (didLayout) {
1732            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
1733
1734            // By this point all views have been sized and positionned
1735            // We can compute the transparent area
1736
1737            if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1738                // start out transparent
1739                // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1740                host.getLocationInWindow(mTmpLocation);
1741                mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1742                        mTmpLocation[0] + host.mRight - host.mLeft,
1743                        mTmpLocation[1] + host.mBottom - host.mTop);
1744
1745                host.gatherTransparentRegion(mTransparentRegion);
1746                if (mTranslator != null) {
1747                    mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1748                }
1749
1750                if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1751                    mPreviousTransparentRegion.set(mTransparentRegion);
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            View focus = mView.findFocus();
2600            if (focus == null) {
2601                return false;
2602            }
2603            View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
2604            if (lastScrolledFocus != null && 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 if (focus != null) {
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                    mHandler.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 int MSG_FLICK = 1;
4336
4337        // Maximum difference in milliseconds between the down and up of a touch
4338        // event for it to be considered a tap
4339        // TODO:Read this value from a configuration file
4340        private static final int MAX_TAP_TIME = 250;
4341
4342        // Where the cutoff is for determining an edge swipe
4343        private static final float EDGE_SWIPE_THRESHOLD = 0.9f;
4344
4345        // TODO: Pass touch slop from the input device
4346        private static final int TOUCH_SLOP = 30;
4347
4348        // The position of the previous TouchNavigation event
4349        private float mLastTouchNavigationXPosition;
4350        private float mLastTouchNavigationYPosition;
4351        // Where the Touch Navigation was initially pressed
4352        private float mTouchNavigationEnterXPosition;
4353        private float mTouchNavigationEnterYPosition;
4354        // When the most recent ACTION_HOVER_ENTER occurred
4355        private long mLastTouchNavigationStartTimeMs = 0;
4356        // When the most recent direction key was sent
4357        private long mLastTouchNavigationKeySendTimeMs = 0;
4358        // When the most recent touch event of any type occurred
4359        private long mLastTouchNavigationEventTimeMs = 0;
4360        // Did the swipe begin in a valid region
4361        private boolean mEdgeSwipePossible;
4362
4363        // How quickly keys were sent
4364        private int mKeySendRateMs = 0;
4365        private int mLastKeySent;
4366        // Last movement in device screen pixels
4367        private float mLastMoveX = 0;
4368        private float mLastMoveY = 0;
4369        // Offset from the initial touch. Gets reset as direction keys are sent.
4370        private float mAccumulatedX;
4371        private float mAccumulatedY;
4372
4373        // Change in position allowed during tap events
4374        private float mTouchSlop;
4375        private float mTouchSlopSquared;
4376        // Has the TouchSlop constraint been invalidated
4377        private boolean mAlwaysInTapRegion = true;
4378
4379        // Information from the most recent event.
4380        // Used to determine what device sent the event during a fling.
4381        private int mLastSource;
4382        private int mLastMetaState;
4383        private int mLastDeviceId;
4384
4385        // TODO: Currently using screen dimensions tuned to a Galaxy Nexus, need to
4386        // read this from a config file instead
4387        private int mDistancePerTick;
4388        private int mDistancePerTickSquared;
4389        // Highest rate that the flinged events can occur at before dying out
4390        private int mMaxRepeatDelay;
4391        // The square of the minimum distance needed for a flick to register
4392        private int mMinFlickDistanceSquared;
4393        // How quickly the repeated events die off
4394        private float mFlickDecay;
4395
4396        public SyntheticTouchNavigationHandler() {
4397            super(true);
4398            mDistancePerTick = SystemProperties.getInt("persist.vr_dist_tick", 64);
4399            mDistancePerTickSquared = mDistancePerTick * mDistancePerTick;
4400            mMaxRepeatDelay = SystemProperties.getInt("persist.vr_repeat_delay", 300);
4401            mMinFlickDistanceSquared = SystemProperties.getInt("persist.vr_min_flick", 20);
4402            mMinFlickDistanceSquared *= mMinFlickDistanceSquared;
4403            mFlickDecay = Float.parseFloat(SystemProperties.get(
4404                    "persist.sys.vr_flick_decay", "1.3"));
4405            mTouchSlop = TOUCH_SLOP;
4406            mTouchSlopSquared = mTouchSlop * mTouchSlop;
4407        }
4408
4409        @Override
4410        public void handleMessage(Message msg) {
4411            switch (msg.what) {
4412                case MSG_FLICK: {
4413                    final long time = SystemClock.uptimeMillis();
4414                    final int keyCode = msg.arg2;
4415
4416                    // Send the key
4417                    enqueueInputEvent(new KeyEvent(time, time,
4418                            KeyEvent.ACTION_DOWN, keyCode, 0, mLastMetaState,
4419                            mLastDeviceId, 0, KeyEvent.FLAG_FALLBACK, mLastSource));
4420                    enqueueInputEvent(new KeyEvent(time, time,
4421                            KeyEvent.ACTION_UP, keyCode, 0, mLastMetaState,
4422                            mLastDeviceId, 0, KeyEvent.FLAG_FALLBACK, mLastSource));
4423
4424                    // Increase the delay by the decay factor and resend
4425                    final int delay = (int) Math.ceil(mFlickDecay * msg.arg1);
4426                    if (delay <= mMaxRepeatDelay) {
4427                        Message next = obtainMessage(MSG_FLICK, delay, keyCode);
4428                        next.setAsynchronous(true);
4429                        sendMessageDelayed(next, delay);
4430                    }
4431                    break;
4432                }
4433            }
4434        }
4435
4436        public void process(MotionEvent event) {
4437            update(event, true);
4438        }
4439
4440        public void cancel(MotionEvent event) {
4441            update(event, false);
4442        }
4443
4444        private void update(MotionEvent event, boolean synthesizeNewKeys) {
4445            if (!synthesizeNewKeys) {
4446                removeMessages(MSG_FLICK);
4447            }
4448
4449            InputDevice device = event.getDevice();
4450            if (device == null) {
4451                return;
4452            }
4453
4454            // Store what time the TouchNavigation event occurred
4455            final long time = SystemClock.uptimeMillis();
4456            switch (event.getAction()) {
4457                case MotionEvent.ACTION_DOWN: {
4458                    mLastTouchNavigationStartTimeMs = time;
4459                    mAlwaysInTapRegion = true;
4460                    mTouchNavigationEnterXPosition = event.getX();
4461                    mTouchNavigationEnterYPosition = event.getY();
4462                    mAccumulatedX = 0;
4463                    mAccumulatedY = 0;
4464                    mLastMoveX = 0;
4465                    mLastMoveY = 0;
4466                    if (device.getMotionRange(MotionEvent.AXIS_Y).getMax()
4467                            * EDGE_SWIPE_THRESHOLD < event.getY()) {
4468                        // Did the swipe begin in a valid region
4469                        mEdgeSwipePossible = true;
4470                    }
4471                    // Clear any flings
4472                    if (synthesizeNewKeys) {
4473                        removeMessages(MSG_FLICK);
4474                    }
4475                    break;
4476                }
4477
4478                case MotionEvent.ACTION_MOVE: {
4479                    // Determine whether the move is slop or an intentional move
4480                    float deltaX = event.getX() - mTouchNavigationEnterXPosition;
4481                    float deltaY = event.getY() - mTouchNavigationEnterYPosition;
4482                    if (mTouchSlopSquared < deltaX * deltaX + deltaY * deltaY) {
4483                        mAlwaysInTapRegion = false;
4484                    }
4485
4486                    // Checks if the swipe has crossed the midpoint
4487                    // and if our swipe gesture is complete
4488                    if (event.getY() < (device.getMotionRange(MotionEvent.AXIS_Y).getMax()
4489                            * .5) && mEdgeSwipePossible) {
4490                        mEdgeSwipePossible = false;
4491
4492                        Intent intent =
4493                                ((SearchManager)mContext.getSystemService(Context.SEARCH_SERVICE))
4494                                .getAssistIntent(mContext, false, UserHandle.USER_CURRENT_OR_SELF);
4495                        if (intent != null) {
4496                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4497                            try {
4498                                mContext.startActivity(intent);
4499                            } catch (ActivityNotFoundException e){
4500                                Log.e(TAG, "Could not start search activity");
4501                            }
4502                        } else {
4503                            Log.e(TAG, "Could not find a search activity");
4504                        }
4505                    }
4506
4507                    // Find the difference in position between the two most recent
4508                    // TouchNavigation events
4509                    mLastMoveX = event.getX() - mLastTouchNavigationXPosition;
4510                    mLastMoveY = event.getY() - mLastTouchNavigationYPosition;
4511                    mAccumulatedX += mLastMoveX;
4512                    mAccumulatedY += mLastMoveY;
4513                    float accumulatedXSquared = mAccumulatedX * mAccumulatedX;
4514                    float accumulatedYSquared = mAccumulatedY * mAccumulatedY;
4515
4516                    // Determine if we've moved far enough to send a key press
4517                    if (accumulatedXSquared > mDistancePerTickSquared
4518                            || accumulatedYSquared > mDistancePerTickSquared) {
4519                        float dominantAxis;
4520                        float sign;
4521                        boolean isXAxis;
4522                        int key;
4523                        int repeatCount = 0;
4524                        // Determine dominant axis
4525                        if (accumulatedXSquared > accumulatedYSquared) {
4526                            dominantAxis = mAccumulatedX;
4527                            isXAxis = true;
4528                        } else {
4529                            dominantAxis = mAccumulatedY;
4530                            isXAxis = false;
4531                        }
4532                        // Determine sign of axis
4533                        sign = (dominantAxis > 0) ? 1 : -1;
4534                        // Determine key to send
4535                        if (isXAxis) {
4536                            key = (sign == 1) ? KeyEvent.KEYCODE_DPAD_RIGHT :
4537                                    KeyEvent.KEYCODE_DPAD_LEFT;
4538                        } else {
4539                            key = (sign == 1) ? KeyEvent.KEYCODE_DPAD_DOWN :
4540                                    KeyEvent.KEYCODE_DPAD_UP;
4541                        }
4542                        // Send key until maximum distance constraint is satisfied
4543                        while (dominantAxis * dominantAxis > mDistancePerTickSquared) {
4544                            repeatCount++;
4545                            dominantAxis -= sign * mDistancePerTick;
4546                            if (synthesizeNewKeys) {
4547                                enqueueInputEvent(new KeyEvent(time, time,
4548                                        KeyEvent.ACTION_DOWN, key, 0, event.getMetaState(),
4549                                        event.getDeviceId(), 0, KeyEvent.FLAG_FALLBACK,
4550                                        event.getSource()));
4551                                enqueueInputEvent(new KeyEvent(time, time,
4552                                        KeyEvent.ACTION_UP, key, 0, event.getMetaState(),
4553                                        event.getDeviceId(), 0, KeyEvent.FLAG_FALLBACK,
4554                                        event.getSource()));
4555                            }
4556                        }
4557                        // Save new axis values
4558                        mAccumulatedX = isXAxis ? dominantAxis : 0;
4559                        mAccumulatedY = isXAxis ? 0 : dominantAxis;
4560
4561                        mLastKeySent = key;
4562                        mKeySendRateMs = (int) (time - mLastTouchNavigationKeySendTimeMs) /
4563                                repeatCount;
4564                        mLastTouchNavigationKeySendTimeMs = time;
4565                    }
4566                    break;
4567                }
4568
4569                case MotionEvent.ACTION_UP: {
4570                    if (time - mLastTouchNavigationStartTimeMs < MAX_TAP_TIME
4571                            && mAlwaysInTapRegion) {
4572                        if (synthesizeNewKeys) {
4573                            enqueueInputEvent(new KeyEvent(mLastTouchNavigationStartTimeMs,
4574                                        time, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0,
4575                                        event.getMetaState(), event.getDeviceId(), 0,
4576                                        KeyEvent.FLAG_FALLBACK, event.getSource()));
4577                            enqueueInputEvent(new KeyEvent(mLastTouchNavigationStartTimeMs,
4578                                        time, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0,
4579                                        event.getMetaState(), event.getDeviceId(), 0,
4580                                        KeyEvent.FLAG_FALLBACK, event.getSource()));
4581                        }
4582                    } else {
4583                        float xMoveSquared = mLastMoveX * mLastMoveX;
4584                        float yMoveSquared = mLastMoveY * mLastMoveY;
4585                        // Determine whether the last gesture was a fling.
4586                        if (mMinFlickDistanceSquared <= xMoveSquared + yMoveSquared
4587                                && time - mLastTouchNavigationEventTimeMs <= MAX_TAP_TIME
4588                                && mKeySendRateMs <= mMaxRepeatDelay
4589                                && mKeySendRateMs > 0) {
4590                            mLastDeviceId = event.getDeviceId();
4591                            mLastSource = event.getSource();
4592                            mLastMetaState = event.getMetaState();
4593
4594                            if (synthesizeNewKeys) {
4595                                Message message = obtainMessage(
4596                                        MSG_FLICK, mKeySendRateMs, mLastKeySent);
4597                                message.setAsynchronous(true);
4598                                sendMessageDelayed(message, mKeySendRateMs);
4599                            }
4600                        }
4601                    }
4602                    mEdgeSwipePossible = false;
4603                    break;
4604                }
4605            }
4606
4607            // Store touch event position and time
4608            mLastTouchNavigationEventTimeMs = time;
4609            mLastTouchNavigationXPosition = event.getX();
4610            mLastTouchNavigationYPosition = event.getY();
4611        }
4612    }
4613
4614    /**
4615     * Returns true if the key is used for keyboard navigation.
4616     * @param keyEvent The key event.
4617     * @return True if the key is used for keyboard navigation.
4618     */
4619    private static boolean isNavigationKey(KeyEvent keyEvent) {
4620        switch (keyEvent.getKeyCode()) {
4621        case KeyEvent.KEYCODE_DPAD_LEFT:
4622        case KeyEvent.KEYCODE_DPAD_RIGHT:
4623        case KeyEvent.KEYCODE_DPAD_UP:
4624        case KeyEvent.KEYCODE_DPAD_DOWN:
4625        case KeyEvent.KEYCODE_DPAD_CENTER:
4626        case KeyEvent.KEYCODE_PAGE_UP:
4627        case KeyEvent.KEYCODE_PAGE_DOWN:
4628        case KeyEvent.KEYCODE_MOVE_HOME:
4629        case KeyEvent.KEYCODE_MOVE_END:
4630        case KeyEvent.KEYCODE_TAB:
4631        case KeyEvent.KEYCODE_SPACE:
4632        case KeyEvent.KEYCODE_ENTER:
4633            return true;
4634        }
4635        return false;
4636    }
4637
4638    /**
4639     * Returns true if the key is used for typing.
4640     * @param keyEvent The key event.
4641     * @return True if the key is used for typing.
4642     */
4643    private static boolean isTypingKey(KeyEvent keyEvent) {
4644        return keyEvent.getUnicodeChar() > 0;
4645    }
4646
4647    /**
4648     * See if the key event means we should leave touch mode (and leave touch mode if so).
4649     * @param event The key event.
4650     * @return Whether this key event should be consumed (meaning the act of
4651     *   leaving touch mode alone is considered the event).
4652     */
4653    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
4654        // Only relevant in touch mode.
4655        if (!mAttachInfo.mInTouchMode) {
4656            return false;
4657        }
4658
4659        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
4660        final int action = event.getAction();
4661        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
4662            return false;
4663        }
4664
4665        // Don't leave touch mode if the IME told us not to.
4666        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
4667            return false;
4668        }
4669
4670        // If the key can be used for keyboard navigation then leave touch mode
4671        // and select a focused view if needed (in ensureTouchMode).
4672        // When a new focused view is selected, we consume the navigation key because
4673        // navigation doesn't make much sense unless a view already has focus so
4674        // the key's purpose is to set focus.
4675        if (isNavigationKey(event)) {
4676            return ensureTouchMode(false);
4677        }
4678
4679        // If the key can be used for typing then leave touch mode
4680        // and select a focused view if needed (in ensureTouchMode).
4681        // Always allow the view to process the typing key.
4682        if (isTypingKey(event)) {
4683            ensureTouchMode(false);
4684            return false;
4685        }
4686
4687        return false;
4688    }
4689
4690    /* drag/drop */
4691    void setLocalDragState(Object obj) {
4692        mLocalDragState = obj;
4693    }
4694
4695    private void handleDragEvent(DragEvent event) {
4696        // From the root, only drag start/end/location are dispatched.  entered/exited
4697        // are determined and dispatched by the viewgroup hierarchy, who then report
4698        // that back here for ultimate reporting back to the framework.
4699        if (mView != null && mAdded) {
4700            final int what = event.mAction;
4701
4702            if (what == DragEvent.ACTION_DRAG_EXITED) {
4703                // A direct EXITED event means that the window manager knows we've just crossed
4704                // a window boundary, so the current drag target within this one must have
4705                // just been exited.  Send it the usual notifications and then we're done
4706                // for now.
4707                mView.dispatchDragEvent(event);
4708            } else {
4709                // Cache the drag description when the operation starts, then fill it in
4710                // on subsequent calls as a convenience
4711                if (what == DragEvent.ACTION_DRAG_STARTED) {
4712                    mCurrentDragView = null;    // Start the current-recipient tracking
4713                    mDragDescription = event.mClipDescription;
4714                } else {
4715                    event.mClipDescription = mDragDescription;
4716                }
4717
4718                // For events with a [screen] location, translate into window coordinates
4719                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
4720                    mDragPoint.set(event.mX, event.mY);
4721                    if (mTranslator != null) {
4722                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
4723                    }
4724
4725                    if (mCurScrollY != 0) {
4726                        mDragPoint.offset(0, mCurScrollY);
4727                    }
4728
4729                    event.mX = mDragPoint.x;
4730                    event.mY = mDragPoint.y;
4731                }
4732
4733                // Remember who the current drag target is pre-dispatch
4734                final View prevDragView = mCurrentDragView;
4735
4736                // Now dispatch the drag/drop event
4737                boolean result = mView.dispatchDragEvent(event);
4738
4739                // If we changed apparent drag target, tell the OS about it
4740                if (prevDragView != mCurrentDragView) {
4741                    try {
4742                        if (prevDragView != null) {
4743                            mWindowSession.dragRecipientExited(mWindow);
4744                        }
4745                        if (mCurrentDragView != null) {
4746                            mWindowSession.dragRecipientEntered(mWindow);
4747                        }
4748                    } catch (RemoteException e) {
4749                        Slog.e(TAG, "Unable to note drag target change");
4750                    }
4751                }
4752
4753                // Report the drop result when we're done
4754                if (what == DragEvent.ACTION_DROP) {
4755                    mDragDescription = null;
4756                    try {
4757                        Log.i(TAG, "Reporting drop result: " + result);
4758                        mWindowSession.reportDropResult(mWindow, result);
4759                    } catch (RemoteException e) {
4760                        Log.e(TAG, "Unable to report drop result");
4761                    }
4762                }
4763
4764                // When the drag operation ends, release any local state object
4765                // that may have been in use
4766                if (what == DragEvent.ACTION_DRAG_ENDED) {
4767                    setLocalDragState(null);
4768                }
4769            }
4770        }
4771        event.recycle();
4772    }
4773
4774    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
4775        if (mSeq != args.seq) {
4776            // The sequence has changed, so we need to update our value and make
4777            // sure to do a traversal afterward so the window manager is given our
4778            // most recent data.
4779            mSeq = args.seq;
4780            mAttachInfo.mForceReportNewAttributes = true;
4781            scheduleTraversals();
4782        }
4783        if (mView == null) return;
4784        if (args.localChanges != 0) {
4785            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
4786        }
4787        if (mAttachInfo != null) {
4788            int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
4789            if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
4790                mAttachInfo.mGlobalSystemUiVisibility = visibility;
4791                mView.dispatchSystemUiVisibilityChanged(visibility);
4792            }
4793        }
4794    }
4795
4796    public void handleDispatchDoneAnimating() {
4797        if (mWindowsAnimating) {
4798            mWindowsAnimating = false;
4799            if (!mDirty.isEmpty() || mIsAnimating)  {
4800                scheduleTraversals();
4801            }
4802        }
4803    }
4804
4805    public void getLastTouchPoint(Point outLocation) {
4806        outLocation.x = (int) mLastTouchPoint.x;
4807        outLocation.y = (int) mLastTouchPoint.y;
4808    }
4809
4810    public void setDragFocus(View newDragTarget) {
4811        if (mCurrentDragView != newDragTarget) {
4812            mCurrentDragView = newDragTarget;
4813        }
4814    }
4815
4816    private AudioManager getAudioManager() {
4817        if (mView == null) {
4818            throw new IllegalStateException("getAudioManager called when there is no mView");
4819        }
4820        if (mAudioManager == null) {
4821            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
4822        }
4823        return mAudioManager;
4824    }
4825
4826    public AccessibilityInteractionController getAccessibilityInteractionController() {
4827        if (mView == null) {
4828            throw new IllegalStateException("getAccessibilityInteractionController"
4829                    + " called when there is no mView");
4830        }
4831        if (mAccessibilityInteractionController == null) {
4832            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
4833        }
4834        return mAccessibilityInteractionController;
4835    }
4836
4837    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
4838            boolean insetsPending) throws RemoteException {
4839
4840        float appScale = mAttachInfo.mApplicationScale;
4841        boolean restore = false;
4842        if (params != null && mTranslator != null) {
4843            restore = true;
4844            params.backup();
4845            mTranslator.translateWindowLayout(params);
4846        }
4847        if (params != null) {
4848            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
4849        }
4850        mPendingConfiguration.seq = 0;
4851        //Log.d(TAG, ">>>>>> CALLING relayout");
4852        if (params != null && mOrigWindowType != params.type) {
4853            // For compatibility with old apps, don't crash here.
4854            if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4855                Slog.w(TAG, "Window type can not be changed after "
4856                        + "the window is added; ignoring change of " + mView);
4857                params.type = mOrigWindowType;
4858            }
4859        }
4860        int relayoutResult = mWindowSession.relayout(
4861                mWindow, mSeq, params,
4862                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
4863                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
4864                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
4865                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
4866                mPendingConfiguration, mSurface);
4867        //Log.d(TAG, "<<<<<< BACK FROM relayout");
4868        if (restore) {
4869            params.restore();
4870        }
4871
4872        if (mTranslator != null) {
4873            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
4874            mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
4875            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
4876            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
4877        }
4878        return relayoutResult;
4879    }
4880
4881    /**
4882     * {@inheritDoc}
4883     */
4884    public void playSoundEffect(int effectId) {
4885        checkThread();
4886
4887        try {
4888            final AudioManager audioManager = getAudioManager();
4889
4890            switch (effectId) {
4891                case SoundEffectConstants.CLICK:
4892                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
4893                    return;
4894                case SoundEffectConstants.NAVIGATION_DOWN:
4895                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
4896                    return;
4897                case SoundEffectConstants.NAVIGATION_LEFT:
4898                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
4899                    return;
4900                case SoundEffectConstants.NAVIGATION_RIGHT:
4901                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
4902                    return;
4903                case SoundEffectConstants.NAVIGATION_UP:
4904                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
4905                    return;
4906                default:
4907                    throw new IllegalArgumentException("unknown effect id " + effectId +
4908                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
4909            }
4910        } catch (IllegalStateException e) {
4911            // Exception thrown by getAudioManager() when mView is null
4912            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
4913            e.printStackTrace();
4914        }
4915    }
4916
4917    /**
4918     * {@inheritDoc}
4919     */
4920    public boolean performHapticFeedback(int effectId, boolean always) {
4921        try {
4922            return mWindowSession.performHapticFeedback(mWindow, effectId, always);
4923        } catch (RemoteException e) {
4924            return false;
4925        }
4926    }
4927
4928    /**
4929     * {@inheritDoc}
4930     */
4931    public View focusSearch(View focused, int direction) {
4932        checkThread();
4933        if (!(mView instanceof ViewGroup)) {
4934            return null;
4935        }
4936        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
4937    }
4938
4939    public void debug() {
4940        mView.debug();
4941    }
4942
4943    public void dumpGfxInfo(int[] info) {
4944        info[0] = info[1] = 0;
4945        if (mView != null) {
4946            getGfxInfo(mView, info);
4947        }
4948    }
4949
4950    private static void getGfxInfo(View view, int[] info) {
4951        DisplayList displayList = view.mDisplayList;
4952        info[0]++;
4953        if (displayList != null) {
4954            info[1] += displayList.getSize();
4955        }
4956
4957        if (view instanceof ViewGroup) {
4958            ViewGroup group = (ViewGroup) view;
4959
4960            int count = group.getChildCount();
4961            for (int i = 0; i < count; i++) {
4962                getGfxInfo(group.getChildAt(i), info);
4963            }
4964        }
4965    }
4966
4967    public void die(boolean immediate) {
4968        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
4969        // done by dispatchDetachedFromWindow will cause havoc on return.
4970        if (immediate && !mIsInTraversal) {
4971            doDie();
4972        } else {
4973            if (!mIsDrawing) {
4974                destroyHardwareRenderer();
4975            } else {
4976                Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
4977                        "  window=" + this + ", title=" + mWindowAttributes.getTitle());
4978            }
4979            mHandler.sendEmptyMessage(MSG_DIE);
4980        }
4981    }
4982
4983    void doDie() {
4984        checkThread();
4985        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
4986        synchronized (this) {
4987            if (mAdded) {
4988                dispatchDetachedFromWindow();
4989            }
4990
4991            if (mAdded && !mFirst) {
4992                invalidateDisplayLists();
4993                destroyHardwareRenderer();
4994
4995                if (mView != null) {
4996                    int viewVisibility = mView.getVisibility();
4997                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
4998                    if (mWindowAttributesChanged || viewVisibilityChanged) {
4999                        // If layout params have been changed, first give them
5000                        // to the window manager to make sure it has the correct
5001                        // animation info.
5002                        try {
5003                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5004                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5005                                mWindowSession.finishDrawing(mWindow);
5006                            }
5007                        } catch (RemoteException e) {
5008                        }
5009                    }
5010
5011                    mSurface.release();
5012                }
5013            }
5014
5015            mAdded = false;
5016        }
5017    }
5018
5019    public void requestUpdateConfiguration(Configuration config) {
5020        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5021        mHandler.sendMessage(msg);
5022    }
5023
5024    public void loadSystemProperties() {
5025        mHandler.post(new Runnable() {
5026            @Override
5027            public void run() {
5028                // Profiling
5029                mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5030                profileRendering(mAttachInfo.mHasWindowFocus);
5031
5032                // Hardware rendering
5033                if (mAttachInfo.mHardwareRenderer != null) {
5034                    if (mAttachInfo.mHardwareRenderer.loadSystemProperties(mHolder.getSurface())) {
5035                        invalidate();
5036                    }
5037                }
5038
5039                // Layout debugging
5040                boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5041                if (layout != mAttachInfo.mDebugLayout) {
5042                    mAttachInfo.mDebugLayout = layout;
5043                    if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5044                        mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5045                    }
5046                }
5047            }
5048        });
5049    }
5050
5051    private void destroyHardwareRenderer() {
5052        AttachInfo attachInfo = mAttachInfo;
5053        HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer;
5054
5055        if (hardwareRenderer != null) {
5056            if (mView != null) {
5057                hardwareRenderer.destroyHardwareResources(mView);
5058            }
5059            hardwareRenderer.destroy(true);
5060            hardwareRenderer.setRequested(false);
5061
5062            attachInfo.mHardwareRenderer = null;
5063            attachInfo.mHardwareAccelerated = false;
5064        }
5065    }
5066
5067    public void dispatchFinishInputConnection(InputConnection connection) {
5068        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
5069        mHandler.sendMessage(msg);
5070    }
5071
5072    public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
5073            Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
5074        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
5075                + " contentInsets=" + contentInsets.toShortString()
5076                + " visibleInsets=" + visibleInsets.toShortString()
5077                + " reportDraw=" + reportDraw);
5078        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
5079        if (mTranslator != null) {
5080            mTranslator.translateRectInScreenToAppWindow(frame);
5081            mTranslator.translateRectInScreenToAppWindow(overscanInsets);
5082            mTranslator.translateRectInScreenToAppWindow(contentInsets);
5083            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
5084        }
5085        SomeArgs args = SomeArgs.obtain();
5086        final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5087        args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5088        args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5089        args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5090        args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
5091        args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
5092        msg.obj = args;
5093        mHandler.sendMessage(msg);
5094    }
5095
5096    public void dispatchMoved(int newX, int newY) {
5097        if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
5098        if (mTranslator != null) {
5099            PointF point = new PointF(newX, newY);
5100            mTranslator.translatePointInScreenToAppWindow(point);
5101            newX = (int) (point.x + 0.5);
5102            newY = (int) (point.y + 0.5);
5103        }
5104        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5105        mHandler.sendMessage(msg);
5106    }
5107
5108    /**
5109     * Represents a pending input event that is waiting in a queue.
5110     *
5111     * Input events are processed in serial order by the timestamp specified by
5112     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
5113     * one input event to the application at a time and waits for the application
5114     * to finish handling it before delivering the next one.
5115     *
5116     * However, because the application or IME can synthesize and inject multiple
5117     * key events at a time without going through the input dispatcher, we end up
5118     * needing a queue on the application's side.
5119     */
5120    private static final class QueuedInputEvent {
5121        public static final int FLAG_DELIVER_POST_IME = 1 << 0;
5122        public static final int FLAG_DEFERRED = 1 << 1;
5123        public static final int FLAG_FINISHED = 1 << 2;
5124        public static final int FLAG_FINISHED_HANDLED = 1 << 3;
5125        public static final int FLAG_RESYNTHESIZED = 1 << 4;
5126
5127        public QueuedInputEvent mNext;
5128
5129        public InputEvent mEvent;
5130        public InputEventReceiver mReceiver;
5131        public int mFlags;
5132
5133        public boolean shouldSkipIme() {
5134            if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5135                return true;
5136            }
5137            return mEvent instanceof MotionEvent
5138                    && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5139        }
5140    }
5141
5142    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
5143            InputEventReceiver receiver, int flags) {
5144        QueuedInputEvent q = mQueuedInputEventPool;
5145        if (q != null) {
5146            mQueuedInputEventPoolSize -= 1;
5147            mQueuedInputEventPool = q.mNext;
5148            q.mNext = null;
5149        } else {
5150            q = new QueuedInputEvent();
5151        }
5152
5153        q.mEvent = event;
5154        q.mReceiver = receiver;
5155        q.mFlags = flags;
5156        return q;
5157    }
5158
5159    private void recycleQueuedInputEvent(QueuedInputEvent q) {
5160        q.mEvent = null;
5161        q.mReceiver = null;
5162
5163        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
5164            mQueuedInputEventPoolSize += 1;
5165            q.mNext = mQueuedInputEventPool;
5166            mQueuedInputEventPool = q;
5167        }
5168    }
5169
5170    void enqueueInputEvent(InputEvent event) {
5171        enqueueInputEvent(event, null, 0, false);
5172    }
5173
5174    void enqueueInputEvent(InputEvent event,
5175            InputEventReceiver receiver, int flags, boolean processImmediately) {
5176        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
5177
5178        // Always enqueue the input event in order, regardless of its time stamp.
5179        // We do this because the application or the IME may inject key events
5180        // in response to touch events and we want to ensure that the injected keys
5181        // are processed in the order they were received and we cannot trust that
5182        // the time stamp of injected events are monotonic.
5183        QueuedInputEvent last = mPendingInputEventTail;
5184        if (last == null) {
5185            mPendingInputEventHead = q;
5186            mPendingInputEventTail = q;
5187        } else {
5188            last.mNext = q;
5189            mPendingInputEventTail = q;
5190        }
5191        mPendingInputEventCount += 1;
5192        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5193                mPendingInputEventCount);
5194
5195        if (processImmediately) {
5196            doProcessInputEvents();
5197        } else {
5198            scheduleProcessInputEvents();
5199        }
5200    }
5201
5202    private void scheduleProcessInputEvents() {
5203        if (!mProcessInputEventsScheduled) {
5204            mProcessInputEventsScheduled = true;
5205            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
5206            msg.setAsynchronous(true);
5207            mHandler.sendMessage(msg);
5208        }
5209    }
5210
5211    void doProcessInputEvents() {
5212        // Deliver all pending input events in the queue.
5213        while (mPendingInputEventHead != null) {
5214            QueuedInputEvent q = mPendingInputEventHead;
5215            mPendingInputEventHead = q.mNext;
5216            if (mPendingInputEventHead == null) {
5217                mPendingInputEventTail = null;
5218            }
5219            q.mNext = null;
5220
5221            mPendingInputEventCount -= 1;
5222            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5223                    mPendingInputEventCount);
5224
5225            deliverInputEvent(q);
5226        }
5227
5228        // We are done processing all input events that we can process right now
5229        // so we can clear the pending flag immediately.
5230        if (mProcessInputEventsScheduled) {
5231            mProcessInputEventsScheduled = false;
5232            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
5233        }
5234    }
5235
5236    private void deliverInputEvent(QueuedInputEvent q) {
5237        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
5238        try {
5239            if (mInputEventConsistencyVerifier != null) {
5240                mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
5241            }
5242
5243            InputStage stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
5244            if (stage != null) {
5245                stage.deliver(q);
5246            } else {
5247                finishInputEvent(q);
5248            }
5249        } finally {
5250            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
5251        }
5252    }
5253
5254    private void finishInputEvent(QueuedInputEvent q) {
5255        if (q.mReceiver != null) {
5256            boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
5257            q.mReceiver.finishInputEvent(q.mEvent, handled);
5258        } else {
5259            q.mEvent.recycleIfNeededAfterDispatch();
5260        }
5261
5262        recycleQueuedInputEvent(q);
5263    }
5264
5265    static boolean isTerminalInputEvent(InputEvent event) {
5266        if (event instanceof KeyEvent) {
5267            final KeyEvent keyEvent = (KeyEvent)event;
5268            return keyEvent.getAction() == KeyEvent.ACTION_UP;
5269        } else {
5270            final MotionEvent motionEvent = (MotionEvent)event;
5271            final int action = motionEvent.getAction();
5272            return action == MotionEvent.ACTION_UP
5273                    || action == MotionEvent.ACTION_CANCEL
5274                    || action == MotionEvent.ACTION_HOVER_EXIT;
5275        }
5276    }
5277
5278    void scheduleConsumeBatchedInput() {
5279        if (!mConsumeBatchedInputScheduled) {
5280            mConsumeBatchedInputScheduled = true;
5281            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
5282                    mConsumedBatchedInputRunnable, null);
5283        }
5284    }
5285
5286    void unscheduleConsumeBatchedInput() {
5287        if (mConsumeBatchedInputScheduled) {
5288            mConsumeBatchedInputScheduled = false;
5289            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
5290                    mConsumedBatchedInputRunnable, null);
5291        }
5292    }
5293
5294    void doConsumeBatchedInput(long frameTimeNanos) {
5295        if (mConsumeBatchedInputScheduled) {
5296            mConsumeBatchedInputScheduled = false;
5297            if (mInputEventReceiver != null) {
5298                mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos);
5299            }
5300            doProcessInputEvents();
5301        }
5302    }
5303
5304    final class TraversalRunnable implements Runnable {
5305        @Override
5306        public void run() {
5307            doTraversal();
5308        }
5309    }
5310    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
5311
5312    final class WindowInputEventReceiver extends InputEventReceiver {
5313        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
5314            super(inputChannel, looper);
5315        }
5316
5317        @Override
5318        public void onInputEvent(InputEvent event) {
5319            enqueueInputEvent(event, this, 0, true);
5320        }
5321
5322        @Override
5323        public void onBatchedInputEventPending() {
5324            scheduleConsumeBatchedInput();
5325        }
5326
5327        @Override
5328        public void dispose() {
5329            unscheduleConsumeBatchedInput();
5330            super.dispose();
5331        }
5332    }
5333    WindowInputEventReceiver mInputEventReceiver;
5334
5335    final class ConsumeBatchedInputRunnable implements Runnable {
5336        @Override
5337        public void run() {
5338            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
5339        }
5340    }
5341    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
5342            new ConsumeBatchedInputRunnable();
5343    boolean mConsumeBatchedInputScheduled;
5344
5345    final class InvalidateOnAnimationRunnable implements Runnable {
5346        private boolean mPosted;
5347        private ArrayList<View> mViews = new ArrayList<View>();
5348        private ArrayList<AttachInfo.InvalidateInfo> mViewRects =
5349                new ArrayList<AttachInfo.InvalidateInfo>();
5350        private View[] mTempViews;
5351        private AttachInfo.InvalidateInfo[] mTempViewRects;
5352
5353        public void addView(View view) {
5354            synchronized (this) {
5355                mViews.add(view);
5356                postIfNeededLocked();
5357            }
5358        }
5359
5360        public void addViewRect(AttachInfo.InvalidateInfo info) {
5361            synchronized (this) {
5362                mViewRects.add(info);
5363                postIfNeededLocked();
5364            }
5365        }
5366
5367        public void removeView(View view) {
5368            synchronized (this) {
5369                mViews.remove(view);
5370
5371                for (int i = mViewRects.size(); i-- > 0; ) {
5372                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
5373                    if (info.target == view) {
5374                        mViewRects.remove(i);
5375                        info.recycle();
5376                    }
5377                }
5378
5379                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
5380                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
5381                    mPosted = false;
5382                }
5383            }
5384        }
5385
5386        @Override
5387        public void run() {
5388            final int viewCount;
5389            final int viewRectCount;
5390            synchronized (this) {
5391                mPosted = false;
5392
5393                viewCount = mViews.size();
5394                if (viewCount != 0) {
5395                    mTempViews = mViews.toArray(mTempViews != null
5396                            ? mTempViews : new View[viewCount]);
5397                    mViews.clear();
5398                }
5399
5400                viewRectCount = mViewRects.size();
5401                if (viewRectCount != 0) {
5402                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
5403                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
5404                    mViewRects.clear();
5405                }
5406            }
5407
5408            for (int i = 0; i < viewCount; i++) {
5409                mTempViews[i].invalidate();
5410                mTempViews[i] = null;
5411            }
5412
5413            for (int i = 0; i < viewRectCount; i++) {
5414                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
5415                info.target.invalidate(info.left, info.top, info.right, info.bottom);
5416                info.recycle();
5417            }
5418        }
5419
5420        private void postIfNeededLocked() {
5421            if (!mPosted) {
5422                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
5423                mPosted = true;
5424            }
5425        }
5426    }
5427    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
5428            new InvalidateOnAnimationRunnable();
5429
5430    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
5431        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
5432        mHandler.sendMessageDelayed(msg, delayMilliseconds);
5433    }
5434
5435    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
5436            long delayMilliseconds) {
5437        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
5438        mHandler.sendMessageDelayed(msg, delayMilliseconds);
5439    }
5440
5441    public void dispatchInvalidateOnAnimation(View view) {
5442        mInvalidateOnAnimationRunnable.addView(view);
5443    }
5444
5445    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
5446        mInvalidateOnAnimationRunnable.addViewRect(info);
5447    }
5448
5449    public void enqueueDisplayList(DisplayList displayList) {
5450        mDisplayLists.add(displayList);
5451    }
5452
5453    public void cancelInvalidate(View view) {
5454        mHandler.removeMessages(MSG_INVALIDATE, view);
5455        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
5456        // them to the pool
5457        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
5458        mInvalidateOnAnimationRunnable.removeView(view);
5459    }
5460
5461    public void dispatchKey(KeyEvent event) {
5462        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event);
5463        msg.setAsynchronous(true);
5464        mHandler.sendMessage(msg);
5465    }
5466
5467    public void dispatchKeyFromIme(KeyEvent event) {
5468        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
5469        msg.setAsynchronous(true);
5470        mHandler.sendMessage(msg);
5471    }
5472
5473    public void dispatchUnhandledKey(KeyEvent event) {
5474        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5475            final KeyCharacterMap kcm = event.getKeyCharacterMap();
5476            final int keyCode = event.getKeyCode();
5477            final int metaState = event.getMetaState();
5478
5479            // Check for fallback actions specified by the key character map.
5480            KeyCharacterMap.FallbackAction fallbackAction =
5481                    kcm.getFallbackAction(keyCode, metaState);
5482            if (fallbackAction != null) {
5483                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5484                KeyEvent fallbackEvent = KeyEvent.obtain(
5485                        event.getDownTime(), event.getEventTime(),
5486                        event.getAction(), fallbackAction.keyCode,
5487                        event.getRepeatCount(), fallbackAction.metaState,
5488                        event.getDeviceId(), event.getScanCode(),
5489                        flags, event.getSource(), null);
5490                fallbackAction.recycle();
5491
5492                dispatchKey(fallbackEvent);
5493            }
5494        }
5495    }
5496
5497    public void dispatchAppVisibility(boolean visible) {
5498        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
5499        msg.arg1 = visible ? 1 : 0;
5500        mHandler.sendMessage(msg);
5501    }
5502
5503    public void dispatchScreenStateChange(boolean on) {
5504        Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE);
5505        msg.arg1 = on ? 1 : 0;
5506        mHandler.sendMessage(msg);
5507    }
5508
5509    public void dispatchGetNewSurface() {
5510        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
5511        mHandler.sendMessage(msg);
5512    }
5513
5514    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
5515        Message msg = Message.obtain();
5516        msg.what = MSG_WINDOW_FOCUS_CHANGED;
5517        msg.arg1 = hasFocus ? 1 : 0;
5518        msg.arg2 = inTouchMode ? 1 : 0;
5519        mHandler.sendMessage(msg);
5520    }
5521
5522    public void dispatchCloseSystemDialogs(String reason) {
5523        Message msg = Message.obtain();
5524        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
5525        msg.obj = reason;
5526        mHandler.sendMessage(msg);
5527    }
5528
5529    public void dispatchDragEvent(DragEvent event) {
5530        final int what;
5531        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
5532            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
5533            mHandler.removeMessages(what);
5534        } else {
5535            what = MSG_DISPATCH_DRAG_EVENT;
5536        }
5537        Message msg = mHandler.obtainMessage(what, event);
5538        mHandler.sendMessage(msg);
5539    }
5540
5541    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
5542            int localValue, int localChanges) {
5543        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
5544        args.seq = seq;
5545        args.globalVisibility = globalVisibility;
5546        args.localValue = localValue;
5547        args.localChanges = localChanges;
5548        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
5549    }
5550
5551    public void dispatchDoneAnimating() {
5552        mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
5553    }
5554
5555    public void dispatchCheckFocus() {
5556        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
5557            // This will result in a call to checkFocus() below.
5558            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
5559        }
5560    }
5561
5562    /**
5563     * Post a callback to send a
5564     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
5565     * This event is send at most once every
5566     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
5567     */
5568    private void postSendWindowContentChangedCallback(View source) {
5569        if (mSendWindowContentChangedAccessibilityEvent == null) {
5570            mSendWindowContentChangedAccessibilityEvent =
5571                new SendWindowContentChangedAccessibilityEvent();
5572        }
5573        View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource;
5574        if (oldSource == null) {
5575            mSendWindowContentChangedAccessibilityEvent.mSource = source;
5576            mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent,
5577                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
5578        } else {
5579            mSendWindowContentChangedAccessibilityEvent.mSource =
5580                    getCommonPredecessor(oldSource, source);
5581        }
5582    }
5583
5584    /**
5585     * Remove a posted callback to send a
5586     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
5587     */
5588    private void removeSendWindowContentChangedCallback() {
5589        if (mSendWindowContentChangedAccessibilityEvent != null) {
5590            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
5591        }
5592    }
5593
5594    public boolean showContextMenuForChild(View originalView) {
5595        return false;
5596    }
5597
5598    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
5599        return null;
5600    }
5601
5602    public void createContextMenu(ContextMenu menu) {
5603    }
5604
5605    public void childDrawableStateChanged(View child) {
5606    }
5607
5608    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
5609        if (mView == null) {
5610            return false;
5611        }
5612        // Intercept accessibility focus events fired by virtual nodes to keep
5613        // track of accessibility focus position in such nodes.
5614        final int eventType = event.getEventType();
5615        switch (eventType) {
5616            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
5617                final long sourceNodeId = event.getSourceNodeId();
5618                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
5619                        sourceNodeId);
5620                View source = mView.findViewByAccessibilityId(accessibilityViewId);
5621                if (source != null) {
5622                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
5623                    if (provider != null) {
5624                        AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(
5625                                AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId));
5626                        setAccessibilityFocus(source, node);
5627                    }
5628                }
5629            } break;
5630            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
5631                final long sourceNodeId = event.getSourceNodeId();
5632                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
5633                        sourceNodeId);
5634                View source = mView.findViewByAccessibilityId(accessibilityViewId);
5635                if (source != null) {
5636                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
5637                    if (provider != null) {
5638                        setAccessibilityFocus(null, null);
5639                    }
5640                }
5641            } break;
5642        }
5643        mAccessibilityManager.sendAccessibilityEvent(event);
5644        return true;
5645    }
5646
5647    @Override
5648    public void childAccessibilityStateChanged(View child) {
5649        postSendWindowContentChangedCallback(child);
5650    }
5651
5652    @Override
5653    public boolean canResolveLayoutDirection() {
5654        return true;
5655    }
5656
5657    @Override
5658    public boolean isLayoutDirectionResolved() {
5659        return true;
5660    }
5661
5662    @Override
5663    public int getLayoutDirection() {
5664        return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
5665    }
5666
5667    @Override
5668    public boolean canResolveTextDirection() {
5669        return true;
5670    }
5671
5672    @Override
5673    public boolean isTextDirectionResolved() {
5674        return true;
5675    }
5676
5677    @Override
5678    public int getTextDirection() {
5679        return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
5680    }
5681
5682    @Override
5683    public boolean canResolveTextAlignment() {
5684        return true;
5685    }
5686
5687    @Override
5688    public boolean isTextAlignmentResolved() {
5689        return true;
5690    }
5691
5692    @Override
5693    public int getTextAlignment() {
5694        return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
5695    }
5696
5697    private View getCommonPredecessor(View first, View second) {
5698        if (mAttachInfo != null) {
5699            if (mTempHashSet == null) {
5700                mTempHashSet = new HashSet<View>();
5701            }
5702            HashSet<View> seen = mTempHashSet;
5703            seen.clear();
5704            View firstCurrent = first;
5705            while (firstCurrent != null) {
5706                seen.add(firstCurrent);
5707                ViewParent firstCurrentParent = firstCurrent.mParent;
5708                if (firstCurrentParent instanceof View) {
5709                    firstCurrent = (View) firstCurrentParent;
5710                } else {
5711                    firstCurrent = null;
5712                }
5713            }
5714            View secondCurrent = second;
5715            while (secondCurrent != null) {
5716                if (seen.contains(secondCurrent)) {
5717                    seen.clear();
5718                    return secondCurrent;
5719                }
5720                ViewParent secondCurrentParent = secondCurrent.mParent;
5721                if (secondCurrentParent instanceof View) {
5722                    secondCurrent = (View) secondCurrentParent;
5723                } else {
5724                    secondCurrent = null;
5725                }
5726            }
5727            seen.clear();
5728        }
5729        return null;
5730    }
5731
5732    void checkThread() {
5733        if (mThread != Thread.currentThread()) {
5734            throw new CalledFromWrongThreadException(
5735                    "Only the original thread that created a view hierarchy can touch its views.");
5736        }
5737    }
5738
5739    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
5740        // ViewAncestor never intercepts touch event, so this can be a no-op
5741    }
5742
5743    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
5744        final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
5745        if (rectangle != null) {
5746            mTempRect.set(rectangle);
5747            mTempRect.offset(0, -mCurScrollY);
5748            mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5749            try {
5750                mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate);
5751            } catch (RemoteException re) {
5752                /* ignore */
5753            }
5754        }
5755        return scrolled;
5756    }
5757
5758    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
5759        // Do nothing.
5760    }
5761
5762    class TakenSurfaceHolder extends BaseSurfaceHolder {
5763        @Override
5764        public boolean onAllowLockCanvas() {
5765            return mDrawingAllowed;
5766        }
5767
5768        @Override
5769        public void onRelayoutContainer() {
5770            // Not currently interesting -- from changing between fixed and layout size.
5771        }
5772
5773        public void setFormat(int format) {
5774            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
5775        }
5776
5777        public void setType(int type) {
5778            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
5779        }
5780
5781        @Override
5782        public void onUpdateSurface() {
5783            // We take care of format and type changes on our own.
5784            throw new IllegalStateException("Shouldn't be here");
5785        }
5786
5787        public boolean isCreating() {
5788            return mIsCreating;
5789        }
5790
5791        @Override
5792        public void setFixedSize(int width, int height) {
5793            throw new UnsupportedOperationException(
5794                    "Currently only support sizing from layout");
5795        }
5796
5797        public void setKeepScreenOn(boolean screenOn) {
5798            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
5799        }
5800    }
5801
5802    static class W extends IWindow.Stub {
5803        private final WeakReference<ViewRootImpl> mViewAncestor;
5804        private final IWindowSession mWindowSession;
5805
5806        W(ViewRootImpl viewAncestor) {
5807            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
5808            mWindowSession = viewAncestor.mWindowSession;
5809        }
5810
5811        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
5812                Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
5813            final ViewRootImpl viewAncestor = mViewAncestor.get();
5814            if (viewAncestor != null) {
5815                viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
5816                        visibleInsets, reportDraw, newConfig);
5817            }
5818        }
5819
5820        @Override
5821        public void moved(int newX, int newY) {
5822            final ViewRootImpl viewAncestor = mViewAncestor.get();
5823            if (viewAncestor != null) {
5824                viewAncestor.dispatchMoved(newX, newY);
5825            }
5826        }
5827
5828        public void dispatchAppVisibility(boolean visible) {
5829            final ViewRootImpl viewAncestor = mViewAncestor.get();
5830            if (viewAncestor != null) {
5831                viewAncestor.dispatchAppVisibility(visible);
5832            }
5833        }
5834
5835        public void dispatchScreenState(boolean on) {
5836            final ViewRootImpl viewAncestor = mViewAncestor.get();
5837            if (viewAncestor != null) {
5838                viewAncestor.dispatchScreenStateChange(on);
5839            }
5840        }
5841
5842        public void dispatchGetNewSurface() {
5843            final ViewRootImpl viewAncestor = mViewAncestor.get();
5844            if (viewAncestor != null) {
5845                viewAncestor.dispatchGetNewSurface();
5846            }
5847        }
5848
5849        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
5850            final ViewRootImpl viewAncestor = mViewAncestor.get();
5851            if (viewAncestor != null) {
5852                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
5853            }
5854        }
5855
5856        private static int checkCallingPermission(String permission) {
5857            try {
5858                return ActivityManagerNative.getDefault().checkPermission(
5859                        permission, Binder.getCallingPid(), Binder.getCallingUid());
5860            } catch (RemoteException e) {
5861                return PackageManager.PERMISSION_DENIED;
5862            }
5863        }
5864
5865        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
5866            final ViewRootImpl viewAncestor = mViewAncestor.get();
5867            if (viewAncestor != null) {
5868                final View view = viewAncestor.mView;
5869                if (view != null) {
5870                    if (checkCallingPermission(Manifest.permission.DUMP) !=
5871                            PackageManager.PERMISSION_GRANTED) {
5872                        throw new SecurityException("Insufficient permissions to invoke"
5873                                + " executeCommand() from pid=" + Binder.getCallingPid()
5874                                + ", uid=" + Binder.getCallingUid());
5875                    }
5876
5877                    OutputStream clientStream = null;
5878                    try {
5879                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
5880                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
5881                    } catch (IOException e) {
5882                        e.printStackTrace();
5883                    } finally {
5884                        if (clientStream != null) {
5885                            try {
5886                                clientStream.close();
5887                            } catch (IOException e) {
5888                                e.printStackTrace();
5889                            }
5890                        }
5891                    }
5892                }
5893            }
5894        }
5895
5896        public void closeSystemDialogs(String reason) {
5897            final ViewRootImpl viewAncestor = mViewAncestor.get();
5898            if (viewAncestor != null) {
5899                viewAncestor.dispatchCloseSystemDialogs(reason);
5900            }
5901        }
5902
5903        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
5904                boolean sync) {
5905            if (sync) {
5906                try {
5907                    mWindowSession.wallpaperOffsetsComplete(asBinder());
5908                } catch (RemoteException e) {
5909                }
5910            }
5911        }
5912
5913        public void dispatchWallpaperCommand(String action, int x, int y,
5914                int z, Bundle extras, boolean sync) {
5915            if (sync) {
5916                try {
5917                    mWindowSession.wallpaperCommandComplete(asBinder(), null);
5918                } catch (RemoteException e) {
5919                }
5920            }
5921        }
5922
5923        /* Drag/drop */
5924        public void dispatchDragEvent(DragEvent event) {
5925            final ViewRootImpl viewAncestor = mViewAncestor.get();
5926            if (viewAncestor != null) {
5927                viewAncestor.dispatchDragEvent(event);
5928            }
5929        }
5930
5931        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
5932                int localValue, int localChanges) {
5933            final ViewRootImpl viewAncestor = mViewAncestor.get();
5934            if (viewAncestor != null) {
5935                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
5936                        localValue, localChanges);
5937            }
5938        }
5939
5940        public void doneAnimating() {
5941            final ViewRootImpl viewAncestor = mViewAncestor.get();
5942            if (viewAncestor != null) {
5943                viewAncestor.dispatchDoneAnimating();
5944            }
5945        }
5946    }
5947
5948    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
5949        public CalledFromWrongThreadException(String msg) {
5950            super(msg);
5951        }
5952    }
5953
5954    private SurfaceHolder mHolder = new SurfaceHolder() {
5955        // we only need a SurfaceHolder for opengl. it would be nice
5956        // to implement everything else though, especially the callback
5957        // support (opengl doesn't make use of it right now, but eventually
5958        // will).
5959        public Surface getSurface() {
5960            return mSurface;
5961        }
5962
5963        public boolean isCreating() {
5964            return false;
5965        }
5966
5967        public void addCallback(Callback callback) {
5968        }
5969
5970        public void removeCallback(Callback callback) {
5971        }
5972
5973        public void setFixedSize(int width, int height) {
5974        }
5975
5976        public void setSizeFromLayout() {
5977        }
5978
5979        public void setFormat(int format) {
5980        }
5981
5982        public void setType(int type) {
5983        }
5984
5985        public void setKeepScreenOn(boolean screenOn) {
5986        }
5987
5988        public Canvas lockCanvas() {
5989            return null;
5990        }
5991
5992        public Canvas lockCanvas(Rect dirty) {
5993            return null;
5994        }
5995
5996        public void unlockCanvasAndPost(Canvas canvas) {
5997        }
5998        public Rect getSurfaceFrame() {
5999            return null;
6000        }
6001    };
6002
6003    static RunQueue getRunQueue() {
6004        RunQueue rq = sRunQueues.get();
6005        if (rq != null) {
6006            return rq;
6007        }
6008        rq = new RunQueue();
6009        sRunQueues.set(rq);
6010        return rq;
6011    }
6012
6013    /**
6014     * The run queue is used to enqueue pending work from Views when no Handler is
6015     * attached.  The work is executed during the next call to performTraversals on
6016     * the thread.
6017     * @hide
6018     */
6019    static final class RunQueue {
6020        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
6021
6022        void post(Runnable action) {
6023            postDelayed(action, 0);
6024        }
6025
6026        void postDelayed(Runnable action, long delayMillis) {
6027            HandlerAction handlerAction = new HandlerAction();
6028            handlerAction.action = action;
6029            handlerAction.delay = delayMillis;
6030
6031            synchronized (mActions) {
6032                mActions.add(handlerAction);
6033            }
6034        }
6035
6036        void removeCallbacks(Runnable action) {
6037            final HandlerAction handlerAction = new HandlerAction();
6038            handlerAction.action = action;
6039
6040            synchronized (mActions) {
6041                final ArrayList<HandlerAction> actions = mActions;
6042
6043                while (actions.remove(handlerAction)) {
6044                    // Keep going
6045                }
6046            }
6047        }
6048
6049        void executeActions(Handler handler) {
6050            synchronized (mActions) {
6051                final ArrayList<HandlerAction> actions = mActions;
6052                final int count = actions.size();
6053
6054                for (int i = 0; i < count; i++) {
6055                    final HandlerAction handlerAction = actions.get(i);
6056                    handler.postDelayed(handlerAction.action, handlerAction.delay);
6057                }
6058
6059                actions.clear();
6060            }
6061        }
6062
6063        private static class HandlerAction {
6064            Runnable action;
6065            long delay;
6066
6067            @Override
6068            public boolean equals(Object o) {
6069                if (this == o) return true;
6070                if (o == null || getClass() != o.getClass()) return false;
6071
6072                HandlerAction that = (HandlerAction) o;
6073                return !(action != null ? !action.equals(that.action) : that.action != null);
6074
6075            }
6076
6077            @Override
6078            public int hashCode() {
6079                int result = action != null ? action.hashCode() : 0;
6080                result = 31 * result + (int) (delay ^ (delay >>> 32));
6081                return result;
6082            }
6083        }
6084    }
6085
6086    /**
6087     * Class for managing the accessibility interaction connection
6088     * based on the global accessibility state.
6089     */
6090    final class AccessibilityInteractionConnectionManager
6091            implements AccessibilityStateChangeListener {
6092        public void onAccessibilityStateChanged(boolean enabled) {
6093            if (enabled) {
6094                ensureConnection();
6095                if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6096                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
6097                    View focusedView = mView.findFocus();
6098                    if (focusedView != null && focusedView != mView) {
6099                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6100                    }
6101                }
6102            } else {
6103                ensureNoConnection();
6104                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
6105            }
6106        }
6107
6108        public void ensureConnection() {
6109            if (mAttachInfo != null) {
6110                final boolean registered =
6111                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
6112                if (!registered) {
6113                    mAttachInfo.mAccessibilityWindowId =
6114                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
6115                                new AccessibilityInteractionConnection(ViewRootImpl.this));
6116                }
6117            }
6118        }
6119
6120        public void ensureNoConnection() {
6121            final boolean registered =
6122                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
6123            if (registered) {
6124                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED;
6125                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
6126            }
6127        }
6128    }
6129
6130    /**
6131     * This class is an interface this ViewAncestor provides to the
6132     * AccessibilityManagerService to the latter can interact with
6133     * the view hierarchy in this ViewAncestor.
6134     */
6135    static final class AccessibilityInteractionConnection
6136            extends IAccessibilityInteractionConnection.Stub {
6137        private final WeakReference<ViewRootImpl> mViewRootImpl;
6138
6139        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
6140            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
6141        }
6142
6143        @Override
6144        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
6145                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6146                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6147            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6148            if (viewRootImpl != null && viewRootImpl.mView != null) {
6149                viewRootImpl.getAccessibilityInteractionController()
6150                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
6151                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
6152                            spec);
6153            } else {
6154                // We cannot make the call and notify the caller so it does not wait.
6155                try {
6156                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6157                } catch (RemoteException re) {
6158                    /* best effort - ignore */
6159                }
6160            }
6161        }
6162
6163        @Override
6164        public void performAccessibilityAction(long accessibilityNodeId, int action,
6165                Bundle arguments, int interactionId,
6166                IAccessibilityInteractionConnectionCallback callback, int flags,
6167                int interogatingPid, long interrogatingTid) {
6168            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6169            if (viewRootImpl != null && viewRootImpl.mView != null) {
6170                viewRootImpl.getAccessibilityInteractionController()
6171                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
6172                            interactionId, callback, flags, interogatingPid, interrogatingTid);
6173            } else {
6174                // We cannot make the call and notify the caller so it does not wait.
6175                try {
6176                    callback.setPerformAccessibilityActionResult(false, interactionId);
6177                } catch (RemoteException re) {
6178                    /* best effort - ignore */
6179                }
6180            }
6181        }
6182
6183        @Override
6184        public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
6185                String viewId, int interactionId,
6186                IAccessibilityInteractionConnectionCallback callback, int flags,
6187                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6188            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6189            if (viewRootImpl != null && viewRootImpl.mView != null) {
6190                viewRootImpl.getAccessibilityInteractionController()
6191                    .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
6192                            viewId, interactionId, callback, flags, interrogatingPid,
6193                            interrogatingTid, spec);
6194            } else {
6195                // We cannot make the call and notify the caller so it does not wait.
6196                try {
6197                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6198                } catch (RemoteException re) {
6199                    /* best effort - ignore */
6200                }
6201            }
6202        }
6203
6204        @Override
6205        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
6206                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6207                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6208            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6209            if (viewRootImpl != null && viewRootImpl.mView != null) {
6210                viewRootImpl.getAccessibilityInteractionController()
6211                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
6212                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
6213                            spec);
6214            } else {
6215                // We cannot make the call and notify the caller so it does not wait.
6216                try {
6217                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6218                } catch (RemoteException re) {
6219                    /* best effort - ignore */
6220                }
6221            }
6222        }
6223
6224        @Override
6225        public void findFocus(long accessibilityNodeId, int focusType, int interactionId,
6226                IAccessibilityInteractionConnectionCallback callback, int flags,
6227                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6228            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6229            if (viewRootImpl != null && viewRootImpl.mView != null) {
6230                viewRootImpl.getAccessibilityInteractionController()
6231                    .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback,
6232                            flags, interrogatingPid, interrogatingTid, spec);
6233            } else {
6234                // We cannot make the call and notify the caller so it does not wait.
6235                try {
6236                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6237                } catch (RemoteException re) {
6238                    /* best effort - ignore */
6239                }
6240            }
6241        }
6242
6243        @Override
6244        public void focusSearch(long accessibilityNodeId, int direction, int interactionId,
6245                IAccessibilityInteractionConnectionCallback callback, int flags,
6246                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6247            ViewRootImpl viewRootImpl = mViewRootImpl.get();
6248            if (viewRootImpl != null && viewRootImpl.mView != null) {
6249                viewRootImpl.getAccessibilityInteractionController()
6250                    .focusSearchClientThread(accessibilityNodeId, direction, interactionId,
6251                            callback, flags, interrogatingPid, interrogatingTid, spec);
6252            } else {
6253                // We cannot make the call and notify the caller so it does not wait.
6254                try {
6255                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6256                } catch (RemoteException re) {
6257                    /* best effort - ignore */
6258                }
6259            }
6260        }
6261    }
6262
6263    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
6264        public View mSource;
6265
6266        public void run() {
6267            if (mSource != null) {
6268                mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
6269                mSource.resetAccessibilityStateChanged();
6270                mSource = null;
6271            }
6272        }
6273    }
6274}
6275