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