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