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