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