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