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