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