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