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