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