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