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