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