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