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