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