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