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