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