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