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