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