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