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