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