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