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