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