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