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