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