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