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