ViewRootImpl.java revision cf8a3b82241a320f568f8448184df6da5bbcf152
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        if (!AccessibilityManager.getInstance(mView.mContext).isEnabled()) {
2320            return;
2321        }
2322        if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) {
2323            return;
2324        }
2325        Drawable drawable = getAccessibilityFocusedDrawable();
2326        if (drawable == null) {
2327            return;
2328        }
2329        AccessibilityNodeProvider provider =
2330            mAccessibilityFocusedHost.getAccessibilityNodeProvider();
2331        Rect bounds = mView.mAttachInfo.mTmpInvalRect;
2332        if (provider == null) {
2333            mAccessibilityFocusedHost.getDrawingRect(bounds);
2334            if (mView instanceof ViewGroup) {
2335                ViewGroup viewGroup = (ViewGroup) mView;
2336                viewGroup.offsetDescendantRectToMyCoords(mAccessibilityFocusedHost, bounds);
2337            }
2338        } else {
2339            if (mAccessibilityFocusedVirtualView == null) {
2340                mAccessibilityFocusedVirtualView = provider.findAccessibilitiyFocus(View.NO_ID);
2341            }
2342            mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2343            bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
2344        }
2345        drawable.setBounds(bounds);
2346        drawable.draw(canvas);
2347    }
2348
2349    private Drawable getAccessibilityFocusedDrawable() {
2350        if (mAttachInfo != null) {
2351            // Lazily load the accessibility focus drawable.
2352            if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2353                TypedValue value = new TypedValue();
2354                final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2355                        R.attr.accessibilityFocusedDrawable, value, true);
2356                if (resolved) {
2357                    mAttachInfo.mAccessibilityFocusDrawable =
2358                        mView.mContext.getResources().getDrawable(value.resourceId);
2359                }
2360            }
2361            return mAttachInfo.mAccessibilityFocusDrawable;
2362        }
2363        return null;
2364    }
2365
2366    void invalidateDisplayLists() {
2367        final ArrayList<DisplayList> displayLists = mDisplayLists;
2368        final int count = displayLists.size();
2369
2370        for (int i = 0; i < count; i++) {
2371            displayLists.get(i).invalidate();
2372        }
2373
2374        displayLists.clear();
2375    }
2376
2377    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2378        final View.AttachInfo attachInfo = mAttachInfo;
2379        final Rect ci = attachInfo.mContentInsets;
2380        final Rect vi = attachInfo.mVisibleInsets;
2381        int scrollY = 0;
2382        boolean handled = false;
2383
2384        if (vi.left > ci.left || vi.top > ci.top
2385                || vi.right > ci.right || vi.bottom > ci.bottom) {
2386            // We'll assume that we aren't going to change the scroll
2387            // offset, since we want to avoid that unless it is actually
2388            // going to make the focus visible...  otherwise we scroll
2389            // all over the place.
2390            scrollY = mScrollY;
2391            // We can be called for two different situations: during a draw,
2392            // to update the scroll position if the focus has changed (in which
2393            // case 'rectangle' is null), or in response to a
2394            // requestChildRectangleOnScreen() call (in which case 'rectangle'
2395            // is non-null and we just want to scroll to whatever that
2396            // rectangle is).
2397            View focus = mRealFocusedView;
2398
2399            // When in touch mode, focus points to the previously focused view,
2400            // which may have been removed from the view hierarchy. The following
2401            // line checks whether the view is still in our hierarchy.
2402            if (focus == null || focus.mAttachInfo != mAttachInfo) {
2403                mRealFocusedView = null;
2404                return false;
2405            }
2406
2407            if (focus != mLastScrolledFocus) {
2408                // If the focus has changed, then ignore any requests to scroll
2409                // to a rectangle; first we want to make sure the entire focus
2410                // view is visible.
2411                rectangle = null;
2412            }
2413            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2414                    + " rectangle=" + rectangle + " ci=" + ci
2415                    + " vi=" + vi);
2416            if (focus == mLastScrolledFocus && !mScrollMayChange
2417                    && rectangle == null) {
2418                // Optimization: if the focus hasn't changed since last
2419                // time, and no layout has happened, then just leave things
2420                // as they are.
2421                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2422                        + mScrollY + " vi=" + vi.toShortString());
2423            } else if (focus != null) {
2424                // We need to determine if the currently focused view is
2425                // within the visible part of the window and, if not, apply
2426                // a pan so it can be seen.
2427                mLastScrolledFocus = focus;
2428                mScrollMayChange = false;
2429                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2430                // Try to find the rectangle from the focus view.
2431                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2432                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2433                            + mView.getWidth() + " h=" + mView.getHeight()
2434                            + " ci=" + ci.toShortString()
2435                            + " vi=" + vi.toShortString());
2436                    if (rectangle == null) {
2437                        focus.getFocusedRect(mTempRect);
2438                        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2439                                + ": focusRect=" + mTempRect.toShortString());
2440                        if (mView instanceof ViewGroup) {
2441                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2442                                    focus, mTempRect);
2443                        }
2444                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2445                                "Focus in window: focusRect="
2446                                + mTempRect.toShortString()
2447                                + " visRect=" + mVisRect.toShortString());
2448                    } else {
2449                        mTempRect.set(rectangle);
2450                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2451                                "Request scroll to rect: "
2452                                + mTempRect.toShortString()
2453                                + " visRect=" + mVisRect.toShortString());
2454                    }
2455                    if (mTempRect.intersect(mVisRect)) {
2456                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2457                                "Focus window visible rect: "
2458                                + mTempRect.toShortString());
2459                        if (mTempRect.height() >
2460                                (mView.getHeight()-vi.top-vi.bottom)) {
2461                            // If the focus simply is not going to fit, then
2462                            // best is probably just to leave things as-is.
2463                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2464                                    "Too tall; leaving scrollY=" + scrollY);
2465                        } else if ((mTempRect.top-scrollY) < vi.top) {
2466                            scrollY -= vi.top - (mTempRect.top-scrollY);
2467                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2468                                    "Top covered; scrollY=" + scrollY);
2469                        } else if ((mTempRect.bottom-scrollY)
2470                                > (mView.getHeight()-vi.bottom)) {
2471                            scrollY += (mTempRect.bottom-scrollY)
2472                                    - (mView.getHeight()-vi.bottom);
2473                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2474                                    "Bottom covered; scrollY=" + scrollY);
2475                        }
2476                        handled = true;
2477                    }
2478                }
2479            }
2480        }
2481
2482        if (scrollY != mScrollY) {
2483            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2484                    + mScrollY + " , new=" + scrollY);
2485            if (!immediate && mResizeBuffer == null) {
2486                if (mScroller == null) {
2487                    mScroller = new Scroller(mView.getContext());
2488                }
2489                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2490            } else if (mScroller != null) {
2491                mScroller.abortAnimation();
2492            }
2493            mScrollY = scrollY;
2494        }
2495
2496        return handled;
2497    }
2498
2499    void setAccessibilityFocusedHost(View host) {
2500        if (mAccessibilityFocusedHost != null && mAccessibilityFocusedVirtualView == null) {
2501            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2502        }
2503        mAccessibilityFocusedHost = host;
2504        mAccessibilityFocusedVirtualView = null;
2505    }
2506
2507    public void requestChildFocus(View child, View focused) {
2508        checkThread();
2509
2510        if (DEBUG_INPUT_RESIZE) {
2511            Log.v(TAG, "Request child focus: focus now " + focused);
2512        }
2513
2514        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused);
2515        scheduleTraversals();
2516
2517        mFocusedView = mRealFocusedView = focused;
2518    }
2519
2520    public void clearChildFocus(View child) {
2521        checkThread();
2522
2523        if (DEBUG_INPUT_RESIZE) {
2524            Log.v(TAG, "Clearing child focus");
2525        }
2526
2527        mOldFocusedView = mFocusedView;
2528
2529        // Invoke the listener only if there is no view to take focus
2530        if (focusSearch(null, View.FOCUS_FORWARD) == null) {
2531            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null);
2532        }
2533
2534        mFocusedView = mRealFocusedView = null;
2535    }
2536
2537    @Override
2538    public ViewParent getParentForAccessibility() {
2539        return null;
2540    }
2541
2542    public void focusableViewAvailable(View v) {
2543        checkThread();
2544        if (mView != null) {
2545            if (!mView.hasFocus()) {
2546                v.requestFocus();
2547            } else {
2548                // the one case where will transfer focus away from the current one
2549                // is if the current view is a view group that prefers to give focus
2550                // to its children first AND the view is a descendant of it.
2551                mFocusedView = mView.findFocus();
2552                boolean descendantsHaveDibsOnFocus =
2553                        (mFocusedView instanceof ViewGroup) &&
2554                            (((ViewGroup) mFocusedView).getDescendantFocusability() ==
2555                                    ViewGroup.FOCUS_AFTER_DESCENDANTS);
2556                if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
2557                    // If a view gets the focus, the listener will be invoked from requestChildFocus()
2558                    v.requestFocus();
2559                }
2560            }
2561        }
2562    }
2563
2564    public void recomputeViewAttributes(View child) {
2565        checkThread();
2566        if (mView == child) {
2567            mAttachInfo.mRecomputeGlobalAttributes = true;
2568            if (!mWillDrawSoon) {
2569                scheduleTraversals();
2570            }
2571        }
2572    }
2573
2574    void dispatchDetachedFromWindow() {
2575        if (mView != null && mView.mAttachInfo != null) {
2576            if (mAttachInfo.mHardwareRenderer != null &&
2577                    mAttachInfo.mHardwareRenderer.isEnabled()) {
2578                mAttachInfo.mHardwareRenderer.validate();
2579            }
2580            mView.dispatchDetachedFromWindow();
2581        }
2582
2583        mAccessibilityInteractionConnectionManager.ensureNoConnection();
2584        mAccessibilityManager.removeAccessibilityStateChangeListener(
2585                mAccessibilityInteractionConnectionManager);
2586        removeSendWindowContentChangedCallback();
2587
2588        destroyHardwareRenderer();
2589
2590        mView = null;
2591        mAttachInfo.mRootView = null;
2592        mAttachInfo.mSurface = null;
2593
2594        mSurface.release();
2595
2596        if (mInputQueueCallback != null && mInputQueue != null) {
2597            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2598            mInputQueueCallback = null;
2599            mInputQueue = null;
2600        } else if (mInputEventReceiver != null) {
2601            mInputEventReceiver.dispose();
2602            mInputEventReceiver = null;
2603        }
2604        try {
2605            sWindowSession.remove(mWindow);
2606        } catch (RemoteException e) {
2607        }
2608
2609        // Dispose the input channel after removing the window so the Window Manager
2610        // doesn't interpret the input channel being closed as an abnormal termination.
2611        if (mInputChannel != null) {
2612            mInputChannel.dispose();
2613            mInputChannel = null;
2614        }
2615
2616        unscheduleTraversals();
2617    }
2618
2619    void updateConfiguration(Configuration config, boolean force) {
2620        if (DEBUG_CONFIGURATION) Log.v(TAG,
2621                "Applying new config to window "
2622                + mWindowAttributes.getTitle()
2623                + ": " + config);
2624
2625        CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2626        if (ci != null) {
2627            config = new Configuration(config);
2628            ci.applyToConfiguration(config);
2629        }
2630
2631        synchronized (sConfigCallbacks) {
2632            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2633                sConfigCallbacks.get(i).onConfigurationChanged(config);
2634            }
2635        }
2636        if (mView != null) {
2637            // At this point the resources have been updated to
2638            // have the most recent config, whatever that is.  Use
2639            // the on in them which may be newer.
2640            config = mView.getResources().getConfiguration();
2641            if (force || mLastConfiguration.diff(config) != 0) {
2642                mLastConfiguration.setTo(config);
2643                mView.dispatchConfigurationChanged(config);
2644            }
2645        }
2646    }
2647
2648    /**
2649     * Return true if child is an ancestor of parent, (or equal to the parent).
2650     */
2651    static boolean isViewDescendantOf(View child, View parent) {
2652        if (child == parent) {
2653            return true;
2654        }
2655
2656        final ViewParent theParent = child.getParent();
2657        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2658    }
2659
2660    private static void forceLayout(View view) {
2661        view.forceLayout();
2662        if (view instanceof ViewGroup) {
2663            ViewGroup group = (ViewGroup) view;
2664            final int count = group.getChildCount();
2665            for (int i = 0; i < count; i++) {
2666                forceLayout(group.getChildAt(i));
2667            }
2668        }
2669    }
2670
2671    private final static int MSG_INVALIDATE = 1;
2672    private final static int MSG_INVALIDATE_RECT = 2;
2673    private final static int MSG_DIE = 3;
2674    private final static int MSG_RESIZED = 4;
2675    private final static int MSG_RESIZED_REPORT = 5;
2676    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
2677    private final static int MSG_DISPATCH_KEY = 7;
2678    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
2679    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
2680    private final static int MSG_IME_FINISHED_EVENT = 10;
2681    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
2682    private final static int MSG_FINISH_INPUT_CONNECTION = 12;
2683    private final static int MSG_CHECK_FOCUS = 13;
2684    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
2685    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
2686    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
2687    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
2688    private final static int MSG_UPDATE_CONFIGURATION = 18;
2689    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
2690    private final static int MSG_DISPATCH_SCREEN_STATE = 20;
2691    private final static int MSG_INVALIDATE_DISPLAY_LIST = 21;
2692    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 22;
2693    private final static int MSG_DISPATCH_DONE_ANIMATING = 23;
2694
2695    final class ViewRootHandler extends Handler {
2696        @Override
2697        public String getMessageName(Message message) {
2698            switch (message.what) {
2699                case MSG_INVALIDATE:
2700                    return "MSG_INVALIDATE";
2701                case MSG_INVALIDATE_RECT:
2702                    return "MSG_INVALIDATE_RECT";
2703                case MSG_DIE:
2704                    return "MSG_DIE";
2705                case MSG_RESIZED:
2706                    return "MSG_RESIZED";
2707                case MSG_RESIZED_REPORT:
2708                    return "MSG_RESIZED_REPORT";
2709                case MSG_WINDOW_FOCUS_CHANGED:
2710                    return "MSG_WINDOW_FOCUS_CHANGED";
2711                case MSG_DISPATCH_KEY:
2712                    return "MSG_DISPATCH_KEY";
2713                case MSG_DISPATCH_APP_VISIBILITY:
2714                    return "MSG_DISPATCH_APP_VISIBILITY";
2715                case MSG_DISPATCH_GET_NEW_SURFACE:
2716                    return "MSG_DISPATCH_GET_NEW_SURFACE";
2717                case MSG_IME_FINISHED_EVENT:
2718                    return "MSG_IME_FINISHED_EVENT";
2719                case MSG_DISPATCH_KEY_FROM_IME:
2720                    return "MSG_DISPATCH_KEY_FROM_IME";
2721                case MSG_FINISH_INPUT_CONNECTION:
2722                    return "MSG_FINISH_INPUT_CONNECTION";
2723                case MSG_CHECK_FOCUS:
2724                    return "MSG_CHECK_FOCUS";
2725                case MSG_CLOSE_SYSTEM_DIALOGS:
2726                    return "MSG_CLOSE_SYSTEM_DIALOGS";
2727                case MSG_DISPATCH_DRAG_EVENT:
2728                    return "MSG_DISPATCH_DRAG_EVENT";
2729                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
2730                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
2731                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
2732                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
2733                case MSG_UPDATE_CONFIGURATION:
2734                    return "MSG_UPDATE_CONFIGURATION";
2735                case MSG_PROCESS_INPUT_EVENTS:
2736                    return "MSG_PROCESS_INPUT_EVENTS";
2737                case MSG_DISPATCH_SCREEN_STATE:
2738                    return "MSG_DISPATCH_SCREEN_STATE";
2739                case MSG_INVALIDATE_DISPLAY_LIST:
2740                    return "MSG_INVALIDATE_DISPLAY_LIST";
2741                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
2742                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
2743                case MSG_DISPATCH_DONE_ANIMATING:
2744                    return "MSG_DISPATCH_DONE_ANIMATING";
2745            }
2746            return super.getMessageName(message);
2747        }
2748
2749        @Override
2750        public void handleMessage(Message msg) {
2751            switch (msg.what) {
2752            case MSG_INVALIDATE:
2753                ((View) msg.obj).invalidate();
2754                break;
2755            case MSG_INVALIDATE_RECT:
2756                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2757                info.target.invalidate(info.left, info.top, info.right, info.bottom);
2758                info.release();
2759                break;
2760            case MSG_IME_FINISHED_EVENT:
2761                handleImeFinishedEvent(msg.arg1, msg.arg2 != 0);
2762                break;
2763            case MSG_PROCESS_INPUT_EVENTS:
2764                mProcessInputEventsScheduled = false;
2765                doProcessInputEvents();
2766                break;
2767            case MSG_DISPATCH_APP_VISIBILITY:
2768                handleAppVisibility(msg.arg1 != 0);
2769                break;
2770            case MSG_DISPATCH_GET_NEW_SURFACE:
2771                handleGetNewSurface();
2772                break;
2773            case MSG_RESIZED:
2774                ResizedInfo ri = (ResizedInfo)msg.obj;
2775
2776                if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
2777                        && mPendingContentInsets.equals(ri.coveredInsets)
2778                        && mPendingVisibleInsets.equals(ri.visibleInsets)
2779                        && ((ResizedInfo)msg.obj).newConfig == null) {
2780                    break;
2781                }
2782                // fall through...
2783            case MSG_RESIZED_REPORT:
2784                if (mAdded) {
2785                    Configuration config = ((ResizedInfo)msg.obj).newConfig;
2786                    if (config != null) {
2787                        updateConfiguration(config, false);
2788                    }
2789                    mWinFrame.left = 0;
2790                    mWinFrame.right = msg.arg1;
2791                    mWinFrame.top = 0;
2792                    mWinFrame.bottom = msg.arg2;
2793                    mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
2794                    mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
2795                    if (msg.what == MSG_RESIZED_REPORT) {
2796                        mReportNextDraw = true;
2797                    }
2798
2799                    if (mView != null) {
2800                        forceLayout(mView);
2801                    }
2802                    requestLayout();
2803                }
2804                break;
2805            case MSG_WINDOW_FOCUS_CHANGED: {
2806                if (mAdded) {
2807                    boolean hasWindowFocus = msg.arg1 != 0;
2808                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
2809
2810                    profileRendering(hasWindowFocus);
2811
2812                    if (hasWindowFocus) {
2813                        boolean inTouchMode = msg.arg2 != 0;
2814                        ensureTouchModeLocally(inTouchMode);
2815
2816                        if (mAttachInfo.mHardwareRenderer != null &&
2817                                mSurface != null && mSurface.isValid()) {
2818                            mFullRedrawNeeded = true;
2819                            try {
2820                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2821                                        mHolder);
2822                            } catch (Surface.OutOfResourcesException e) {
2823                                Log.e(TAG, "OutOfResourcesException locking surface", e);
2824                                try {
2825                                    if (!sWindowSession.outOfMemory(mWindow)) {
2826                                        Slog.w(TAG, "No processes killed for memory; killing self");
2827                                        Process.killProcess(Process.myPid());
2828                                    }
2829                                } catch (RemoteException ex) {
2830                                }
2831                                // Retry in a bit.
2832                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
2833                                return;
2834                            }
2835                        }
2836                    }
2837
2838                    mLastWasImTarget = WindowManager.LayoutParams
2839                            .mayUseInputMethod(mWindowAttributes.flags);
2840
2841                    InputMethodManager imm = InputMethodManager.peekInstance();
2842                    if (mView != null) {
2843                        if (hasWindowFocus && imm != null && mLastWasImTarget) {
2844                            imm.startGettingWindowFocus(mView);
2845                        }
2846                        mAttachInfo.mKeyDispatchState.reset();
2847                        mView.dispatchWindowFocusChanged(hasWindowFocus);
2848                    }
2849
2850                    // Note: must be done after the focus change callbacks,
2851                    // so all of the view state is set up correctly.
2852                    if (hasWindowFocus) {
2853                        if (imm != null && mLastWasImTarget) {
2854                            imm.onWindowFocus(mView, mView.findFocus(),
2855                                    mWindowAttributes.softInputMode,
2856                                    !mHasHadWindowFocus, mWindowAttributes.flags);
2857                        }
2858                        // Clear the forward bit.  We can just do this directly, since
2859                        // the window manager doesn't care about it.
2860                        mWindowAttributes.softInputMode &=
2861                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2862                        ((WindowManager.LayoutParams)mView.getLayoutParams())
2863                                .softInputMode &=
2864                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2865                        mHasHadWindowFocus = true;
2866                    }
2867
2868                    if (mView != null && mAccessibilityManager.isEnabled()) {
2869                        if (hasWindowFocus) {
2870                            mView.sendAccessibilityEvent(
2871                                    AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2872                            // Give accessibility focus to the view that has input
2873                            // focus if such, otherwise to the first one.
2874                            if (mView instanceof ViewGroup) {
2875                                ViewGroup viewGroup = (ViewGroup) mView;
2876                                View focused = viewGroup.findFocus();
2877                                if (focused != null) {
2878                                    focused.requestAccessibilityFocus();
2879                                }
2880                            }
2881                            // There is no accessibility focus, despite our effort
2882                            // above, now just give it to the first view.
2883                            if (mAccessibilityFocusedHost == null) {
2884                                mView.requestAccessibilityFocus();
2885                            }
2886                        } else {
2887                            // Clear accessibility focus when the window loses input focus.
2888                            setAccessibilityFocusedHost(null);
2889                        }
2890                    }
2891                }
2892            } break;
2893            case MSG_DIE:
2894                doDie();
2895                break;
2896            case MSG_DISPATCH_KEY: {
2897                KeyEvent event = (KeyEvent)msg.obj;
2898                enqueueInputEvent(event, null, 0, true);
2899            } break;
2900            case MSG_DISPATCH_KEY_FROM_IME: {
2901                if (LOCAL_LOGV) Log.v(
2902                    TAG, "Dispatching key "
2903                    + msg.obj + " from IME to " + mView);
2904                KeyEvent event = (KeyEvent)msg.obj;
2905                if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2906                    // The IME is trying to say this event is from the
2907                    // system!  Bad bad bad!
2908                    //noinspection UnusedAssignment
2909                    event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
2910                }
2911                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
2912            } break;
2913            case MSG_FINISH_INPUT_CONNECTION: {
2914                InputMethodManager imm = InputMethodManager.peekInstance();
2915                if (imm != null) {
2916                    imm.reportFinishInputConnection((InputConnection)msg.obj);
2917                }
2918            } break;
2919            case MSG_CHECK_FOCUS: {
2920                InputMethodManager imm = InputMethodManager.peekInstance();
2921                if (imm != null) {
2922                    imm.checkFocus();
2923                }
2924            } break;
2925            case MSG_CLOSE_SYSTEM_DIALOGS: {
2926                if (mView != null) {
2927                    mView.onCloseSystemDialogs((String)msg.obj);
2928                }
2929            } break;
2930            case MSG_DISPATCH_DRAG_EVENT:
2931            case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
2932                DragEvent event = (DragEvent)msg.obj;
2933                event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
2934                handleDragEvent(event);
2935            } break;
2936            case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
2937                handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj);
2938            } break;
2939            case MSG_UPDATE_CONFIGURATION: {
2940                Configuration config = (Configuration)msg.obj;
2941                if (config.isOtherSeqNewer(mLastConfiguration)) {
2942                    config = mLastConfiguration;
2943                }
2944                updateConfiguration(config, false);
2945            } break;
2946            case MSG_DISPATCH_SCREEN_STATE: {
2947                if (mView != null) {
2948                    handleScreenStateChange(msg.arg1 == 1);
2949                }
2950            } break;
2951            case MSG_INVALIDATE_DISPLAY_LIST: {
2952                invalidateDisplayLists();
2953            } break;
2954            case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
2955                setAccessibilityFocusedHost(null);
2956            } break;
2957            case MSG_DISPATCH_DONE_ANIMATING: {
2958                handleDispatchDoneAnimating();
2959            } break;
2960            }
2961        }
2962    }
2963
2964    final ViewRootHandler mHandler = new ViewRootHandler();
2965
2966    /**
2967     * Something in the current window tells us we need to change the touch mode.  For
2968     * example, we are not in touch mode, and the user touches the screen.
2969     *
2970     * If the touch mode has changed, tell the window manager, and handle it locally.
2971     *
2972     * @param inTouchMode Whether we want to be in touch mode.
2973     * @return True if the touch mode changed and focus changed was changed as a result
2974     */
2975    boolean ensureTouchMode(boolean inTouchMode) {
2976        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2977                + "touch mode is " + mAttachInfo.mInTouchMode);
2978        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2979
2980        // tell the window manager
2981        try {
2982            sWindowSession.setInTouchMode(inTouchMode);
2983        } catch (RemoteException e) {
2984            throw new RuntimeException(e);
2985        }
2986
2987        // handle the change
2988        return ensureTouchModeLocally(inTouchMode);
2989    }
2990
2991    /**
2992     * Ensure that the touch mode for this window is set, and if it is changing,
2993     * take the appropriate action.
2994     * @param inTouchMode Whether we want to be in touch mode.
2995     * @return True if the touch mode changed and focus changed was changed as a result
2996     */
2997    private boolean ensureTouchModeLocally(boolean inTouchMode) {
2998        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2999                + "touch mode is " + mAttachInfo.mInTouchMode);
3000
3001        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3002
3003        mAttachInfo.mInTouchMode = inTouchMode;
3004        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3005
3006        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3007    }
3008
3009    private boolean enterTouchMode() {
3010        if (mView != null) {
3011            if (mView.hasFocus()) {
3012                // note: not relying on mFocusedView here because this could
3013                // be when the window is first being added, and mFocused isn't
3014                // set yet.
3015                final View focused = mView.findFocus();
3016                if (focused != null && !focused.isFocusableInTouchMode()) {
3017
3018                    final ViewGroup ancestorToTakeFocus =
3019                            findAncestorToTakeFocusInTouchMode(focused);
3020                    if (ancestorToTakeFocus != null) {
3021                        // there is an ancestor that wants focus after its descendants that
3022                        // is focusable in touch mode.. give it focus
3023                        return ancestorToTakeFocus.requestFocus();
3024                    } else {
3025                        // nothing appropriate to have focus in touch mode, clear it out
3026                        mView.unFocus();
3027                        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
3028                        mFocusedView = null;
3029                        mOldFocusedView = null;
3030                        return true;
3031                    }
3032                }
3033            }
3034        }
3035        return false;
3036    }
3037
3038    /**
3039     * Find an ancestor of focused that wants focus after its descendants and is
3040     * focusable in touch mode.
3041     * @param focused The currently focused view.
3042     * @return An appropriate view, or null if no such view exists.
3043     */
3044    private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3045        ViewParent parent = focused.getParent();
3046        while (parent instanceof ViewGroup) {
3047            final ViewGroup vgParent = (ViewGroup) parent;
3048            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3049                    && vgParent.isFocusableInTouchMode()) {
3050                return vgParent;
3051            }
3052            if (vgParent.isRootNamespace()) {
3053                return null;
3054            } else {
3055                parent = vgParent.getParent();
3056            }
3057        }
3058        return null;
3059    }
3060
3061    private boolean leaveTouchMode() {
3062        if (mView != null) {
3063            if (mView.hasFocus()) {
3064                // i learned the hard way to not trust mFocusedView :)
3065                mFocusedView = mView.findFocus();
3066                if (!(mFocusedView instanceof ViewGroup)) {
3067                    // some view has focus, let it keep it
3068                    return false;
3069                } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
3070                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3071                    // some view group has focus, and doesn't prefer its children
3072                    // over itself for focus, so let them keep it.
3073                    return false;
3074                }
3075            }
3076
3077            // find the best view to give focus to in this brave new non-touch-mode
3078            // world
3079            final View focused = focusSearch(null, View.FOCUS_DOWN);
3080            if (focused != null) {
3081                return focused.requestFocus(View.FOCUS_DOWN);
3082            }
3083        }
3084        return false;
3085    }
3086
3087    private void deliverInputEvent(QueuedInputEvent q) {
3088        if (ViewDebug.DEBUG_LATENCY) {
3089            q.mDeliverTimeNanos = System.nanoTime();
3090        }
3091
3092        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
3093        try {
3094            if (q.mEvent instanceof KeyEvent) {
3095                deliverKeyEvent(q);
3096            } else {
3097                final int source = q.mEvent.getSource();
3098                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3099                    deliverPointerEvent(q);
3100                } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3101                    deliverTrackballEvent(q);
3102                } else {
3103                    deliverGenericMotionEvent(q);
3104                }
3105            }
3106        } finally {
3107            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3108        }
3109    }
3110
3111    private void deliverPointerEvent(QueuedInputEvent q) {
3112        final MotionEvent event = (MotionEvent)q.mEvent;
3113        final boolean isTouchEvent = event.isTouchEvent();
3114        if (mInputEventConsistencyVerifier != null) {
3115            if (isTouchEvent) {
3116                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
3117            } else {
3118                mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3119            }
3120        }
3121
3122        // If there is no view, then the event will not be handled.
3123        if (mView == null || !mAdded) {
3124            finishInputEvent(q, false);
3125            return;
3126        }
3127
3128        // Translate the pointer event for compatibility, if needed.
3129        if (mTranslator != null) {
3130            mTranslator.translateEventInScreenToAppWindow(event);
3131        }
3132
3133        // Enter touch mode on down or scroll.
3134        final int action = event.getAction();
3135        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3136            ensureTouchMode(true);
3137        }
3138
3139        // Offset the scroll position.
3140        if (mCurScrollY != 0) {
3141            event.offsetLocation(0, mCurScrollY);
3142        }
3143        if (MEASURE_LATENCY) {
3144            lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
3145        }
3146
3147        // Remember the touch position for possible drag-initiation.
3148        if (isTouchEvent) {
3149            mLastTouchPoint.x = event.getRawX();
3150            mLastTouchPoint.y = event.getRawY();
3151        }
3152
3153        // Dispatch touch to view hierarchy.
3154        boolean handled = mView.dispatchPointerEvent(event);
3155        if (MEASURE_LATENCY) {
3156            lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
3157        }
3158        if (handled) {
3159            finishInputEvent(q, true);
3160            return;
3161        }
3162
3163        // Pointer event was unhandled.
3164        finishInputEvent(q, false);
3165    }
3166
3167    private void deliverTrackballEvent(QueuedInputEvent q) {
3168        final MotionEvent event = (MotionEvent)q.mEvent;
3169        if (mInputEventConsistencyVerifier != null) {
3170            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
3171        }
3172
3173        // If there is no view, then the event will not be handled.
3174        if (mView == null || !mAdded) {
3175            finishInputEvent(q, false);
3176            return;
3177        }
3178
3179        // Deliver the trackball event to the view.
3180        if (mView.dispatchTrackballEvent(event)) {
3181            // If we reach this, we delivered a trackball event to mView and
3182            // mView consumed it. Because we will not translate the trackball
3183            // event into a key event, touch mode will not exit, so we exit
3184            // touch mode here.
3185            ensureTouchMode(false);
3186
3187            finishInputEvent(q, true);
3188            mLastTrackballTime = Integer.MIN_VALUE;
3189            return;
3190        }
3191
3192        // Translate the trackball event into DPAD keys and try to deliver those.
3193        final TrackballAxis x = mTrackballAxisX;
3194        final TrackballAxis y = mTrackballAxisY;
3195
3196        long curTime = SystemClock.uptimeMillis();
3197        if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
3198            // It has been too long since the last movement,
3199            // so restart at the beginning.
3200            x.reset(0);
3201            y.reset(0);
3202            mLastTrackballTime = curTime;
3203        }
3204
3205        final int action = event.getAction();
3206        final int metaState = event.getMetaState();
3207        switch (action) {
3208            case MotionEvent.ACTION_DOWN:
3209                x.reset(2);
3210                y.reset(2);
3211                enqueueInputEvent(new KeyEvent(curTime, curTime,
3212                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3213                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3214                        InputDevice.SOURCE_KEYBOARD));
3215                break;
3216            case MotionEvent.ACTION_UP:
3217                x.reset(2);
3218                y.reset(2);
3219                enqueueInputEvent(new KeyEvent(curTime, curTime,
3220                        KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3221                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3222                        InputDevice.SOURCE_KEYBOARD));
3223                break;
3224        }
3225
3226        if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
3227                + x.step + " dir=" + x.dir + " acc=" + x.acceleration
3228                + " move=" + event.getX()
3229                + " / Y=" + y.position + " step="
3230                + y.step + " dir=" + y.dir + " acc=" + y.acceleration
3231                + " move=" + event.getY());
3232        final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
3233        final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
3234
3235        // Generate DPAD events based on the trackball movement.
3236        // We pick the axis that has moved the most as the direction of
3237        // the DPAD.  When we generate DPAD events for one axis, then the
3238        // other axis is reset -- we don't want to perform DPAD jumps due
3239        // to slight movements in the trackball when making major movements
3240        // along the other axis.
3241        int keycode = 0;
3242        int movement = 0;
3243        float accel = 1;
3244        if (xOff > yOff) {
3245            movement = x.generate((2/event.getXPrecision()));
3246            if (movement != 0) {
3247                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
3248                        : KeyEvent.KEYCODE_DPAD_LEFT;
3249                accel = x.acceleration;
3250                y.reset(2);
3251            }
3252        } else if (yOff > 0) {
3253            movement = y.generate((2/event.getYPrecision()));
3254            if (movement != 0) {
3255                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
3256                        : KeyEvent.KEYCODE_DPAD_UP;
3257                accel = y.acceleration;
3258                x.reset(2);
3259            }
3260        }
3261
3262        if (keycode != 0) {
3263            if (movement < 0) movement = -movement;
3264            int accelMovement = (int)(movement * accel);
3265            if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
3266                    + " accelMovement=" + accelMovement
3267                    + " accel=" + accel);
3268            if (accelMovement > movement) {
3269                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3270                        + keycode);
3271                movement--;
3272                int repeatCount = accelMovement - movement;
3273                enqueueInputEvent(new KeyEvent(curTime, curTime,
3274                        KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
3275                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3276                        InputDevice.SOURCE_KEYBOARD));
3277            }
3278            while (movement > 0) {
3279                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3280                        + keycode);
3281                movement--;
3282                curTime = SystemClock.uptimeMillis();
3283                enqueueInputEvent(new KeyEvent(curTime, curTime,
3284                        KeyEvent.ACTION_DOWN, keycode, 0, metaState,
3285                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3286                        InputDevice.SOURCE_KEYBOARD));
3287                enqueueInputEvent(new KeyEvent(curTime, curTime,
3288                        KeyEvent.ACTION_UP, keycode, 0, metaState,
3289                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3290                        InputDevice.SOURCE_KEYBOARD));
3291            }
3292            mLastTrackballTime = curTime;
3293        }
3294
3295        // Unfortunately we can't tell whether the application consumed the keys, so
3296        // we always consider the trackball event handled.
3297        finishInputEvent(q, true);
3298    }
3299
3300    private void deliverGenericMotionEvent(QueuedInputEvent q) {
3301        final MotionEvent event = (MotionEvent)q.mEvent;
3302        if (mInputEventConsistencyVerifier != null) {
3303            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3304        }
3305
3306        final int source = event.getSource();
3307        final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
3308
3309        // If there is no view, then the event will not be handled.
3310        if (mView == null || !mAdded) {
3311            if (isJoystick) {
3312                updateJoystickDirection(event, false);
3313            }
3314            finishInputEvent(q, false);
3315            return;
3316        }
3317
3318        // Deliver the event to the view.
3319        if (mView.dispatchGenericMotionEvent(event)) {
3320            if (isJoystick) {
3321                updateJoystickDirection(event, false);
3322            }
3323            finishInputEvent(q, true);
3324            return;
3325        }
3326
3327        if (isJoystick) {
3328            // Translate the joystick event into DPAD keys and try to deliver those.
3329            updateJoystickDirection(event, true);
3330            finishInputEvent(q, true);
3331        } else {
3332            finishInputEvent(q, false);
3333        }
3334    }
3335
3336    private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
3337        final long time = event.getEventTime();
3338        final int metaState = event.getMetaState();
3339        final int deviceId = event.getDeviceId();
3340        final int source = event.getSource();
3341
3342        int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
3343        if (xDirection == 0) {
3344            xDirection = joystickAxisValueToDirection(event.getX());
3345        }
3346
3347        int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
3348        if (yDirection == 0) {
3349            yDirection = joystickAxisValueToDirection(event.getY());
3350        }
3351
3352        if (xDirection != mLastJoystickXDirection) {
3353            if (mLastJoystickXKeyCode != 0) {
3354                enqueueInputEvent(new KeyEvent(time, time,
3355                        KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
3356                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3357                mLastJoystickXKeyCode = 0;
3358            }
3359
3360            mLastJoystickXDirection = xDirection;
3361
3362            if (xDirection != 0 && synthesizeNewKeys) {
3363                mLastJoystickXKeyCode = xDirection > 0
3364                        ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3365                enqueueInputEvent(new KeyEvent(time, time,
3366                        KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3367                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3368            }
3369        }
3370
3371        if (yDirection != mLastJoystickYDirection) {
3372            if (mLastJoystickYKeyCode != 0) {
3373                enqueueInputEvent(new KeyEvent(time, time,
3374                        KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3375                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3376                mLastJoystickYKeyCode = 0;
3377            }
3378
3379            mLastJoystickYDirection = yDirection;
3380
3381            if (yDirection != 0 && synthesizeNewKeys) {
3382                mLastJoystickYKeyCode = yDirection > 0
3383                        ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3384                enqueueInputEvent(new KeyEvent(time, time,
3385                        KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3386                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3387            }
3388        }
3389    }
3390
3391    private static int joystickAxisValueToDirection(float value) {
3392        if (value >= 0.5f) {
3393            return 1;
3394        } else if (value <= -0.5f) {
3395            return -1;
3396        } else {
3397            return 0;
3398        }
3399    }
3400
3401    /**
3402     * Returns true if the key is used for keyboard navigation.
3403     * @param keyEvent The key event.
3404     * @return True if the key is used for keyboard navigation.
3405     */
3406    private static boolean isNavigationKey(KeyEvent keyEvent) {
3407        switch (keyEvent.getKeyCode()) {
3408        case KeyEvent.KEYCODE_DPAD_LEFT:
3409        case KeyEvent.KEYCODE_DPAD_RIGHT:
3410        case KeyEvent.KEYCODE_DPAD_UP:
3411        case KeyEvent.KEYCODE_DPAD_DOWN:
3412        case KeyEvent.KEYCODE_DPAD_CENTER:
3413        case KeyEvent.KEYCODE_PAGE_UP:
3414        case KeyEvent.KEYCODE_PAGE_DOWN:
3415        case KeyEvent.KEYCODE_MOVE_HOME:
3416        case KeyEvent.KEYCODE_MOVE_END:
3417        case KeyEvent.KEYCODE_TAB:
3418        case KeyEvent.KEYCODE_SPACE:
3419        case KeyEvent.KEYCODE_ENTER:
3420            return true;
3421        }
3422        return false;
3423    }
3424
3425    /**
3426     * Returns true if the key is used for typing.
3427     * @param keyEvent The key event.
3428     * @return True if the key is used for typing.
3429     */
3430    private static boolean isTypingKey(KeyEvent keyEvent) {
3431        return keyEvent.getUnicodeChar() > 0;
3432    }
3433
3434    /**
3435     * See if the key event means we should leave touch mode (and leave touch mode if so).
3436     * @param event The key event.
3437     * @return Whether this key event should be consumed (meaning the act of
3438     *   leaving touch mode alone is considered the event).
3439     */
3440    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3441        // Only relevant in touch mode.
3442        if (!mAttachInfo.mInTouchMode) {
3443            return false;
3444        }
3445
3446        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3447        final int action = event.getAction();
3448        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3449            return false;
3450        }
3451
3452        // Don't leave touch mode if the IME told us not to.
3453        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3454            return false;
3455        }
3456
3457        // If the key can be used for keyboard navigation then leave touch mode
3458        // and select a focused view if needed (in ensureTouchMode).
3459        // When a new focused view is selected, we consume the navigation key because
3460        // navigation doesn't make much sense unless a view already has focus so
3461        // the key's purpose is to set focus.
3462        if (isNavigationKey(event)) {
3463            return ensureTouchMode(false);
3464        }
3465
3466        // If the key can be used for typing then leave touch mode
3467        // and select a focused view if needed (in ensureTouchMode).
3468        // Always allow the view to process the typing key.
3469        if (isTypingKey(event)) {
3470            ensureTouchMode(false);
3471            return false;
3472        }
3473
3474        return false;
3475    }
3476
3477    private void deliverKeyEvent(QueuedInputEvent q) {
3478        final KeyEvent event = (KeyEvent)q.mEvent;
3479        if (mInputEventConsistencyVerifier != null) {
3480            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3481        }
3482
3483        if ((q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3484            // If there is no view, then the event will not be handled.
3485            if (mView == null || !mAdded) {
3486                finishInputEvent(q, false);
3487                return;
3488            }
3489
3490            if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3491
3492            // Perform predispatching before the IME.
3493            if (mView.dispatchKeyEventPreIme(event)) {
3494                finishInputEvent(q, true);
3495                return;
3496            }
3497
3498            // Dispatch to the IME before propagating down the view hierarchy.
3499            // The IME will eventually call back into handleImeFinishedEvent.
3500            if (mLastWasImTarget) {
3501                InputMethodManager imm = InputMethodManager.peekInstance();
3502                if (imm != null) {
3503                    final int seq = event.getSequenceNumber();
3504                    if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3505                            + seq + " event=" + event);
3506                    imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
3507                    return;
3508                }
3509            }
3510        }
3511
3512        // Not dispatching to IME, continue with post IME actions.
3513        deliverKeyEventPostIme(q);
3514    }
3515
3516    void handleImeFinishedEvent(int seq, boolean handled) {
3517        final QueuedInputEvent q = mCurrentInputEvent;
3518        if (q != null && q.mEvent.getSequenceNumber() == seq) {
3519            final KeyEvent event = (KeyEvent)q.mEvent;
3520            if (DEBUG_IMF) {
3521                Log.v(TAG, "IME finished event: seq=" + seq
3522                        + " handled=" + handled + " event=" + event);
3523            }
3524            if (handled) {
3525                finishInputEvent(q, true);
3526            } else {
3527                deliverKeyEventPostIme(q);
3528            }
3529        } else {
3530            if (DEBUG_IMF) {
3531                Log.v(TAG, "IME finished event: seq=" + seq
3532                        + " handled=" + handled + ", event not found!");
3533            }
3534        }
3535    }
3536
3537    private void deliverKeyEventPostIme(QueuedInputEvent q) {
3538        final KeyEvent event = (KeyEvent)q.mEvent;
3539        if (ViewDebug.DEBUG_LATENCY) {
3540            q.mDeliverPostImeTimeNanos = System.nanoTime();
3541        }
3542
3543        // If the view went away, then the event will not be handled.
3544        if (mView == null || !mAdded) {
3545            finishInputEvent(q, false);
3546            return;
3547        }
3548
3549        // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3550        if (checkForLeavingTouchModeAndConsume(event)) {
3551            finishInputEvent(q, true);
3552            return;
3553        }
3554
3555        // Make sure the fallback event policy sees all keys that will be delivered to the
3556        // view hierarchy.
3557        mFallbackEventHandler.preDispatchKeyEvent(event);
3558
3559        // Deliver the key to the view hierarchy.
3560        if (mView.dispatchKeyEvent(event)) {
3561            finishInputEvent(q, true);
3562            return;
3563        }
3564
3565        // If the Control modifier is held, try to interpret the key as a shortcut.
3566        if (event.getAction() == KeyEvent.ACTION_DOWN
3567                && event.isCtrlPressed()
3568                && event.getRepeatCount() == 0
3569                && !KeyEvent.isModifierKey(event.getKeyCode())) {
3570            if (mView.dispatchKeyShortcutEvent(event)) {
3571                finishInputEvent(q, true);
3572                return;
3573            }
3574        }
3575
3576        // Apply the fallback event policy.
3577        if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3578            finishInputEvent(q, true);
3579            return;
3580        }
3581
3582        // Handle automatic focus changes.
3583        if (event.getAction() == KeyEvent.ACTION_DOWN) {
3584            int direction = 0;
3585            switch (event.getKeyCode()) {
3586                case KeyEvent.KEYCODE_DPAD_LEFT:
3587                    if (event.hasNoModifiers()) {
3588                        direction = View.FOCUS_LEFT;
3589                    }
3590                    break;
3591                case KeyEvent.KEYCODE_DPAD_RIGHT:
3592                    if (event.hasNoModifiers()) {
3593                        direction = View.FOCUS_RIGHT;
3594                    }
3595                    break;
3596                case KeyEvent.KEYCODE_DPAD_UP:
3597                    if (event.hasNoModifiers()) {
3598                        direction = View.FOCUS_UP;
3599                    }
3600                    break;
3601                case KeyEvent.KEYCODE_DPAD_DOWN:
3602                    if (event.hasNoModifiers()) {
3603                        direction = View.FOCUS_DOWN;
3604                    }
3605                    break;
3606                case KeyEvent.KEYCODE_TAB:
3607                    if (event.hasNoModifiers()) {
3608                        direction = View.FOCUS_FORWARD;
3609                    } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3610                        direction = View.FOCUS_BACKWARD;
3611                    }
3612                    break;
3613            }
3614            if (direction != 0) {
3615                View focused = mView.findFocus();
3616                if (focused != null) {
3617                    View v = focused.focusSearch(direction);
3618                    if (v != null && v != focused) {
3619                        // do the math the get the interesting rect
3620                        // of previous focused into the coord system of
3621                        // newly focused view
3622                        focused.getFocusedRect(mTempRect);
3623                        if (mView instanceof ViewGroup) {
3624                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3625                                    focused, mTempRect);
3626                            ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3627                                    v, mTempRect);
3628                        }
3629                        if (v.requestFocus(direction, mTempRect)) {
3630                            playSoundEffect(SoundEffectConstants
3631                                    .getContantForFocusDirection(direction));
3632                            finishInputEvent(q, true);
3633                            return;
3634                        }
3635                    }
3636
3637                    // Give the focused view a last chance to handle the dpad key.
3638                    if (mView.dispatchUnhandledMove(focused, direction)) {
3639                        finishInputEvent(q, true);
3640                        return;
3641                    }
3642                }
3643            }
3644        }
3645
3646        // Key was unhandled.
3647        finishInputEvent(q, false);
3648    }
3649
3650    /* drag/drop */
3651    void setLocalDragState(Object obj) {
3652        mLocalDragState = obj;
3653    }
3654
3655    private void handleDragEvent(DragEvent event) {
3656        // From the root, only drag start/end/location are dispatched.  entered/exited
3657        // are determined and dispatched by the viewgroup hierarchy, who then report
3658        // that back here for ultimate reporting back to the framework.
3659        if (mView != null && mAdded) {
3660            final int what = event.mAction;
3661
3662            if (what == DragEvent.ACTION_DRAG_EXITED) {
3663                // A direct EXITED event means that the window manager knows we've just crossed
3664                // a window boundary, so the current drag target within this one must have
3665                // just been exited.  Send it the usual notifications and then we're done
3666                // for now.
3667                mView.dispatchDragEvent(event);
3668            } else {
3669                // Cache the drag description when the operation starts, then fill it in
3670                // on subsequent calls as a convenience
3671                if (what == DragEvent.ACTION_DRAG_STARTED) {
3672                    mCurrentDragView = null;    // Start the current-recipient tracking
3673                    mDragDescription = event.mClipDescription;
3674                } else {
3675                    event.mClipDescription = mDragDescription;
3676                }
3677
3678                // For events with a [screen] location, translate into window coordinates
3679                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3680                    mDragPoint.set(event.mX, event.mY);
3681                    if (mTranslator != null) {
3682                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3683                    }
3684
3685                    if (mCurScrollY != 0) {
3686                        mDragPoint.offset(0, mCurScrollY);
3687                    }
3688
3689                    event.mX = mDragPoint.x;
3690                    event.mY = mDragPoint.y;
3691                }
3692
3693                // Remember who the current drag target is pre-dispatch
3694                final View prevDragView = mCurrentDragView;
3695
3696                // Now dispatch the drag/drop event
3697                boolean result = mView.dispatchDragEvent(event);
3698
3699                // If we changed apparent drag target, tell the OS about it
3700                if (prevDragView != mCurrentDragView) {
3701                    try {
3702                        if (prevDragView != null) {
3703                            sWindowSession.dragRecipientExited(mWindow);
3704                        }
3705                        if (mCurrentDragView != null) {
3706                            sWindowSession.dragRecipientEntered(mWindow);
3707                        }
3708                    } catch (RemoteException e) {
3709                        Slog.e(TAG, "Unable to note drag target change");
3710                    }
3711                }
3712
3713                // Report the drop result when we're done
3714                if (what == DragEvent.ACTION_DROP) {
3715                    mDragDescription = null;
3716                    try {
3717                        Log.i(TAG, "Reporting drop result: " + result);
3718                        sWindowSession.reportDropResult(mWindow, result);
3719                    } catch (RemoteException e) {
3720                        Log.e(TAG, "Unable to report drop result");
3721                    }
3722                }
3723
3724                // When the drag operation ends, release any local state object
3725                // that may have been in use
3726                if (what == DragEvent.ACTION_DRAG_ENDED) {
3727                    setLocalDragState(null);
3728                }
3729            }
3730        }
3731        event.recycle();
3732    }
3733
3734    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
3735        if (mSeq != args.seq) {
3736            // The sequence has changed, so we need to update our value and make
3737            // sure to do a traversal afterward so the window manager is given our
3738            // most recent data.
3739            mSeq = args.seq;
3740            mAttachInfo.mForceReportNewAttributes = true;
3741            scheduleTraversals();
3742        }
3743        if (mView == null) return;
3744        if (args.localChanges != 0) {
3745            if (mAttachInfo != null) {
3746                mAttachInfo.mRecomputeGlobalAttributes = true;
3747            }
3748            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
3749            scheduleTraversals();
3750        }
3751        mView.dispatchSystemUiVisibilityChanged(args.globalVisibility);
3752    }
3753
3754    public void handleDispatchDoneAnimating() {
3755        if (mWindowsAnimating) {
3756            mWindowsAnimating = false;
3757            if (!mDirty.isEmpty() || mIsAnimating)  {
3758                scheduleTraversals();
3759            }
3760        }
3761    }
3762
3763    public void getLastTouchPoint(Point outLocation) {
3764        outLocation.x = (int) mLastTouchPoint.x;
3765        outLocation.y = (int) mLastTouchPoint.y;
3766    }
3767
3768    public void setDragFocus(View newDragTarget) {
3769        if (mCurrentDragView != newDragTarget) {
3770            mCurrentDragView = newDragTarget;
3771        }
3772    }
3773
3774    private AudioManager getAudioManager() {
3775        if (mView == null) {
3776            throw new IllegalStateException("getAudioManager called when there is no mView");
3777        }
3778        if (mAudioManager == null) {
3779            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3780        }
3781        return mAudioManager;
3782    }
3783
3784    public AccessibilityInteractionController getAccessibilityInteractionController() {
3785        if (mView == null) {
3786            throw new IllegalStateException("getAccessibilityInteractionController"
3787                    + " called when there is no mView");
3788        }
3789        if (mAccessibilityInteractionController == null) {
3790            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
3791        }
3792        return mAccessibilityInteractionController;
3793    }
3794
3795    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3796            boolean insetsPending) throws RemoteException {
3797
3798        float appScale = mAttachInfo.mApplicationScale;
3799        boolean restore = false;
3800        if (params != null && mTranslator != null) {
3801            restore = true;
3802            params.backup();
3803            mTranslator.translateWindowLayout(params);
3804        }
3805        if (params != null) {
3806            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
3807        }
3808        mPendingConfiguration.seq = 0;
3809        //Log.d(TAG, ">>>>>> CALLING relayout");
3810        if (params != null && mOrigWindowType != params.type) {
3811            // For compatibility with old apps, don't crash here.
3812            if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
3813                Slog.w(TAG, "Window type can not be changed after "
3814                        + "the window is added; ignoring change of " + mView);
3815                params.type = mOrigWindowType;
3816            }
3817        }
3818        int relayoutResult = sWindowSession.relayout(
3819                mWindow, mSeq, params,
3820                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3821                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
3822                viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0,
3823                mWinFrame, mPendingContentInsets, mPendingVisibleInsets,
3824                mPendingConfiguration, mSurface);
3825        //Log.d(TAG, "<<<<<< BACK FROM relayout");
3826        if (restore) {
3827            params.restore();
3828        }
3829
3830        if (mTranslator != null) {
3831            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3832            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3833            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
3834        }
3835        return relayoutResult;
3836    }
3837
3838    /**
3839     * {@inheritDoc}
3840     */
3841    public void playSoundEffect(int effectId) {
3842        checkThread();
3843
3844        try {
3845            final AudioManager audioManager = getAudioManager();
3846
3847            switch (effectId) {
3848                case SoundEffectConstants.CLICK:
3849                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3850                    return;
3851                case SoundEffectConstants.NAVIGATION_DOWN:
3852                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3853                    return;
3854                case SoundEffectConstants.NAVIGATION_LEFT:
3855                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3856                    return;
3857                case SoundEffectConstants.NAVIGATION_RIGHT:
3858                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3859                    return;
3860                case SoundEffectConstants.NAVIGATION_UP:
3861                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3862                    return;
3863                default:
3864                    throw new IllegalArgumentException("unknown effect id " + effectId +
3865                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
3866            }
3867        } catch (IllegalStateException e) {
3868            // Exception thrown by getAudioManager() when mView is null
3869            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3870            e.printStackTrace();
3871        }
3872    }
3873
3874    /**
3875     * {@inheritDoc}
3876     */
3877    public boolean performHapticFeedback(int effectId, boolean always) {
3878        try {
3879            return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3880        } catch (RemoteException e) {
3881            return false;
3882        }
3883    }
3884
3885    /**
3886     * {@inheritDoc}
3887     */
3888    public View focusSearch(View focused, int direction) {
3889        checkThread();
3890        if (!(mView instanceof ViewGroup)) {
3891            return null;
3892        }
3893        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3894    }
3895
3896    public void debug() {
3897        mView.debug();
3898    }
3899
3900    public void dumpGfxInfo(int[] info) {
3901        if (mView != null) {
3902            getGfxInfo(mView, info);
3903        } else {
3904            info[0] = info[1] = 0;
3905        }
3906    }
3907
3908    private static void getGfxInfo(View view, int[] info) {
3909        DisplayList displayList = view.mDisplayList;
3910        info[0]++;
3911        if (displayList != null) {
3912            info[1] += displayList.getSize();
3913        }
3914
3915        if (view instanceof ViewGroup) {
3916            ViewGroup group = (ViewGroup) view;
3917
3918            int count = group.getChildCount();
3919            for (int i = 0; i < count; i++) {
3920                getGfxInfo(group.getChildAt(i), info);
3921            }
3922        }
3923    }
3924
3925    public void die(boolean immediate) {
3926        if (immediate) {
3927            doDie();
3928        } else {
3929            destroyHardwareRenderer();
3930            mHandler.sendEmptyMessage(MSG_DIE);
3931        }
3932    }
3933
3934    void doDie() {
3935        checkThread();
3936        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
3937        synchronized (this) {
3938            if (mAdded) {
3939                dispatchDetachedFromWindow();
3940            }
3941
3942            if (mAdded && !mFirst) {
3943                destroyHardwareRenderer();
3944
3945                if (mView != null) {
3946                    int viewVisibility = mView.getVisibility();
3947                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3948                    if (mWindowAttributesChanged || viewVisibilityChanged) {
3949                        // If layout params have been changed, first give them
3950                        // to the window manager to make sure it has the correct
3951                        // animation info.
3952                        try {
3953                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3954                                    & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) {
3955                                sWindowSession.finishDrawing(mWindow);
3956                            }
3957                        } catch (RemoteException e) {
3958                        }
3959                    }
3960
3961                    mSurface.release();
3962                }
3963            }
3964
3965            mAdded = false;
3966        }
3967    }
3968
3969    public void requestUpdateConfiguration(Configuration config) {
3970        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
3971        mHandler.sendMessage(msg);
3972    }
3973
3974    private void destroyHardwareRenderer() {
3975        AttachInfo attachInfo = mAttachInfo;
3976        HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer;
3977
3978        if (hardwareRenderer != null) {
3979            if (mView != null) {
3980                hardwareRenderer.destroyHardwareResources(mView);
3981            }
3982            hardwareRenderer.destroy(true);
3983            hardwareRenderer.setRequested(false);
3984
3985            attachInfo.mHardwareRenderer = null;
3986            attachInfo.mHardwareAccelerated = false;
3987        }
3988    }
3989
3990    void dispatchImeFinishedEvent(int seq, boolean handled) {
3991        Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT);
3992        msg.arg1 = seq;
3993        msg.arg2 = handled ? 1 : 0;
3994        msg.setAsynchronous(true);
3995        mHandler.sendMessage(msg);
3996    }
3997
3998    public void dispatchFinishInputConnection(InputConnection connection) {
3999        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
4000        mHandler.sendMessage(msg);
4001    }
4002
4003    public void dispatchResized(int w, int h, Rect coveredInsets,
4004            Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4005        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
4006                + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
4007                + " visibleInsets=" + visibleInsets.toShortString()
4008                + " reportDraw=" + reportDraw);
4009        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED);
4010        if (mTranslator != null) {
4011            mTranslator.translateRectInScreenToAppWindow(coveredInsets);
4012            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
4013            w *= mTranslator.applicationInvertedScale;
4014            h *= mTranslator.applicationInvertedScale;
4015        }
4016        msg.arg1 = w;
4017        msg.arg2 = h;
4018        ResizedInfo ri = new ResizedInfo();
4019        ri.coveredInsets = new Rect(coveredInsets);
4020        ri.visibleInsets = new Rect(visibleInsets);
4021        ri.newConfig = newConfig;
4022        msg.obj = ri;
4023        mHandler.sendMessage(msg);
4024    }
4025
4026    /**
4027     * Represents a pending input event that is waiting in a queue.
4028     *
4029     * Input events are processed in serial order by the timestamp specified by
4030     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
4031     * one input event to the application at a time and waits for the application
4032     * to finish handling it before delivering the next one.
4033     *
4034     * However, because the application or IME can synthesize and inject multiple
4035     * key events at a time without going through the input dispatcher, we end up
4036     * needing a queue on the application's side.
4037     */
4038    private static final class QueuedInputEvent {
4039        public static final int FLAG_DELIVER_POST_IME = 1;
4040
4041        public QueuedInputEvent mNext;
4042
4043        public InputEvent mEvent;
4044        public InputEventReceiver mReceiver;
4045        public int mFlags;
4046
4047        // Used for latency calculations.
4048        public long mReceiveTimeNanos;
4049        public long mDeliverTimeNanos;
4050        public long mDeliverPostImeTimeNanos;
4051    }
4052
4053    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
4054            InputEventReceiver receiver, int flags) {
4055        QueuedInputEvent q = mQueuedInputEventPool;
4056        if (q != null) {
4057            mQueuedInputEventPoolSize -= 1;
4058            mQueuedInputEventPool = q.mNext;
4059            q.mNext = null;
4060        } else {
4061            q = new QueuedInputEvent();
4062        }
4063
4064        q.mEvent = event;
4065        q.mReceiver = receiver;
4066        q.mFlags = flags;
4067        return q;
4068    }
4069
4070    private void recycleQueuedInputEvent(QueuedInputEvent q) {
4071        q.mEvent = null;
4072        q.mReceiver = null;
4073
4074        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
4075            mQueuedInputEventPoolSize += 1;
4076            q.mNext = mQueuedInputEventPool;
4077            mQueuedInputEventPool = q;
4078        }
4079    }
4080
4081    void enqueueInputEvent(InputEvent event) {
4082        enqueueInputEvent(event, null, 0, false);
4083    }
4084
4085    void enqueueInputEvent(InputEvent event,
4086            InputEventReceiver receiver, int flags, boolean processImmediately) {
4087        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
4088
4089        if (ViewDebug.DEBUG_LATENCY) {
4090            q.mReceiveTimeNanos = System.nanoTime();
4091            q.mDeliverTimeNanos = 0;
4092            q.mDeliverPostImeTimeNanos = 0;
4093        }
4094
4095        // Always enqueue the input event in order, regardless of its time stamp.
4096        // We do this because the application or the IME may inject key events
4097        // in response to touch events and we want to ensure that the injected keys
4098        // are processed in the order they were received and we cannot trust that
4099        // the time stamp of injected events are monotonic.
4100        QueuedInputEvent last = mFirstPendingInputEvent;
4101        if (last == null) {
4102            mFirstPendingInputEvent = q;
4103        } else {
4104            while (last.mNext != null) {
4105                last = last.mNext;
4106            }
4107            last.mNext = q;
4108        }
4109
4110        if (processImmediately) {
4111            doProcessInputEvents();
4112        } else {
4113            scheduleProcessInputEvents();
4114        }
4115    }
4116
4117    private void scheduleProcessInputEvents() {
4118        if (!mProcessInputEventsScheduled) {
4119            mProcessInputEventsScheduled = true;
4120            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
4121            msg.setAsynchronous(true);
4122            mHandler.sendMessage(msg);
4123        }
4124    }
4125
4126    void doProcessInputEvents() {
4127        while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) {
4128            QueuedInputEvent q = mFirstPendingInputEvent;
4129            mFirstPendingInputEvent = q.mNext;
4130            q.mNext = null;
4131            mCurrentInputEvent = q;
4132            deliverInputEvent(q);
4133        }
4134
4135        // We are done processing all input events that we can process right now
4136        // so we can clear the pending flag immediately.
4137        if (mProcessInputEventsScheduled) {
4138            mProcessInputEventsScheduled = false;
4139            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
4140        }
4141    }
4142
4143    private void finishInputEvent(QueuedInputEvent q, boolean handled) {
4144        if (q != mCurrentInputEvent) {
4145            throw new IllegalStateException("finished input event out of order");
4146        }
4147
4148        if (ViewDebug.DEBUG_LATENCY) {
4149            final long now = System.nanoTime();
4150            final long eventTime = q.mEvent.getEventTimeNano();
4151            final StringBuilder msg = new StringBuilder();
4152            msg.append("Spent ");
4153            msg.append((now - q.mReceiveTimeNanos) * 0.000001f);
4154            msg.append("ms processing ");
4155            if (q.mEvent instanceof KeyEvent) {
4156                final KeyEvent  keyEvent = (KeyEvent)q.mEvent;
4157                msg.append("key event, action=");
4158                msg.append(KeyEvent.actionToString(keyEvent.getAction()));
4159            } else {
4160                final MotionEvent motionEvent = (MotionEvent)q.mEvent;
4161                msg.append("motion event, action=");
4162                msg.append(MotionEvent.actionToString(motionEvent.getAction()));
4163                msg.append(", historySize=");
4164                msg.append(motionEvent.getHistorySize());
4165            }
4166            msg.append(", handled=");
4167            msg.append(handled);
4168            msg.append(", received at +");
4169            msg.append((q.mReceiveTimeNanos - eventTime) * 0.000001f);
4170            if (q.mDeliverTimeNanos != 0) {
4171                msg.append("ms, delivered at +");
4172                msg.append((q.mDeliverTimeNanos - eventTime) * 0.000001f);
4173            }
4174            if (q.mDeliverPostImeTimeNanos != 0) {
4175                msg.append("ms, delivered post IME at +");
4176                msg.append((q.mDeliverPostImeTimeNanos - eventTime) * 0.000001f);
4177            }
4178            msg.append("ms, finished at +");
4179            msg.append((now - eventTime) * 0.000001f);
4180            msg.append("ms.");
4181            Log.d(ViewDebug.DEBUG_LATENCY_TAG, msg.toString());
4182        }
4183
4184        if (q.mReceiver != null) {
4185            q.mReceiver.finishInputEvent(q.mEvent, handled);
4186        } else {
4187            q.mEvent.recycleIfNeededAfterDispatch();
4188        }
4189
4190        recycleQueuedInputEvent(q);
4191
4192        mCurrentInputEvent = null;
4193        if (mFirstPendingInputEvent != null) {
4194            scheduleProcessInputEvents();
4195        }
4196    }
4197
4198    void scheduleConsumeBatchedInput() {
4199        if (!mConsumeBatchedInputScheduled) {
4200            mConsumeBatchedInputScheduled = true;
4201            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
4202                    mConsumedBatchedInputRunnable, null);
4203        }
4204    }
4205
4206    void unscheduleConsumeBatchedInput() {
4207        if (mConsumeBatchedInputScheduled) {
4208            mConsumeBatchedInputScheduled = false;
4209            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
4210                    mConsumedBatchedInputRunnable, null);
4211        }
4212    }
4213
4214    void doConsumeBatchedInput(long frameTimeNanos) {
4215        if (mConsumeBatchedInputScheduled) {
4216            mConsumeBatchedInputScheduled = false;
4217            if (mInputEventReceiver != null) {
4218                mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos);
4219            }
4220            doProcessInputEvents();
4221        }
4222    }
4223
4224    final class TraversalRunnable implements Runnable {
4225        @Override
4226        public void run() {
4227            doTraversal();
4228        }
4229    }
4230    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
4231
4232    final class WindowInputEventReceiver extends InputEventReceiver {
4233        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
4234            super(inputChannel, looper);
4235        }
4236
4237        @Override
4238        public void onInputEvent(InputEvent event) {
4239            enqueueInputEvent(event, this, 0, true);
4240        }
4241
4242        @Override
4243        public void onBatchedInputEventPending() {
4244            scheduleConsumeBatchedInput();
4245        }
4246
4247        @Override
4248        public void dispose() {
4249            unscheduleConsumeBatchedInput();
4250            super.dispose();
4251        }
4252    }
4253    WindowInputEventReceiver mInputEventReceiver;
4254
4255    final class ConsumeBatchedInputRunnable implements Runnable {
4256        @Override
4257        public void run() {
4258            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
4259        }
4260    }
4261    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
4262            new ConsumeBatchedInputRunnable();
4263    boolean mConsumeBatchedInputScheduled;
4264
4265    final class InvalidateOnAnimationRunnable implements Runnable {
4266        private boolean mPosted;
4267        private ArrayList<View> mViews = new ArrayList<View>();
4268        private ArrayList<AttachInfo.InvalidateInfo> mViewRects =
4269                new ArrayList<AttachInfo.InvalidateInfo>();
4270        private View[] mTempViews;
4271        private AttachInfo.InvalidateInfo[] mTempViewRects;
4272
4273        public void addView(View view) {
4274            synchronized (this) {
4275                mViews.add(view);
4276                postIfNeededLocked();
4277            }
4278        }
4279
4280        public void addViewRect(AttachInfo.InvalidateInfo info) {
4281            synchronized (this) {
4282                mViewRects.add(info);
4283                postIfNeededLocked();
4284            }
4285        }
4286
4287        public void removeView(View view) {
4288            synchronized (this) {
4289                mViews.remove(view);
4290
4291                for (int i = mViewRects.size(); i-- > 0; ) {
4292                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
4293                    if (info.target == view) {
4294                        mViewRects.remove(i);
4295                        info.release();
4296                    }
4297                }
4298
4299                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
4300                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
4301                    mPosted = false;
4302                }
4303            }
4304        }
4305
4306        @Override
4307        public void run() {
4308            final int viewCount;
4309            final int viewRectCount;
4310            synchronized (this) {
4311                mPosted = false;
4312
4313                viewCount = mViews.size();
4314                if (viewCount != 0) {
4315                    mTempViews = mViews.toArray(mTempViews != null
4316                            ? mTempViews : new View[viewCount]);
4317                    mViews.clear();
4318                }
4319
4320                viewRectCount = mViewRects.size();
4321                if (viewRectCount != 0) {
4322                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
4323                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
4324                    mViewRects.clear();
4325                }
4326            }
4327
4328            for (int i = 0; i < viewCount; i++) {
4329                mTempViews[i].invalidate();
4330            }
4331
4332            for (int i = 0; i < viewRectCount; i++) {
4333                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
4334                info.target.invalidate(info.left, info.top, info.right, info.bottom);
4335                info.release();
4336            }
4337        }
4338
4339        private void postIfNeededLocked() {
4340            if (!mPosted) {
4341                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
4342                mPosted = true;
4343            }
4344        }
4345    }
4346    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
4347            new InvalidateOnAnimationRunnable();
4348
4349    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
4350        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
4351        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4352    }
4353
4354    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
4355            long delayMilliseconds) {
4356        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
4357        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4358    }
4359
4360    public void dispatchInvalidateOnAnimation(View view) {
4361        mInvalidateOnAnimationRunnable.addView(view);
4362    }
4363
4364    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
4365        mInvalidateOnAnimationRunnable.addViewRect(info);
4366    }
4367
4368    public void invalidateDisplayList(DisplayList displayList) {
4369        mDisplayLists.add(displayList);
4370
4371        mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST);
4372        Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST);
4373        mHandler.sendMessage(msg);
4374    }
4375
4376    public void cancelInvalidate(View view) {
4377        mHandler.removeMessages(MSG_INVALIDATE, view);
4378        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
4379        // them to the pool
4380        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
4381        mInvalidateOnAnimationRunnable.removeView(view);
4382    }
4383
4384    public void dispatchKey(KeyEvent event) {
4385        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event);
4386        msg.setAsynchronous(true);
4387        mHandler.sendMessage(msg);
4388    }
4389
4390    public void dispatchKeyFromIme(KeyEvent event) {
4391        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
4392        msg.setAsynchronous(true);
4393        mHandler.sendMessage(msg);
4394    }
4395
4396    public void dispatchUnhandledKey(KeyEvent event) {
4397        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4398            final KeyCharacterMap kcm = event.getKeyCharacterMap();
4399            final int keyCode = event.getKeyCode();
4400            final int metaState = event.getMetaState();
4401
4402            KeyEvent fallbackEvent = null;
4403            synchronized (mFallbackAction) {
4404                // Check for fallback actions specified by the key character map.
4405                if (kcm.getFallbackAction(keyCode, metaState, mFallbackAction)) {
4406                    int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
4407                    fallbackEvent = KeyEvent.obtain(
4408                            event.getDownTime(), event.getEventTime(),
4409                            event.getAction(), mFallbackAction.keyCode,
4410                            event.getRepeatCount(), mFallbackAction.metaState,
4411                            event.getDeviceId(), event.getScanCode(),
4412                            flags, event.getSource(), null);
4413                }
4414            }
4415            if (fallbackEvent != null) {
4416                dispatchKey(fallbackEvent);
4417            }
4418        }
4419    }
4420
4421    public void dispatchAppVisibility(boolean visible) {
4422        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
4423        msg.arg1 = visible ? 1 : 0;
4424        mHandler.sendMessage(msg);
4425    }
4426
4427    public void dispatchScreenStateChange(boolean on) {
4428        Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE);
4429        msg.arg1 = on ? 1 : 0;
4430        mHandler.sendMessage(msg);
4431    }
4432
4433    public void dispatchGetNewSurface() {
4434        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
4435        mHandler.sendMessage(msg);
4436    }
4437
4438    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4439        Message msg = Message.obtain();
4440        msg.what = MSG_WINDOW_FOCUS_CHANGED;
4441        msg.arg1 = hasFocus ? 1 : 0;
4442        msg.arg2 = inTouchMode ? 1 : 0;
4443        mHandler.sendMessage(msg);
4444    }
4445
4446    public void dispatchCloseSystemDialogs(String reason) {
4447        Message msg = Message.obtain();
4448        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
4449        msg.obj = reason;
4450        mHandler.sendMessage(msg);
4451    }
4452
4453    public void dispatchDragEvent(DragEvent event) {
4454        final int what;
4455        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
4456            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
4457            mHandler.removeMessages(what);
4458        } else {
4459            what = MSG_DISPATCH_DRAG_EVENT;
4460        }
4461        Message msg = mHandler.obtainMessage(what, event);
4462        mHandler.sendMessage(msg);
4463    }
4464
4465    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4466            int localValue, int localChanges) {
4467        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
4468        args.seq = seq;
4469        args.globalVisibility = globalVisibility;
4470        args.localValue = localValue;
4471        args.localChanges = localChanges;
4472        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
4473    }
4474
4475    public void dispatchDoneAnimating() {
4476        mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
4477    }
4478
4479    public void dispatchCheckFocus() {
4480        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
4481            // This will result in a call to checkFocus() below.
4482            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
4483        }
4484    }
4485
4486    /**
4487     * Post a callback to send a
4488     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4489     * This event is send at most once every
4490     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
4491     */
4492    private void postSendWindowContentChangedCallback(View source) {
4493        if (mSendWindowContentChangedAccessibilityEvent == null) {
4494            mSendWindowContentChangedAccessibilityEvent =
4495                new SendWindowContentChangedAccessibilityEvent();
4496        }
4497        View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource;
4498        if (oldSource == null) {
4499            mSendWindowContentChangedAccessibilityEvent.mSource = source;
4500            mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent,
4501                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
4502        } else {
4503            mSendWindowContentChangedAccessibilityEvent.mSource =
4504                    getCommonPredecessor(oldSource, source);
4505        }
4506    }
4507
4508    /**
4509     * Remove a posted callback to send a
4510     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4511     */
4512    private void removeSendWindowContentChangedCallback() {
4513        if (mSendWindowContentChangedAccessibilityEvent != null) {
4514            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
4515        }
4516    }
4517
4518    public boolean showContextMenuForChild(View originalView) {
4519        return false;
4520    }
4521
4522    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
4523        return null;
4524    }
4525
4526    public void createContextMenu(ContextMenu menu) {
4527    }
4528
4529    public void childDrawableStateChanged(View child) {
4530    }
4531
4532    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
4533        if (mView == null) {
4534            return false;
4535        }
4536        mAccessibilityManager.sendAccessibilityEvent(event);
4537        return true;
4538    }
4539
4540    @Override
4541    public void childAccessibilityStateChanged(View child) {
4542        postSendWindowContentChangedCallback(child);
4543    }
4544
4545    private View getCommonPredecessor(View first, View second) {
4546        if (mAttachInfo != null) {
4547            if (mTempHashSet == null) {
4548                mTempHashSet = new HashSet<View>();
4549            }
4550            HashSet<View> seen = mTempHashSet;
4551            seen.clear();
4552            View firstCurrent = first;
4553            while (firstCurrent != null) {
4554                seen.add(firstCurrent);
4555                ViewParent firstCurrentParent = firstCurrent.mParent;
4556                if (firstCurrentParent instanceof View) {
4557                    firstCurrent = (View) firstCurrentParent;
4558                } else {
4559                    firstCurrent = null;
4560                }
4561            }
4562            View secondCurrent = second;
4563            while (secondCurrent != null) {
4564                if (seen.contains(secondCurrent)) {
4565                    seen.clear();
4566                    return secondCurrent;
4567                }
4568                ViewParent secondCurrentParent = secondCurrent.mParent;
4569                if (secondCurrentParent instanceof View) {
4570                    secondCurrent = (View) secondCurrentParent;
4571                } else {
4572                    secondCurrent = null;
4573                }
4574            }
4575            seen.clear();
4576        }
4577        return null;
4578    }
4579
4580    void checkThread() {
4581        if (mThread != Thread.currentThread()) {
4582            throw new CalledFromWrongThreadException(
4583                    "Only the original thread that created a view hierarchy can touch its views.");
4584        }
4585    }
4586
4587    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
4588        // ViewAncestor never intercepts touch event, so this can be a no-op
4589    }
4590
4591    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
4592            boolean immediate) {
4593        return scrollToRectOrFocus(rectangle, immediate);
4594    }
4595
4596    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
4597        // Do nothing.
4598    }
4599
4600    class TakenSurfaceHolder extends BaseSurfaceHolder {
4601        @Override
4602        public boolean onAllowLockCanvas() {
4603            return mDrawingAllowed;
4604        }
4605
4606        @Override
4607        public void onRelayoutContainer() {
4608            // Not currently interesting -- from changing between fixed and layout size.
4609        }
4610
4611        public void setFormat(int format) {
4612            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
4613        }
4614
4615        public void setType(int type) {
4616            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
4617        }
4618
4619        @Override
4620        public void onUpdateSurface() {
4621            // We take care of format and type changes on our own.
4622            throw new IllegalStateException("Shouldn't be here");
4623        }
4624
4625        public boolean isCreating() {
4626            return mIsCreating;
4627        }
4628
4629        @Override
4630        public void setFixedSize(int width, int height) {
4631            throw new UnsupportedOperationException(
4632                    "Currently only support sizing from layout");
4633        }
4634
4635        public void setKeepScreenOn(boolean screenOn) {
4636            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
4637        }
4638    }
4639
4640    static class InputMethodCallback extends IInputMethodCallback.Stub {
4641        private WeakReference<ViewRootImpl> mViewAncestor;
4642
4643        public InputMethodCallback(ViewRootImpl viewAncestor) {
4644            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4645        }
4646
4647        public void finishedEvent(int seq, boolean handled) {
4648            final ViewRootImpl viewAncestor = mViewAncestor.get();
4649            if (viewAncestor != null) {
4650                viewAncestor.dispatchImeFinishedEvent(seq, handled);
4651            }
4652        }
4653
4654        public void sessionCreated(IInputMethodSession session) {
4655            // Stub -- not for use in the client.
4656        }
4657    }
4658
4659    static class W extends IWindow.Stub {
4660        private final WeakReference<ViewRootImpl> mViewAncestor;
4661
4662        W(ViewRootImpl viewAncestor) {
4663            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4664        }
4665
4666        public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
4667                boolean reportDraw, Configuration newConfig) {
4668            final ViewRootImpl viewAncestor = mViewAncestor.get();
4669            if (viewAncestor != null) {
4670                viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw,
4671                        newConfig);
4672            }
4673        }
4674
4675        public void dispatchAppVisibility(boolean visible) {
4676            final ViewRootImpl viewAncestor = mViewAncestor.get();
4677            if (viewAncestor != null) {
4678                viewAncestor.dispatchAppVisibility(visible);
4679            }
4680        }
4681
4682        public void dispatchScreenState(boolean on) {
4683            final ViewRootImpl viewAncestor = mViewAncestor.get();
4684            if (viewAncestor != null) {
4685                viewAncestor.dispatchScreenStateChange(on);
4686            }
4687        }
4688
4689        public void dispatchGetNewSurface() {
4690            final ViewRootImpl viewAncestor = mViewAncestor.get();
4691            if (viewAncestor != null) {
4692                viewAncestor.dispatchGetNewSurface();
4693            }
4694        }
4695
4696        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4697            final ViewRootImpl viewAncestor = mViewAncestor.get();
4698            if (viewAncestor != null) {
4699                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
4700            }
4701        }
4702
4703        private static int checkCallingPermission(String permission) {
4704            try {
4705                return ActivityManagerNative.getDefault().checkPermission(
4706                        permission, Binder.getCallingPid(), Binder.getCallingUid());
4707            } catch (RemoteException e) {
4708                return PackageManager.PERMISSION_DENIED;
4709            }
4710        }
4711
4712        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
4713            final ViewRootImpl viewAncestor = mViewAncestor.get();
4714            if (viewAncestor != null) {
4715                final View view = viewAncestor.mView;
4716                if (view != null) {
4717                    if (checkCallingPermission(Manifest.permission.DUMP) !=
4718                            PackageManager.PERMISSION_GRANTED) {
4719                        throw new SecurityException("Insufficient permissions to invoke"
4720                                + " executeCommand() from pid=" + Binder.getCallingPid()
4721                                + ", uid=" + Binder.getCallingUid());
4722                    }
4723
4724                    OutputStream clientStream = null;
4725                    try {
4726                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
4727                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
4728                    } catch (IOException e) {
4729                        e.printStackTrace();
4730                    } finally {
4731                        if (clientStream != null) {
4732                            try {
4733                                clientStream.close();
4734                            } catch (IOException e) {
4735                                e.printStackTrace();
4736                            }
4737                        }
4738                    }
4739                }
4740            }
4741        }
4742
4743        public void closeSystemDialogs(String reason) {
4744            final ViewRootImpl viewAncestor = mViewAncestor.get();
4745            if (viewAncestor != null) {
4746                viewAncestor.dispatchCloseSystemDialogs(reason);
4747            }
4748        }
4749
4750        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
4751                boolean sync) {
4752            if (sync) {
4753                try {
4754                    sWindowSession.wallpaperOffsetsComplete(asBinder());
4755                } catch (RemoteException e) {
4756                }
4757            }
4758        }
4759
4760        public void dispatchWallpaperCommand(String action, int x, int y,
4761                int z, Bundle extras, boolean sync) {
4762            if (sync) {
4763                try {
4764                    sWindowSession.wallpaperCommandComplete(asBinder(), null);
4765                } catch (RemoteException e) {
4766                }
4767            }
4768        }
4769
4770        /* Drag/drop */
4771        public void dispatchDragEvent(DragEvent event) {
4772            final ViewRootImpl viewAncestor = mViewAncestor.get();
4773            if (viewAncestor != null) {
4774                viewAncestor.dispatchDragEvent(event);
4775            }
4776        }
4777
4778        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4779                int localValue, int localChanges) {
4780            final ViewRootImpl viewAncestor = mViewAncestor.get();
4781            if (viewAncestor != null) {
4782                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
4783                        localValue, localChanges);
4784            }
4785        }
4786
4787        public void doneAnimating() {
4788            final ViewRootImpl viewAncestor = mViewAncestor.get();
4789            if (viewAncestor != null) {
4790                viewAncestor.dispatchDoneAnimating();
4791            }
4792        }
4793    }
4794
4795    /**
4796     * Maintains state information for a single trackball axis, generating
4797     * discrete (DPAD) movements based on raw trackball motion.
4798     */
4799    static final class TrackballAxis {
4800        /**
4801         * The maximum amount of acceleration we will apply.
4802         */
4803        static final float MAX_ACCELERATION = 20;
4804
4805        /**
4806         * The maximum amount of time (in milliseconds) between events in order
4807         * for us to consider the user to be doing fast trackball movements,
4808         * and thus apply an acceleration.
4809         */
4810        static final long FAST_MOVE_TIME = 150;
4811
4812        /**
4813         * Scaling factor to the time (in milliseconds) between events to how
4814         * much to multiple/divide the current acceleration.  When movement
4815         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4816         * FAST_MOVE_TIME it divides it.
4817         */
4818        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4819
4820        float position;
4821        float absPosition;
4822        float acceleration = 1;
4823        long lastMoveTime = 0;
4824        int step;
4825        int dir;
4826        int nonAccelMovement;
4827
4828        void reset(int _step) {
4829            position = 0;
4830            acceleration = 1;
4831            lastMoveTime = 0;
4832            step = _step;
4833            dir = 0;
4834        }
4835
4836        /**
4837         * Add trackball movement into the state.  If the direction of movement
4838         * has been reversed, the state is reset before adding the
4839         * movement (so that you don't have to compensate for any previously
4840         * collected movement before see the result of the movement in the
4841         * new direction).
4842         *
4843         * @return Returns the absolute value of the amount of movement
4844         * collected so far.
4845         */
4846        float collect(float off, long time, String axis) {
4847            long normTime;
4848            if (off > 0) {
4849                normTime = (long)(off * FAST_MOVE_TIME);
4850                if (dir < 0) {
4851                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4852                    position = 0;
4853                    step = 0;
4854                    acceleration = 1;
4855                    lastMoveTime = 0;
4856                }
4857                dir = 1;
4858            } else if (off < 0) {
4859                normTime = (long)((-off) * FAST_MOVE_TIME);
4860                if (dir > 0) {
4861                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4862                    position = 0;
4863                    step = 0;
4864                    acceleration = 1;
4865                    lastMoveTime = 0;
4866                }
4867                dir = -1;
4868            } else {
4869                normTime = 0;
4870            }
4871
4872            // The number of milliseconds between each movement that is
4873            // considered "normal" and will not result in any acceleration
4874            // or deceleration, scaled by the offset we have here.
4875            if (normTime > 0) {
4876                long delta = time - lastMoveTime;
4877                lastMoveTime = time;
4878                float acc = acceleration;
4879                if (delta < normTime) {
4880                    // The user is scrolling rapidly, so increase acceleration.
4881                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4882                    if (scale > 1) acc *= scale;
4883                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4884                            + off + " normTime=" + normTime + " delta=" + delta
4885                            + " scale=" + scale + " acc=" + acc);
4886                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4887                } else {
4888                    // The user is scrolling slowly, so decrease acceleration.
4889                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4890                    if (scale > 1) acc /= scale;
4891                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4892                            + off + " normTime=" + normTime + " delta=" + delta
4893                            + " scale=" + scale + " acc=" + acc);
4894                    acceleration = acc > 1 ? acc : 1;
4895                }
4896            }
4897            position += off;
4898            return (absPosition = Math.abs(position));
4899        }
4900
4901        /**
4902         * Generate the number of discrete movement events appropriate for
4903         * the currently collected trackball movement.
4904         *
4905         * @param precision The minimum movement required to generate the
4906         * first discrete movement.
4907         *
4908         * @return Returns the number of discrete movements, either positive
4909         * or negative, or 0 if there is not enough trackball movement yet
4910         * for a discrete movement.
4911         */
4912        int generate(float precision) {
4913            int movement = 0;
4914            nonAccelMovement = 0;
4915            do {
4916                final int dir = position >= 0 ? 1 : -1;
4917                switch (step) {
4918                    // If we are going to execute the first step, then we want
4919                    // to do this as soon as possible instead of waiting for
4920                    // a full movement, in order to make things look responsive.
4921                    case 0:
4922                        if (absPosition < precision) {
4923                            return movement;
4924                        }
4925                        movement += dir;
4926                        nonAccelMovement += dir;
4927                        step = 1;
4928                        break;
4929                    // If we have generated the first movement, then we need
4930                    // to wait for the second complete trackball motion before
4931                    // generating the second discrete movement.
4932                    case 1:
4933                        if (absPosition < 2) {
4934                            return movement;
4935                        }
4936                        movement += dir;
4937                        nonAccelMovement += dir;
4938                        position += dir > 0 ? -2 : 2;
4939                        absPosition = Math.abs(position);
4940                        step = 2;
4941                        break;
4942                    // After the first two, we generate discrete movements
4943                    // consistently with the trackball, applying an acceleration
4944                    // if the trackball is moving quickly.  This is a simple
4945                    // acceleration on top of what we already compute based
4946                    // on how quickly the wheel is being turned, to apply
4947                    // a longer increasing acceleration to continuous movement
4948                    // in one direction.
4949                    default:
4950                        if (absPosition < 1) {
4951                            return movement;
4952                        }
4953                        movement += dir;
4954                        position += dir >= 0 ? -1 : 1;
4955                        absPosition = Math.abs(position);
4956                        float acc = acceleration;
4957                        acc *= 1.1f;
4958                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4959                        break;
4960                }
4961            } while (true);
4962        }
4963    }
4964
4965    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
4966        public CalledFromWrongThreadException(String msg) {
4967            super(msg);
4968        }
4969    }
4970
4971    private SurfaceHolder mHolder = new SurfaceHolder() {
4972        // we only need a SurfaceHolder for opengl. it would be nice
4973        // to implement everything else though, especially the callback
4974        // support (opengl doesn't make use of it right now, but eventually
4975        // will).
4976        public Surface getSurface() {
4977            return mSurface;
4978        }
4979
4980        public boolean isCreating() {
4981            return false;
4982        }
4983
4984        public void addCallback(Callback callback) {
4985        }
4986
4987        public void removeCallback(Callback callback) {
4988        }
4989
4990        public void setFixedSize(int width, int height) {
4991        }
4992
4993        public void setSizeFromLayout() {
4994        }
4995
4996        public void setFormat(int format) {
4997        }
4998
4999        public void setType(int type) {
5000        }
5001
5002        public void setKeepScreenOn(boolean screenOn) {
5003        }
5004
5005        public Canvas lockCanvas() {
5006            return null;
5007        }
5008
5009        public Canvas lockCanvas(Rect dirty) {
5010            return null;
5011        }
5012
5013        public void unlockCanvasAndPost(Canvas canvas) {
5014        }
5015        public Rect getSurfaceFrame() {
5016            return null;
5017        }
5018    };
5019
5020    static RunQueue getRunQueue() {
5021        RunQueue rq = sRunQueues.get();
5022        if (rq != null) {
5023            return rq;
5024        }
5025        rq = new RunQueue();
5026        sRunQueues.set(rq);
5027        return rq;
5028    }
5029
5030    /**
5031     * The run queue is used to enqueue pending work from Views when no Handler is
5032     * attached.  The work is executed during the next call to performTraversals on
5033     * the thread.
5034     * @hide
5035     */
5036    static final class RunQueue {
5037        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
5038
5039        void post(Runnable action) {
5040            postDelayed(action, 0);
5041        }
5042
5043        void postDelayed(Runnable action, long delayMillis) {
5044            HandlerAction handlerAction = new HandlerAction();
5045            handlerAction.action = action;
5046            handlerAction.delay = delayMillis;
5047
5048            synchronized (mActions) {
5049                mActions.add(handlerAction);
5050            }
5051        }
5052
5053        void removeCallbacks(Runnable action) {
5054            final HandlerAction handlerAction = new HandlerAction();
5055            handlerAction.action = action;
5056
5057            synchronized (mActions) {
5058                final ArrayList<HandlerAction> actions = mActions;
5059
5060                while (actions.remove(handlerAction)) {
5061                    // Keep going
5062                }
5063            }
5064        }
5065
5066        void executeActions(Handler handler) {
5067            synchronized (mActions) {
5068                final ArrayList<HandlerAction> actions = mActions;
5069                final int count = actions.size();
5070
5071                for (int i = 0; i < count; i++) {
5072                    final HandlerAction handlerAction = actions.get(i);
5073                    handler.postDelayed(handlerAction.action, handlerAction.delay);
5074                }
5075
5076                actions.clear();
5077            }
5078        }
5079
5080        private static class HandlerAction {
5081            Runnable action;
5082            long delay;
5083
5084            @Override
5085            public boolean equals(Object o) {
5086                if (this == o) return true;
5087                if (o == null || getClass() != o.getClass()) return false;
5088
5089                HandlerAction that = (HandlerAction) o;
5090                return !(action != null ? !action.equals(that.action) : that.action != null);
5091
5092            }
5093
5094            @Override
5095            public int hashCode() {
5096                int result = action != null ? action.hashCode() : 0;
5097                result = 31 * result + (int) (delay ^ (delay >>> 32));
5098                return result;
5099            }
5100        }
5101    }
5102
5103    /**
5104     * Class for managing the accessibility interaction connection
5105     * based on the global accessibility state.
5106     */
5107    final class AccessibilityInteractionConnectionManager
5108            implements AccessibilityStateChangeListener {
5109        public void onAccessibilityStateChanged(boolean enabled) {
5110            if (enabled) {
5111                ensureConnection();
5112                if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
5113                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
5114                    View focusedView = mView.findFocus();
5115                    if (focusedView != null && focusedView != mView) {
5116                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5117                    }
5118                }
5119            } else {
5120                ensureNoConnection();
5121                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
5122            }
5123        }
5124
5125        public void ensureConnection() {
5126            if (mAttachInfo != null) {
5127                final boolean registered =
5128                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5129                if (!registered) {
5130                    mAttachInfo.mAccessibilityWindowId =
5131                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
5132                                new AccessibilityInteractionConnection(ViewRootImpl.this));
5133                }
5134            }
5135        }
5136
5137        public void ensureNoConnection() {
5138            final boolean registered =
5139                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5140            if (registered) {
5141                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED;
5142                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
5143            }
5144        }
5145    }
5146
5147    /**
5148     * This class is an interface this ViewAncestor provides to the
5149     * AccessibilityManagerService to the latter can interact with
5150     * the view hierarchy in this ViewAncestor.
5151     */
5152    static final class AccessibilityInteractionConnection
5153            extends IAccessibilityInteractionConnection.Stub {
5154        private final WeakReference<ViewRootImpl> mViewRootImpl;
5155
5156        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
5157            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
5158        }
5159
5160        @Override
5161        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
5162                int interactionId, IAccessibilityInteractionConnectionCallback callback,
5163                int flags, int interrogatingPid, long interrogatingTid) {
5164            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5165            if (viewRootImpl != null && viewRootImpl.mView != null) {
5166                viewRootImpl.getAccessibilityInteractionController()
5167                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
5168                        interactionId, callback, flags, interrogatingPid, interrogatingTid);
5169            } else {
5170                // We cannot make the call and notify the caller so it does not wait.
5171                try {
5172                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5173                } catch (RemoteException re) {
5174                    /* best effort - ignore */
5175                }
5176            }
5177        }
5178
5179        @Override
5180        public void performAccessibilityAction(long accessibilityNodeId, int action,
5181                Bundle arguments, int interactionId,
5182                IAccessibilityInteractionConnectionCallback callback, int flags,
5183                int interogatingPid, long interrogatingTid) {
5184            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5185            if (viewRootImpl != null && viewRootImpl.mView != null) {
5186                viewRootImpl.getAccessibilityInteractionController()
5187                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
5188                            interactionId, callback, flags, interogatingPid, interrogatingTid);
5189            } else {
5190                // We cannot make the call and notify the caller so it does not wait.
5191                try {
5192                    callback.setPerformAccessibilityActionResult(false, interactionId);
5193                } catch (RemoteException re) {
5194                    /* best effort - ignore */
5195                }
5196            }
5197        }
5198
5199        @Override
5200        public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId,
5201                int interactionId, IAccessibilityInteractionConnectionCallback callback,
5202                int flags, int interrogatingPid, long interrogatingTid) {
5203            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5204            if (viewRootImpl != null && viewRootImpl.mView != null) {
5205                viewRootImpl.getAccessibilityInteractionController()
5206                    .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId,
5207                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
5208            } else {
5209                // We cannot make the call and notify the caller so it does not wait.
5210                try {
5211                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5212                } catch (RemoteException re) {
5213                    /* best effort - ignore */
5214                }
5215            }
5216        }
5217
5218        @Override
5219        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
5220                int interactionId, IAccessibilityInteractionConnectionCallback callback,
5221                int flags, int interrogatingPid, long interrogatingTid) {
5222            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5223            if (viewRootImpl != null && viewRootImpl.mView != null) {
5224                viewRootImpl.getAccessibilityInteractionController()
5225                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
5226                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
5227            } else {
5228                // We cannot make the call and notify the caller so it does not wait.
5229                try {
5230                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5231                } catch (RemoteException re) {
5232                    /* best effort - ignore */
5233                }
5234            }
5235        }
5236
5237        @Override
5238        public void findFocus(long accessibilityNodeId, int interactionId, int focusType,
5239                IAccessibilityInteractionConnectionCallback callback,  int flags,
5240                int interrogatingPid, long interrogatingTid) {
5241            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5242            if (viewRootImpl != null && viewRootImpl.mView != null) {
5243                viewRootImpl.getAccessibilityInteractionController()
5244                    .findFocusClientThread(accessibilityNodeId, interactionId, focusType,
5245                            callback, flags, interrogatingPid, interrogatingTid);
5246            } else {
5247                // We cannot make the call and notify the caller so it does not wait.
5248                try {
5249                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5250                } catch (RemoteException re) {
5251                    /* best effort - ignore */
5252                }
5253            }
5254        }
5255
5256        @Override
5257        public void focusSearch(long accessibilityNodeId, int interactionId, int direction,
5258                IAccessibilityInteractionConnectionCallback callback, int flags,
5259                int interrogatingPid, long interrogatingTid) {
5260            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5261            if (viewRootImpl != null && viewRootImpl.mView != null) {
5262                viewRootImpl.getAccessibilityInteractionController()
5263                    .focusSearchClientThread(accessibilityNodeId, interactionId, direction,
5264                            callback, flags, interrogatingPid, interrogatingTid);
5265            } else {
5266                // We cannot make the call and notify the caller so it does not wait.
5267                try {
5268                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5269                } catch (RemoteException re) {
5270                    /* best effort - ignore */
5271                }
5272            }
5273        }
5274    }
5275
5276    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
5277        public View mSource;
5278
5279        public void run() {
5280            if (mSource != null) {
5281                mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
5282                mSource.resetAccessibilityStateChanged();
5283                mSource = null;
5284            }
5285        }
5286    }
5287}
5288