ViewRootImpl.java revision 908aecc3a63c5520d5b11da14a9383f885b7d126
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    // These are accessed by multiple threads.
255    final Rect mWinFrame; // frame given by window manager.
256
257    final Rect mPendingVisibleInsets = new Rect();
258    final Rect mPendingContentInsets = new Rect();
259    final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
260            = new ViewTreeObserver.InternalInsetsInfo();
261
262    final Rect mFitSystemWindowsInsets = new Rect();
263
264    final Configuration mLastConfiguration = new Configuration();
265    final Configuration mPendingConfiguration = new Configuration();
266
267    class ResizedInfo {
268        Rect contentInsets;
269        Rect visibleInsets;
270        Configuration newConfig;
271    }
272
273    boolean mScrollMayChange;
274    int mSoftInputMode;
275    View mLastScrolledFocus;
276    int mScrollY;
277    int mCurScrollY;
278    Scroller mScroller;
279    HardwareLayer mResizeBuffer;
280    long mResizeBufferStartTime;
281    int mResizeBufferDuration;
282    static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
283    private ArrayList<LayoutTransition> mPendingTransitions;
284
285    final ViewConfiguration mViewConfiguration;
286
287    /* Drag/drop */
288    ClipDescription mDragDescription;
289    View mCurrentDragView;
290    volatile Object mLocalDragState;
291    final PointF mDragPoint = new PointF();
292    final PointF mLastTouchPoint = new PointF();
293
294    private boolean mProfileRendering;
295    private Thread mRenderProfiler;
296    private volatile boolean mRenderProfilingEnabled;
297
298    // Variables to track frames per second, enabled via DEBUG_FPS flag
299    private long mFpsStartTime = -1;
300    private long mFpsPrevTime = -1;
301    private int mFpsNumFrames;
302
303    private final ArrayList<DisplayList> mDisplayLists = new ArrayList<DisplayList>(24);
304
305    /**
306     * see {@link #playSoundEffect(int)}
307     */
308    AudioManager mAudioManager;
309
310    final AccessibilityManager mAccessibilityManager;
311
312    AccessibilityInteractionController mAccessibilityInteractionController;
313
314    AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
315
316    SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
317
318    HashSet<View> mTempHashSet;
319
320    private final int mDensity;
321    private final int mNoncompatDensity;
322
323    /**
324     * Consistency verifier for debugging purposes.
325     */
326    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
327            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
328                    new InputEventConsistencyVerifier(this, 0) : null;
329
330    public static IWindowSession getWindowSession(Looper mainLooper) {
331        synchronized (mStaticInit) {
332            if (!mInitialized) {
333                try {
334                    InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
335                    IWindowManager windowManager = WindowManagerImpl.getWindowManagerService();
336                    sWindowSession = windowManager.openSession(
337                            imm.getClient(), imm.getInputContext());
338                    float animatorScale = windowManager.getAnimationScale(2);
339                    ValueAnimator.setDurationScale(animatorScale);
340                    mInitialized = true;
341                } catch (RemoteException e) {
342                }
343            }
344            return sWindowSession;
345        }
346    }
347
348    static final class SystemUiVisibilityInfo {
349        int seq;
350        int globalVisibility;
351        int localValue;
352        int localChanges;
353    }
354
355    public ViewRootImpl(Context context) {
356        super();
357
358        if (MEASURE_LATENCY) {
359            if (lt == null) {
360                lt = new LatencyTimer(100, 1000);
361            }
362        }
363
364        // Initialize the statics when this class is first instantiated. This is
365        // done here instead of in the static block because Zygote does not
366        // allow the spawning of threads.
367        getWindowSession(context.getMainLooper());
368
369        mThread = Thread.currentThread();
370        mLocation = new WindowLeaked(null);
371        mLocation.fillInStackTrace();
372        mWidth = -1;
373        mHeight = -1;
374        mDirty = new Rect();
375        mTempRect = new Rect();
376        mVisRect = new Rect();
377        mWinFrame = new Rect();
378        mWindow = new W(this);
379        mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
380        mInputMethodCallback = new InputMethodCallback(this);
381        mViewVisibility = View.GONE;
382        mTransparentRegion = new Region();
383        mPreviousTransparentRegion = new Region();
384        mFirst = true; // true for the first time the view is added
385        mAdded = false;
386        mAccessibilityManager = AccessibilityManager.getInstance(context);
387        mAccessibilityInteractionConnectionManager =
388            new AccessibilityInteractionConnectionManager();
389        mAccessibilityManager.addAccessibilityStateChangeListener(
390                mAccessibilityInteractionConnectionManager);
391        mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, mHandler, this);
392        mViewConfiguration = ViewConfiguration.get(context);
393        mDensity = context.getResources().getDisplayMetrics().densityDpi;
394        mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
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.addToDisplay(mWindow, mSeq, mWindowAttributes,
550                            getHostVisibility(), Display.DEFAULT_DISPLAY,
551                            mAttachInfo.mContentInsets, 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 ? mNoncompatDensity : 0);
2278                attachInfo.mSetIgnoreDirtyState = false;
2279
2280                mView.draw(canvas);
2281
2282                drawAccessibilityFocusedDrawableIfNeeded(canvas);
2283            } finally {
2284                if (!attachInfo.mSetIgnoreDirtyState) {
2285                    // Only clear the flag if it was not set during the mView.draw() call
2286                    attachInfo.mIgnoreDirtyState = false;
2287                }
2288            }
2289        } finally {
2290            try {
2291                surface.unlockCanvasAndPost(canvas);
2292            } catch (IllegalArgumentException e) {
2293                Log.e(TAG, "Could not unlock surface", e);
2294                mLayoutRequested = true;    // ask wm for a new surface next time.
2295                //noinspection ReturnInsideFinallyBlock
2296                return false;
2297            }
2298
2299            if (LOCAL_LOGV) {
2300                Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
2301            }
2302        }
2303        return true;
2304    }
2305
2306    /**
2307     * We want to draw a highlight around the current accessibility focused.
2308     * Since adding a style for all possible view is not a viable option we
2309     * have this specialized drawing method.
2310     *
2311     * Note: We are doing this here to be able to draw the highlight for
2312     *       virtual views in addition to real ones.
2313     *
2314     * @param canvas The canvas on which to draw.
2315     */
2316    private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2317        AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2318        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2319            return;
2320        }
2321        if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) {
2322            return;
2323        }
2324        Drawable drawable = getAccessibilityFocusedDrawable();
2325        if (drawable == null) {
2326            return;
2327        }
2328        AccessibilityNodeProvider provider =
2329            mAccessibilityFocusedHost.getAccessibilityNodeProvider();
2330        Rect bounds = mView.mAttachInfo.mTmpInvalRect;
2331        if (provider == null) {
2332            mAccessibilityFocusedHost.getDrawingRect(bounds);
2333            if (mView instanceof ViewGroup) {
2334                ViewGroup viewGroup = (ViewGroup) mView;
2335                viewGroup.offsetDescendantRectToMyCoords(mAccessibilityFocusedHost, bounds);
2336            }
2337        } else {
2338            if (mAccessibilityFocusedVirtualView == null) {
2339                return;
2340            }
2341            mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2342            bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
2343        }
2344        drawable.setBounds(bounds);
2345        drawable.draw(canvas);
2346    }
2347
2348    private Drawable getAccessibilityFocusedDrawable() {
2349        if (mAttachInfo != null) {
2350            // Lazily load the accessibility focus drawable.
2351            if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2352                TypedValue value = new TypedValue();
2353                final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2354                        R.attr.accessibilityFocusedDrawable, value, true);
2355                if (resolved) {
2356                    mAttachInfo.mAccessibilityFocusDrawable =
2357                        mView.mContext.getResources().getDrawable(value.resourceId);
2358                }
2359            }
2360            return mAttachInfo.mAccessibilityFocusDrawable;
2361        }
2362        return null;
2363    }
2364
2365    void invalidateDisplayLists() {
2366        final ArrayList<DisplayList> displayLists = mDisplayLists;
2367        final int count = displayLists.size();
2368
2369        for (int i = 0; i < count; i++) {
2370            final DisplayList displayList = displayLists.get(i);
2371            displayList.invalidate();
2372            displayList.clear();
2373        }
2374
2375        displayLists.clear();
2376    }
2377
2378    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2379        final View.AttachInfo attachInfo = mAttachInfo;
2380        final Rect ci = attachInfo.mContentInsets;
2381        final Rect vi = attachInfo.mVisibleInsets;
2382        int scrollY = 0;
2383        boolean handled = false;
2384
2385        if (vi.left > ci.left || vi.top > ci.top
2386                || vi.right > ci.right || vi.bottom > ci.bottom) {
2387            // We'll assume that we aren't going to change the scroll
2388            // offset, since we want to avoid that unless it is actually
2389            // going to make the focus visible...  otherwise we scroll
2390            // all over the place.
2391            scrollY = mScrollY;
2392            // We can be called for two different situations: during a draw,
2393            // to update the scroll position if the focus has changed (in which
2394            // case 'rectangle' is null), or in response to a
2395            // requestChildRectangleOnScreen() call (in which case 'rectangle'
2396            // is non-null and we just want to scroll to whatever that
2397            // rectangle is).
2398            View focus = mRealFocusedView;
2399
2400            // When in touch mode, focus points to the previously focused view,
2401            // which may have been removed from the view hierarchy. The following
2402            // line checks whether the view is still in our hierarchy.
2403            if (focus == null || focus.mAttachInfo != mAttachInfo) {
2404                mRealFocusedView = null;
2405                return false;
2406            }
2407
2408            if (focus != mLastScrolledFocus) {
2409                // If the focus has changed, then ignore any requests to scroll
2410                // to a rectangle; first we want to make sure the entire focus
2411                // view is visible.
2412                rectangle = null;
2413            }
2414            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2415                    + " rectangle=" + rectangle + " ci=" + ci
2416                    + " vi=" + vi);
2417            if (focus == mLastScrolledFocus && !mScrollMayChange
2418                    && rectangle == null) {
2419                // Optimization: if the focus hasn't changed since last
2420                // time, and no layout has happened, then just leave things
2421                // as they are.
2422                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2423                        + mScrollY + " vi=" + vi.toShortString());
2424            } else if (focus != null) {
2425                // We need to determine if the currently focused view is
2426                // within the visible part of the window and, if not, apply
2427                // a pan so it can be seen.
2428                mLastScrolledFocus = focus;
2429                mScrollMayChange = false;
2430                if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2431                // Try to find the rectangle from the focus view.
2432                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2433                    if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2434                            + mView.getWidth() + " h=" + mView.getHeight()
2435                            + " ci=" + ci.toShortString()
2436                            + " vi=" + vi.toShortString());
2437                    if (rectangle == null) {
2438                        focus.getFocusedRect(mTempRect);
2439                        if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2440                                + ": focusRect=" + mTempRect.toShortString());
2441                        if (mView instanceof ViewGroup) {
2442                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2443                                    focus, mTempRect);
2444                        }
2445                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2446                                "Focus in window: focusRect="
2447                                + mTempRect.toShortString()
2448                                + " visRect=" + mVisRect.toShortString());
2449                    } else {
2450                        mTempRect.set(rectangle);
2451                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2452                                "Request scroll to rect: "
2453                                + mTempRect.toShortString()
2454                                + " visRect=" + mVisRect.toShortString());
2455                    }
2456                    if (mTempRect.intersect(mVisRect)) {
2457                        if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2458                                "Focus window visible rect: "
2459                                + mTempRect.toShortString());
2460                        if (mTempRect.height() >
2461                                (mView.getHeight()-vi.top-vi.bottom)) {
2462                            // If the focus simply is not going to fit, then
2463                            // best is probably just to leave things as-is.
2464                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2465                                    "Too tall; leaving scrollY=" + scrollY);
2466                        } else if ((mTempRect.top-scrollY) < vi.top) {
2467                            scrollY -= vi.top - (mTempRect.top-scrollY);
2468                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2469                                    "Top covered; scrollY=" + scrollY);
2470                        } else if ((mTempRect.bottom-scrollY)
2471                                > (mView.getHeight()-vi.bottom)) {
2472                            scrollY += (mTempRect.bottom-scrollY)
2473                                    - (mView.getHeight()-vi.bottom);
2474                            if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2475                                    "Bottom covered; scrollY=" + scrollY);
2476                        }
2477                        handled = true;
2478                    }
2479                }
2480            }
2481        }
2482
2483        if (scrollY != mScrollY) {
2484            if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2485                    + mScrollY + " , new=" + scrollY);
2486            if (!immediate && mResizeBuffer == null) {
2487                if (mScroller == null) {
2488                    mScroller = new Scroller(mView.getContext());
2489                }
2490                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2491            } else if (mScroller != null) {
2492                mScroller.abortAnimation();
2493            }
2494            mScrollY = scrollY;
2495        }
2496
2497        return handled;
2498    }
2499
2500    /**
2501     * @hide
2502     */
2503    public View getAccessibilityFocusedHost() {
2504        return mAccessibilityFocusedHost;
2505    }
2506
2507    /**
2508     * @hide
2509     */
2510    public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
2511        return mAccessibilityFocusedVirtualView;
2512    }
2513
2514    void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
2515        // If we have a virtual view with accessibility focus we need
2516        // to clear the focus and invalidate the virtual view bounds.
2517        if (mAccessibilityFocusedVirtualView != null) {
2518
2519            AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
2520            View focusHost = mAccessibilityFocusedHost;
2521            focusHost.clearAccessibilityFocusNoCallbacks();
2522
2523            // Wipe the state of the current accessibility focus since
2524            // the call into the provider to clear accessibility focus
2525            // will fire an accessibility event which will end up calling
2526            // this method and we want to have clean state when this
2527            // invocation happens.
2528            mAccessibilityFocusedHost = null;
2529            mAccessibilityFocusedVirtualView = null;
2530
2531            AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
2532            if (provider != null) {
2533                // Invalidate the area of the cleared accessibility focus.
2534                focusNode.getBoundsInParent(mTempRect);
2535                focusHost.invalidate(mTempRect);
2536                // Clear accessibility focus in the virtual node.
2537                final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
2538                        focusNode.getSourceNodeId());
2539                provider.performAction(virtualNodeId,
2540                        AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
2541            }
2542            focusNode.recycle();
2543        }
2544        if (mAccessibilityFocusedHost != null) {
2545            // Clear accessibility focus in the view.
2546            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2547        }
2548
2549        // Set the new focus host and node.
2550        mAccessibilityFocusedHost = view;
2551        mAccessibilityFocusedVirtualView = node;
2552    }
2553
2554    public void requestChildFocus(View child, View focused) {
2555        checkThread();
2556
2557        if (DEBUG_INPUT_RESIZE) {
2558            Log.v(TAG, "Request child focus: focus now " + focused);
2559        }
2560
2561        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused);
2562        scheduleTraversals();
2563
2564        mFocusedView = mRealFocusedView = focused;
2565    }
2566
2567    public void clearChildFocus(View child) {
2568        checkThread();
2569
2570        if (DEBUG_INPUT_RESIZE) {
2571            Log.v(TAG, "Clearing child focus");
2572        }
2573
2574        mOldFocusedView = mFocusedView;
2575
2576        // Invoke the listener only if there is no view to take focus
2577        if (focusSearch(null, View.FOCUS_FORWARD) == null) {
2578            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null);
2579        }
2580
2581        mFocusedView = mRealFocusedView = null;
2582    }
2583
2584    @Override
2585    public ViewParent getParentForAccessibility() {
2586        return null;
2587    }
2588
2589    public void focusableViewAvailable(View v) {
2590        checkThread();
2591        if (mView != null) {
2592            if (!mView.hasFocus()) {
2593                v.requestFocus();
2594            } else {
2595                // the one case where will transfer focus away from the current one
2596                // is if the current view is a view group that prefers to give focus
2597                // to its children first AND the view is a descendant of it.
2598                mFocusedView = mView.findFocus();
2599                boolean descendantsHaveDibsOnFocus =
2600                        (mFocusedView instanceof ViewGroup) &&
2601                            (((ViewGroup) mFocusedView).getDescendantFocusability() ==
2602                                    ViewGroup.FOCUS_AFTER_DESCENDANTS);
2603                if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
2604                    // If a view gets the focus, the listener will be invoked from requestChildFocus()
2605                    v.requestFocus();
2606                }
2607            }
2608        }
2609    }
2610
2611    public void recomputeViewAttributes(View child) {
2612        checkThread();
2613        if (mView == child) {
2614            mAttachInfo.mRecomputeGlobalAttributes = true;
2615            if (!mWillDrawSoon) {
2616                scheduleTraversals();
2617            }
2618        }
2619    }
2620
2621    void dispatchDetachedFromWindow() {
2622        if (mView != null && mView.mAttachInfo != null) {
2623            if (mAttachInfo.mHardwareRenderer != null &&
2624                    mAttachInfo.mHardwareRenderer.isEnabled()) {
2625                mAttachInfo.mHardwareRenderer.validate();
2626            }
2627            mView.dispatchDetachedFromWindow();
2628        }
2629
2630        mAccessibilityInteractionConnectionManager.ensureNoConnection();
2631        mAccessibilityManager.removeAccessibilityStateChangeListener(
2632                mAccessibilityInteractionConnectionManager);
2633        removeSendWindowContentChangedCallback();
2634
2635        destroyHardwareRenderer();
2636
2637        setAccessibilityFocus(null, null);
2638
2639        mView = null;
2640        mAttachInfo.mRootView = null;
2641        mAttachInfo.mSurface = null;
2642
2643        mSurface.release();
2644
2645        if (mInputQueueCallback != null && mInputQueue != null) {
2646            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2647            mInputQueueCallback = null;
2648            mInputQueue = null;
2649        } else if (mInputEventReceiver != null) {
2650            mInputEventReceiver.dispose();
2651            mInputEventReceiver = null;
2652        }
2653        try {
2654            sWindowSession.remove(mWindow);
2655        } catch (RemoteException e) {
2656        }
2657
2658        // Dispose the input channel after removing the window so the Window Manager
2659        // doesn't interpret the input channel being closed as an abnormal termination.
2660        if (mInputChannel != null) {
2661            mInputChannel.dispose();
2662            mInputChannel = null;
2663        }
2664
2665        unscheduleTraversals();
2666    }
2667
2668    void updateConfiguration(Configuration config, boolean force) {
2669        if (DEBUG_CONFIGURATION) Log.v(TAG,
2670                "Applying new config to window "
2671                + mWindowAttributes.getTitle()
2672                + ": " + config);
2673
2674        CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2675        if (ci != null) {
2676            config = new Configuration(config);
2677            ci.applyToConfiguration(mNoncompatDensity, config);
2678        }
2679
2680        synchronized (sConfigCallbacks) {
2681            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2682                sConfigCallbacks.get(i).onConfigurationChanged(config);
2683            }
2684        }
2685        if (mView != null) {
2686            // At this point the resources have been updated to
2687            // have the most recent config, whatever that is.  Use
2688            // the one in them which may be newer.
2689            config = mView.getResources().getConfiguration();
2690            if (force || mLastConfiguration.diff(config) != 0) {
2691                mLastConfiguration.setTo(config);
2692                mView.dispatchConfigurationChanged(config);
2693            }
2694        }
2695    }
2696
2697    /**
2698     * Return true if child is an ancestor of parent, (or equal to the parent).
2699     */
2700    public static boolean isViewDescendantOf(View child, View parent) {
2701        if (child == parent) {
2702            return true;
2703        }
2704
2705        final ViewParent theParent = child.getParent();
2706        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2707    }
2708
2709    private static void forceLayout(View view) {
2710        view.forceLayout();
2711        if (view instanceof ViewGroup) {
2712            ViewGroup group = (ViewGroup) view;
2713            final int count = group.getChildCount();
2714            for (int i = 0; i < count; i++) {
2715                forceLayout(group.getChildAt(i));
2716            }
2717        }
2718    }
2719
2720    private final static int MSG_INVALIDATE = 1;
2721    private final static int MSG_INVALIDATE_RECT = 2;
2722    private final static int MSG_DIE = 3;
2723    private final static int MSG_RESIZED = 4;
2724    private final static int MSG_RESIZED_REPORT = 5;
2725    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
2726    private final static int MSG_DISPATCH_KEY = 7;
2727    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
2728    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
2729    private final static int MSG_IME_FINISHED_EVENT = 10;
2730    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
2731    private final static int MSG_FINISH_INPUT_CONNECTION = 12;
2732    private final static int MSG_CHECK_FOCUS = 13;
2733    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
2734    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
2735    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
2736    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
2737    private final static int MSG_UPDATE_CONFIGURATION = 18;
2738    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
2739    private final static int MSG_DISPATCH_SCREEN_STATE = 20;
2740    private final static int MSG_INVALIDATE_DISPLAY_LIST = 21;
2741    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 22;
2742    private final static int MSG_DISPATCH_DONE_ANIMATING = 23;
2743    private final static int MSG_INVALIDATE_WORLD = 24;
2744    private final static int MSG_WINDOW_MOVED = 25;
2745
2746    final class ViewRootHandler extends Handler {
2747        @Override
2748        public String getMessageName(Message message) {
2749            switch (message.what) {
2750                case MSG_INVALIDATE:
2751                    return "MSG_INVALIDATE";
2752                case MSG_INVALIDATE_RECT:
2753                    return "MSG_INVALIDATE_RECT";
2754                case MSG_DIE:
2755                    return "MSG_DIE";
2756                case MSG_RESIZED:
2757                    return "MSG_RESIZED";
2758                case MSG_RESIZED_REPORT:
2759                    return "MSG_RESIZED_REPORT";
2760                case MSG_WINDOW_FOCUS_CHANGED:
2761                    return "MSG_WINDOW_FOCUS_CHANGED";
2762                case MSG_DISPATCH_KEY:
2763                    return "MSG_DISPATCH_KEY";
2764                case MSG_DISPATCH_APP_VISIBILITY:
2765                    return "MSG_DISPATCH_APP_VISIBILITY";
2766                case MSG_DISPATCH_GET_NEW_SURFACE:
2767                    return "MSG_DISPATCH_GET_NEW_SURFACE";
2768                case MSG_IME_FINISHED_EVENT:
2769                    return "MSG_IME_FINISHED_EVENT";
2770                case MSG_DISPATCH_KEY_FROM_IME:
2771                    return "MSG_DISPATCH_KEY_FROM_IME";
2772                case MSG_FINISH_INPUT_CONNECTION:
2773                    return "MSG_FINISH_INPUT_CONNECTION";
2774                case MSG_CHECK_FOCUS:
2775                    return "MSG_CHECK_FOCUS";
2776                case MSG_CLOSE_SYSTEM_DIALOGS:
2777                    return "MSG_CLOSE_SYSTEM_DIALOGS";
2778                case MSG_DISPATCH_DRAG_EVENT:
2779                    return "MSG_DISPATCH_DRAG_EVENT";
2780                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
2781                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
2782                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
2783                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
2784                case MSG_UPDATE_CONFIGURATION:
2785                    return "MSG_UPDATE_CONFIGURATION";
2786                case MSG_PROCESS_INPUT_EVENTS:
2787                    return "MSG_PROCESS_INPUT_EVENTS";
2788                case MSG_DISPATCH_SCREEN_STATE:
2789                    return "MSG_DISPATCH_SCREEN_STATE";
2790                case MSG_INVALIDATE_DISPLAY_LIST:
2791                    return "MSG_INVALIDATE_DISPLAY_LIST";
2792                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
2793                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
2794                case MSG_DISPATCH_DONE_ANIMATING:
2795                    return "MSG_DISPATCH_DONE_ANIMATING";
2796                case MSG_WINDOW_MOVED:
2797                    return "MSG_WINDOW_MOVED";
2798            }
2799            return super.getMessageName(message);
2800        }
2801
2802        @Override
2803        public void handleMessage(Message msg) {
2804            switch (msg.what) {
2805            case MSG_INVALIDATE:
2806                ((View) msg.obj).invalidate();
2807                break;
2808            case MSG_INVALIDATE_RECT:
2809                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2810                info.target.invalidate(info.left, info.top, info.right, info.bottom);
2811                info.release();
2812                break;
2813            case MSG_IME_FINISHED_EVENT:
2814                handleImeFinishedEvent(msg.arg1, msg.arg2 != 0);
2815                break;
2816            case MSG_PROCESS_INPUT_EVENTS:
2817                mProcessInputEventsScheduled = false;
2818                doProcessInputEvents();
2819                break;
2820            case MSG_DISPATCH_APP_VISIBILITY:
2821                handleAppVisibility(msg.arg1 != 0);
2822                break;
2823            case MSG_DISPATCH_GET_NEW_SURFACE:
2824                handleGetNewSurface();
2825                break;
2826            case MSG_RESIZED:
2827                ResizedInfo ri = (ResizedInfo)msg.obj;
2828
2829                if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
2830                        && mPendingContentInsets.equals(ri.contentInsets)
2831                        && mPendingVisibleInsets.equals(ri.visibleInsets)
2832                        && ((ResizedInfo)msg.obj).newConfig == null) {
2833                    break;
2834                }
2835                // fall through...
2836            case MSG_RESIZED_REPORT:
2837                if (mAdded) {
2838                    Configuration config = ((ResizedInfo)msg.obj).newConfig;
2839                    if (config != null) {
2840                        updateConfiguration(config, false);
2841                    }
2842                    // TODO: Should left/top stay unchanged and only change the right/bottom?
2843                    mWinFrame.left = 0;
2844                    mWinFrame.right = msg.arg1;
2845                    mWinFrame.top = 0;
2846                    mWinFrame.bottom = msg.arg2;
2847                    mPendingContentInsets.set(((ResizedInfo)msg.obj).contentInsets);
2848                    mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
2849                    if (msg.what == MSG_RESIZED_REPORT) {
2850                        mReportNextDraw = true;
2851                    }
2852
2853                    if (mView != null) {
2854                        forceLayout(mView);
2855                    }
2856                    requestLayout();
2857                }
2858                break;
2859            case MSG_WINDOW_MOVED:
2860                if (mAdded) {
2861                    final int w = mWinFrame.width();
2862                    final int h = mWinFrame.height();
2863                    final int l = msg.arg1;
2864                    final int t = msg.arg2;
2865                    mWinFrame.left = l;
2866                    mWinFrame.right = l + w;
2867                    mWinFrame.top = t;
2868                    mWinFrame.bottom = t + h;
2869
2870                    if (mView != null) {
2871                        forceLayout(mView);
2872                    }
2873                    requestLayout();
2874                }
2875                break;
2876            case MSG_WINDOW_FOCUS_CHANGED: {
2877                if (mAdded) {
2878                    boolean hasWindowFocus = msg.arg1 != 0;
2879                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
2880
2881                    profileRendering(hasWindowFocus);
2882
2883                    if (hasWindowFocus) {
2884                        boolean inTouchMode = msg.arg2 != 0;
2885                        ensureTouchModeLocally(inTouchMode);
2886
2887                        if (mAttachInfo.mHardwareRenderer != null &&
2888                                mSurface != null && mSurface.isValid()) {
2889                            mFullRedrawNeeded = true;
2890                            try {
2891                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2892                                        mHolder.getSurface());
2893                            } catch (Surface.OutOfResourcesException e) {
2894                                Log.e(TAG, "OutOfResourcesException locking surface", e);
2895                                try {
2896                                    if (!sWindowSession.outOfMemory(mWindow)) {
2897                                        Slog.w(TAG, "No processes killed for memory; killing self");
2898                                        Process.killProcess(Process.myPid());
2899                                    }
2900                                } catch (RemoteException ex) {
2901                                }
2902                                // Retry in a bit.
2903                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
2904                                return;
2905                            }
2906                        }
2907                    }
2908
2909                    mLastWasImTarget = WindowManager.LayoutParams
2910                            .mayUseInputMethod(mWindowAttributes.flags);
2911
2912                    InputMethodManager imm = InputMethodManager.peekInstance();
2913                    if (mView != null) {
2914                        if (hasWindowFocus && imm != null && mLastWasImTarget) {
2915                            imm.startGettingWindowFocus(mView);
2916                        }
2917                        mAttachInfo.mKeyDispatchState.reset();
2918                        mView.dispatchWindowFocusChanged(hasWindowFocus);
2919                    }
2920
2921                    // Note: must be done after the focus change callbacks,
2922                    // so all of the view state is set up correctly.
2923                    if (hasWindowFocus) {
2924                        if (imm != null && mLastWasImTarget) {
2925                            imm.onWindowFocus(mView, mView.findFocus(),
2926                                    mWindowAttributes.softInputMode,
2927                                    !mHasHadWindowFocus, mWindowAttributes.flags);
2928                        }
2929                        // Clear the forward bit.  We can just do this directly, since
2930                        // the window manager doesn't care about it.
2931                        mWindowAttributes.softInputMode &=
2932                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2933                        ((WindowManager.LayoutParams)mView.getLayoutParams())
2934                                .softInputMode &=
2935                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2936                        mHasHadWindowFocus = true;
2937                    }
2938
2939                    setAccessibilityFocus(null, null);
2940
2941                    if (mView != null && mAccessibilityManager.isEnabled()) {
2942                        if (hasWindowFocus) {
2943                            mView.sendAccessibilityEvent(
2944                                    AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2945                        }
2946                    }
2947                }
2948            } break;
2949            case MSG_DIE:
2950                doDie();
2951                break;
2952            case MSG_DISPATCH_KEY: {
2953                KeyEvent event = (KeyEvent)msg.obj;
2954                enqueueInputEvent(event, null, 0, true);
2955            } break;
2956            case MSG_DISPATCH_KEY_FROM_IME: {
2957                if (LOCAL_LOGV) Log.v(
2958                    TAG, "Dispatching key "
2959                    + msg.obj + " from IME to " + mView);
2960                KeyEvent event = (KeyEvent)msg.obj;
2961                if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2962                    // The IME is trying to say this event is from the
2963                    // system!  Bad bad bad!
2964                    //noinspection UnusedAssignment
2965                    event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
2966                }
2967                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
2968            } break;
2969            case MSG_FINISH_INPUT_CONNECTION: {
2970                InputMethodManager imm = InputMethodManager.peekInstance();
2971                if (imm != null) {
2972                    imm.reportFinishInputConnection((InputConnection)msg.obj);
2973                }
2974            } break;
2975            case MSG_CHECK_FOCUS: {
2976                InputMethodManager imm = InputMethodManager.peekInstance();
2977                if (imm != null) {
2978                    imm.checkFocus();
2979                }
2980            } break;
2981            case MSG_CLOSE_SYSTEM_DIALOGS: {
2982                if (mView != null) {
2983                    mView.onCloseSystemDialogs((String)msg.obj);
2984                }
2985            } break;
2986            case MSG_DISPATCH_DRAG_EVENT:
2987            case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
2988                DragEvent event = (DragEvent)msg.obj;
2989                event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
2990                handleDragEvent(event);
2991            } break;
2992            case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
2993                handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj);
2994            } break;
2995            case MSG_UPDATE_CONFIGURATION: {
2996                Configuration config = (Configuration)msg.obj;
2997                if (config.isOtherSeqNewer(mLastConfiguration)) {
2998                    config = mLastConfiguration;
2999                }
3000                updateConfiguration(config, false);
3001            } break;
3002            case MSG_DISPATCH_SCREEN_STATE: {
3003                if (mView != null) {
3004                    handleScreenStateChange(msg.arg1 == 1);
3005                }
3006            } break;
3007            case MSG_INVALIDATE_DISPLAY_LIST: {
3008                invalidateDisplayLists();
3009            } break;
3010            case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3011                setAccessibilityFocus(null, null);
3012            } break;
3013            case MSG_DISPATCH_DONE_ANIMATING: {
3014                handleDispatchDoneAnimating();
3015            } break;
3016            case MSG_INVALIDATE_WORLD: {
3017                invalidateWorld(mView);
3018            } break;
3019            }
3020        }
3021    }
3022
3023    final ViewRootHandler mHandler = new ViewRootHandler();
3024
3025    /**
3026     * Something in the current window tells us we need to change the touch mode.  For
3027     * example, we are not in touch mode, and the user touches the screen.
3028     *
3029     * If the touch mode has changed, tell the window manager, and handle it locally.
3030     *
3031     * @param inTouchMode Whether we want to be in touch mode.
3032     * @return True if the touch mode changed and focus changed was changed as a result
3033     */
3034    boolean ensureTouchMode(boolean inTouchMode) {
3035        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3036                + "touch mode is " + mAttachInfo.mInTouchMode);
3037        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3038
3039        // tell the window manager
3040        try {
3041            sWindowSession.setInTouchMode(inTouchMode);
3042        } catch (RemoteException e) {
3043            throw new RuntimeException(e);
3044        }
3045
3046        // handle the change
3047        return ensureTouchModeLocally(inTouchMode);
3048    }
3049
3050    /**
3051     * Ensure that the touch mode for this window is set, and if it is changing,
3052     * take the appropriate action.
3053     * @param inTouchMode Whether we want to be in touch mode.
3054     * @return True if the touch mode changed and focus changed was changed as a result
3055     */
3056    private boolean ensureTouchModeLocally(boolean inTouchMode) {
3057        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3058                + "touch mode is " + mAttachInfo.mInTouchMode);
3059
3060        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3061
3062        mAttachInfo.mInTouchMode = inTouchMode;
3063        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3064
3065        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3066    }
3067
3068    private boolean enterTouchMode() {
3069        if (mView != null) {
3070            if (mView.hasFocus()) {
3071                // note: not relying on mFocusedView here because this could
3072                // be when the window is first being added, and mFocused isn't
3073                // set yet.
3074                final View focused = mView.findFocus();
3075                if (focused != null && !focused.isFocusableInTouchMode()) {
3076
3077                    final ViewGroup ancestorToTakeFocus =
3078                            findAncestorToTakeFocusInTouchMode(focused);
3079                    if (ancestorToTakeFocus != null) {
3080                        // there is an ancestor that wants focus after its descendants that
3081                        // is focusable in touch mode.. give it focus
3082                        return ancestorToTakeFocus.requestFocus();
3083                    } else {
3084                        // nothing appropriate to have focus in touch mode, clear it out
3085                        mView.unFocus();
3086                        mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
3087                        mFocusedView = null;
3088                        mOldFocusedView = null;
3089                        return true;
3090                    }
3091                }
3092            }
3093        }
3094        return false;
3095    }
3096
3097    /**
3098     * Find an ancestor of focused that wants focus after its descendants and is
3099     * focusable in touch mode.
3100     * @param focused The currently focused view.
3101     * @return An appropriate view, or null if no such view exists.
3102     */
3103    private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3104        ViewParent parent = focused.getParent();
3105        while (parent instanceof ViewGroup) {
3106            final ViewGroup vgParent = (ViewGroup) parent;
3107            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3108                    && vgParent.isFocusableInTouchMode()) {
3109                return vgParent;
3110            }
3111            if (vgParent.isRootNamespace()) {
3112                return null;
3113            } else {
3114                parent = vgParent.getParent();
3115            }
3116        }
3117        return null;
3118    }
3119
3120    private boolean leaveTouchMode() {
3121        if (mView != null) {
3122            if (mView.hasFocus()) {
3123                // i learned the hard way to not trust mFocusedView :)
3124                mFocusedView = mView.findFocus();
3125                if (!(mFocusedView instanceof ViewGroup)) {
3126                    // some view has focus, let it keep it
3127                    return false;
3128                } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
3129                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3130                    // some view group has focus, and doesn't prefer its children
3131                    // over itself for focus, so let them keep it.
3132                    return false;
3133                }
3134            }
3135
3136            // find the best view to give focus to in this brave new non-touch-mode
3137            // world
3138            final View focused = focusSearch(null, View.FOCUS_DOWN);
3139            if (focused != null) {
3140                return focused.requestFocus(View.FOCUS_DOWN);
3141            }
3142        }
3143        return false;
3144    }
3145
3146    private void deliverInputEvent(QueuedInputEvent q) {
3147        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
3148        try {
3149            if (q.mEvent instanceof KeyEvent) {
3150                deliverKeyEvent(q);
3151            } else {
3152                final int source = q.mEvent.getSource();
3153                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3154                    deliverPointerEvent(q);
3155                } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3156                    deliverTrackballEvent(q);
3157                } else {
3158                    deliverGenericMotionEvent(q);
3159                }
3160            }
3161        } finally {
3162            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3163        }
3164    }
3165
3166    private void deliverPointerEvent(QueuedInputEvent q) {
3167        final MotionEvent event = (MotionEvent)q.mEvent;
3168        final boolean isTouchEvent = event.isTouchEvent();
3169        if (mInputEventConsistencyVerifier != null) {
3170            if (isTouchEvent) {
3171                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
3172            } else {
3173                mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3174            }
3175        }
3176
3177        // If there is no view, then the event will not be handled.
3178        if (mView == null || !mAdded) {
3179            finishInputEvent(q, false);
3180            return;
3181        }
3182
3183        // Translate the pointer event for compatibility, if needed.
3184        if (mTranslator != null) {
3185            mTranslator.translateEventInScreenToAppWindow(event);
3186        }
3187
3188        // Enter touch mode on down or scroll.
3189        final int action = event.getAction();
3190        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3191            ensureTouchMode(true);
3192        }
3193
3194        // Offset the scroll position.
3195        if (mCurScrollY != 0) {
3196            event.offsetLocation(0, mCurScrollY);
3197        }
3198        if (MEASURE_LATENCY) {
3199            lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
3200        }
3201
3202        // Remember the touch position for possible drag-initiation.
3203        if (isTouchEvent) {
3204            mLastTouchPoint.x = event.getRawX();
3205            mLastTouchPoint.y = event.getRawY();
3206        }
3207
3208        // Dispatch touch to view hierarchy.
3209        boolean handled = mView.dispatchPointerEvent(event);
3210        if (MEASURE_LATENCY) {
3211            lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
3212        }
3213        if (handled) {
3214            finishInputEvent(q, true);
3215            return;
3216        }
3217
3218        // Pointer event was unhandled.
3219        finishInputEvent(q, false);
3220    }
3221
3222    private void deliverTrackballEvent(QueuedInputEvent q) {
3223        final MotionEvent event = (MotionEvent)q.mEvent;
3224        if (mInputEventConsistencyVerifier != null) {
3225            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
3226        }
3227
3228        // If there is no view, then the event will not be handled.
3229        if (mView == null || !mAdded) {
3230            finishInputEvent(q, false);
3231            return;
3232        }
3233
3234        // Deliver the trackball event to the view.
3235        if (mView.dispatchTrackballEvent(event)) {
3236            // If we reach this, we delivered a trackball event to mView and
3237            // mView consumed it. Because we will not translate the trackball
3238            // event into a key event, touch mode will not exit, so we exit
3239            // touch mode here.
3240            ensureTouchMode(false);
3241
3242            finishInputEvent(q, true);
3243            mLastTrackballTime = Integer.MIN_VALUE;
3244            return;
3245        }
3246
3247        // Translate the trackball event into DPAD keys and try to deliver those.
3248        final TrackballAxis x = mTrackballAxisX;
3249        final TrackballAxis y = mTrackballAxisY;
3250
3251        long curTime = SystemClock.uptimeMillis();
3252        if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
3253            // It has been too long since the last movement,
3254            // so restart at the beginning.
3255            x.reset(0);
3256            y.reset(0);
3257            mLastTrackballTime = curTime;
3258        }
3259
3260        final int action = event.getAction();
3261        final int metaState = event.getMetaState();
3262        switch (action) {
3263            case MotionEvent.ACTION_DOWN:
3264                x.reset(2);
3265                y.reset(2);
3266                enqueueInputEvent(new KeyEvent(curTime, curTime,
3267                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3268                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3269                        InputDevice.SOURCE_KEYBOARD));
3270                break;
3271            case MotionEvent.ACTION_UP:
3272                x.reset(2);
3273                y.reset(2);
3274                enqueueInputEvent(new KeyEvent(curTime, curTime,
3275                        KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3276                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3277                        InputDevice.SOURCE_KEYBOARD));
3278                break;
3279        }
3280
3281        if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
3282                + x.step + " dir=" + x.dir + " acc=" + x.acceleration
3283                + " move=" + event.getX()
3284                + " / Y=" + y.position + " step="
3285                + y.step + " dir=" + y.dir + " acc=" + y.acceleration
3286                + " move=" + event.getY());
3287        final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
3288        final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
3289
3290        // Generate DPAD events based on the trackball movement.
3291        // We pick the axis that has moved the most as the direction of
3292        // the DPAD.  When we generate DPAD events for one axis, then the
3293        // other axis is reset -- we don't want to perform DPAD jumps due
3294        // to slight movements in the trackball when making major movements
3295        // along the other axis.
3296        int keycode = 0;
3297        int movement = 0;
3298        float accel = 1;
3299        if (xOff > yOff) {
3300            movement = x.generate((2/event.getXPrecision()));
3301            if (movement != 0) {
3302                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
3303                        : KeyEvent.KEYCODE_DPAD_LEFT;
3304                accel = x.acceleration;
3305                y.reset(2);
3306            }
3307        } else if (yOff > 0) {
3308            movement = y.generate((2/event.getYPrecision()));
3309            if (movement != 0) {
3310                keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
3311                        : KeyEvent.KEYCODE_DPAD_UP;
3312                accel = y.acceleration;
3313                x.reset(2);
3314            }
3315        }
3316
3317        if (keycode != 0) {
3318            if (movement < 0) movement = -movement;
3319            int accelMovement = (int)(movement * accel);
3320            if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
3321                    + " accelMovement=" + accelMovement
3322                    + " accel=" + accel);
3323            if (accelMovement > movement) {
3324                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3325                        + keycode);
3326                movement--;
3327                int repeatCount = accelMovement - movement;
3328                enqueueInputEvent(new KeyEvent(curTime, curTime,
3329                        KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
3330                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3331                        InputDevice.SOURCE_KEYBOARD));
3332            }
3333            while (movement > 0) {
3334                if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3335                        + keycode);
3336                movement--;
3337                curTime = SystemClock.uptimeMillis();
3338                enqueueInputEvent(new KeyEvent(curTime, curTime,
3339                        KeyEvent.ACTION_DOWN, keycode, 0, metaState,
3340                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3341                        InputDevice.SOURCE_KEYBOARD));
3342                enqueueInputEvent(new KeyEvent(curTime, curTime,
3343                        KeyEvent.ACTION_UP, keycode, 0, metaState,
3344                        KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3345                        InputDevice.SOURCE_KEYBOARD));
3346            }
3347            mLastTrackballTime = curTime;
3348        }
3349
3350        // Unfortunately we can't tell whether the application consumed the keys, so
3351        // we always consider the trackball event handled.
3352        finishInputEvent(q, true);
3353    }
3354
3355    private void deliverGenericMotionEvent(QueuedInputEvent q) {
3356        final MotionEvent event = (MotionEvent)q.mEvent;
3357        if (mInputEventConsistencyVerifier != null) {
3358            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3359        }
3360
3361        final int source = event.getSource();
3362        final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
3363
3364        // If there is no view, then the event will not be handled.
3365        if (mView == null || !mAdded) {
3366            if (isJoystick) {
3367                updateJoystickDirection(event, false);
3368            }
3369            finishInputEvent(q, false);
3370            return;
3371        }
3372
3373        // Deliver the event to the view.
3374        if (mView.dispatchGenericMotionEvent(event)) {
3375            if (isJoystick) {
3376                updateJoystickDirection(event, false);
3377            }
3378            finishInputEvent(q, true);
3379            return;
3380        }
3381
3382        if (isJoystick) {
3383            // Translate the joystick event into DPAD keys and try to deliver those.
3384            updateJoystickDirection(event, true);
3385            finishInputEvent(q, true);
3386        } else {
3387            finishInputEvent(q, false);
3388        }
3389    }
3390
3391    private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
3392        final long time = event.getEventTime();
3393        final int metaState = event.getMetaState();
3394        final int deviceId = event.getDeviceId();
3395        final int source = event.getSource();
3396
3397        int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
3398        if (xDirection == 0) {
3399            xDirection = joystickAxisValueToDirection(event.getX());
3400        }
3401
3402        int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
3403        if (yDirection == 0) {
3404            yDirection = joystickAxisValueToDirection(event.getY());
3405        }
3406
3407        if (xDirection != mLastJoystickXDirection) {
3408            if (mLastJoystickXKeyCode != 0) {
3409                enqueueInputEvent(new KeyEvent(time, time,
3410                        KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
3411                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3412                mLastJoystickXKeyCode = 0;
3413            }
3414
3415            mLastJoystickXDirection = xDirection;
3416
3417            if (xDirection != 0 && synthesizeNewKeys) {
3418                mLastJoystickXKeyCode = xDirection > 0
3419                        ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3420                enqueueInputEvent(new KeyEvent(time, time,
3421                        KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3422                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3423            }
3424        }
3425
3426        if (yDirection != mLastJoystickYDirection) {
3427            if (mLastJoystickYKeyCode != 0) {
3428                enqueueInputEvent(new KeyEvent(time, time,
3429                        KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3430                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3431                mLastJoystickYKeyCode = 0;
3432            }
3433
3434            mLastJoystickYDirection = yDirection;
3435
3436            if (yDirection != 0 && synthesizeNewKeys) {
3437                mLastJoystickYKeyCode = yDirection > 0
3438                        ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3439                enqueueInputEvent(new KeyEvent(time, time,
3440                        KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3441                        deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3442            }
3443        }
3444    }
3445
3446    private static int joystickAxisValueToDirection(float value) {
3447        if (value >= 0.5f) {
3448            return 1;
3449        } else if (value <= -0.5f) {
3450            return -1;
3451        } else {
3452            return 0;
3453        }
3454    }
3455
3456    /**
3457     * Returns true if the key is used for keyboard navigation.
3458     * @param keyEvent The key event.
3459     * @return True if the key is used for keyboard navigation.
3460     */
3461    private static boolean isNavigationKey(KeyEvent keyEvent) {
3462        switch (keyEvent.getKeyCode()) {
3463        case KeyEvent.KEYCODE_DPAD_LEFT:
3464        case KeyEvent.KEYCODE_DPAD_RIGHT:
3465        case KeyEvent.KEYCODE_DPAD_UP:
3466        case KeyEvent.KEYCODE_DPAD_DOWN:
3467        case KeyEvent.KEYCODE_DPAD_CENTER:
3468        case KeyEvent.KEYCODE_PAGE_UP:
3469        case KeyEvent.KEYCODE_PAGE_DOWN:
3470        case KeyEvent.KEYCODE_MOVE_HOME:
3471        case KeyEvent.KEYCODE_MOVE_END:
3472        case KeyEvent.KEYCODE_TAB:
3473        case KeyEvent.KEYCODE_SPACE:
3474        case KeyEvent.KEYCODE_ENTER:
3475            return true;
3476        }
3477        return false;
3478    }
3479
3480    /**
3481     * Returns true if the key is used for typing.
3482     * @param keyEvent The key event.
3483     * @return True if the key is used for typing.
3484     */
3485    private static boolean isTypingKey(KeyEvent keyEvent) {
3486        return keyEvent.getUnicodeChar() > 0;
3487    }
3488
3489    /**
3490     * See if the key event means we should leave touch mode (and leave touch mode if so).
3491     * @param event The key event.
3492     * @return Whether this key event should be consumed (meaning the act of
3493     *   leaving touch mode alone is considered the event).
3494     */
3495    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3496        // Only relevant in touch mode.
3497        if (!mAttachInfo.mInTouchMode) {
3498            return false;
3499        }
3500
3501        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3502        final int action = event.getAction();
3503        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3504            return false;
3505        }
3506
3507        // Don't leave touch mode if the IME told us not to.
3508        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3509            return false;
3510        }
3511
3512        // If the key can be used for keyboard navigation then leave touch mode
3513        // and select a focused view if needed (in ensureTouchMode).
3514        // When a new focused view is selected, we consume the navigation key because
3515        // navigation doesn't make much sense unless a view already has focus so
3516        // the key's purpose is to set focus.
3517        if (isNavigationKey(event)) {
3518            return ensureTouchMode(false);
3519        }
3520
3521        // If the key can be used for typing then leave touch mode
3522        // and select a focused view if needed (in ensureTouchMode).
3523        // Always allow the view to process the typing key.
3524        if (isTypingKey(event)) {
3525            ensureTouchMode(false);
3526            return false;
3527        }
3528
3529        return false;
3530    }
3531
3532    private void deliverKeyEvent(QueuedInputEvent q) {
3533        final KeyEvent event = (KeyEvent)q.mEvent;
3534        if (mInputEventConsistencyVerifier != null) {
3535            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3536        }
3537
3538        if ((q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3539            // If there is no view, then the event will not be handled.
3540            if (mView == null || !mAdded) {
3541                finishInputEvent(q, false);
3542                return;
3543            }
3544
3545            if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3546
3547            // Perform predispatching before the IME.
3548            if (mView.dispatchKeyEventPreIme(event)) {
3549                finishInputEvent(q, true);
3550                return;
3551            }
3552
3553            // Dispatch to the IME before propagating down the view hierarchy.
3554            // The IME will eventually call back into handleImeFinishedEvent.
3555            if (mLastWasImTarget) {
3556                InputMethodManager imm = InputMethodManager.peekInstance();
3557                if (imm != null) {
3558                    final int seq = event.getSequenceNumber();
3559                    if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3560                            + seq + " event=" + event);
3561                    imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
3562                    return;
3563                }
3564            }
3565        }
3566
3567        // Not dispatching to IME, continue with post IME actions.
3568        deliverKeyEventPostIme(q);
3569    }
3570
3571    void handleImeFinishedEvent(int seq, boolean handled) {
3572        final QueuedInputEvent q = mCurrentInputEvent;
3573        if (q != null && q.mEvent.getSequenceNumber() == seq) {
3574            final KeyEvent event = (KeyEvent)q.mEvent;
3575            if (DEBUG_IMF) {
3576                Log.v(TAG, "IME finished event: seq=" + seq
3577                        + " handled=" + handled + " event=" + event);
3578            }
3579            if (handled) {
3580                finishInputEvent(q, true);
3581            } else {
3582                deliverKeyEventPostIme(q);
3583            }
3584        } else {
3585            if (DEBUG_IMF) {
3586                Log.v(TAG, "IME finished event: seq=" + seq
3587                        + " handled=" + handled + ", event not found!");
3588            }
3589        }
3590    }
3591
3592    private void deliverKeyEventPostIme(QueuedInputEvent q) {
3593        final KeyEvent event = (KeyEvent)q.mEvent;
3594
3595        // If the view went away, then the event will not be handled.
3596        if (mView == null || !mAdded) {
3597            finishInputEvent(q, false);
3598            return;
3599        }
3600
3601        // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3602        if (checkForLeavingTouchModeAndConsume(event)) {
3603            finishInputEvent(q, true);
3604            return;
3605        }
3606
3607        // Make sure the fallback event policy sees all keys that will be delivered to the
3608        // view hierarchy.
3609        mFallbackEventHandler.preDispatchKeyEvent(event);
3610
3611        // Deliver the key to the view hierarchy.
3612        if (mView.dispatchKeyEvent(event)) {
3613            finishInputEvent(q, true);
3614            return;
3615        }
3616
3617        // If the Control modifier is held, try to interpret the key as a shortcut.
3618        if (event.getAction() == KeyEvent.ACTION_DOWN
3619                && event.isCtrlPressed()
3620                && event.getRepeatCount() == 0
3621                && !KeyEvent.isModifierKey(event.getKeyCode())) {
3622            if (mView.dispatchKeyShortcutEvent(event)) {
3623                finishInputEvent(q, true);
3624                return;
3625            }
3626        }
3627
3628        // Apply the fallback event policy.
3629        if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3630            finishInputEvent(q, true);
3631            return;
3632        }
3633
3634        // Handle automatic focus changes.
3635        if (event.getAction() == KeyEvent.ACTION_DOWN) {
3636            int direction = 0;
3637            switch (event.getKeyCode()) {
3638                case KeyEvent.KEYCODE_DPAD_LEFT:
3639                    if (event.hasNoModifiers()) {
3640                        direction = View.FOCUS_LEFT;
3641                    }
3642                    break;
3643                case KeyEvent.KEYCODE_DPAD_RIGHT:
3644                    if (event.hasNoModifiers()) {
3645                        direction = View.FOCUS_RIGHT;
3646                    }
3647                    break;
3648                case KeyEvent.KEYCODE_DPAD_UP:
3649                    if (event.hasNoModifiers()) {
3650                        direction = View.FOCUS_UP;
3651                    }
3652                    break;
3653                case KeyEvent.KEYCODE_DPAD_DOWN:
3654                    if (event.hasNoModifiers()) {
3655                        direction = View.FOCUS_DOWN;
3656                    }
3657                    break;
3658                case KeyEvent.KEYCODE_TAB:
3659                    if (event.hasNoModifiers()) {
3660                        direction = View.FOCUS_FORWARD;
3661                    } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3662                        direction = View.FOCUS_BACKWARD;
3663                    }
3664                    break;
3665            }
3666            if (direction != 0) {
3667                View focused = mView.findFocus();
3668                if (focused != null) {
3669                    View v = focused.focusSearch(direction);
3670                    if (v != null && v != focused) {
3671                        // do the math the get the interesting rect
3672                        // of previous focused into the coord system of
3673                        // newly focused view
3674                        focused.getFocusedRect(mTempRect);
3675                        if (mView instanceof ViewGroup) {
3676                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3677                                    focused, mTempRect);
3678                            ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3679                                    v, mTempRect);
3680                        }
3681                        if (v.requestFocus(direction, mTempRect)) {
3682                            playSoundEffect(SoundEffectConstants
3683                                    .getContantForFocusDirection(direction));
3684                            finishInputEvent(q, true);
3685                            return;
3686                        }
3687                    }
3688
3689                    // Give the focused view a last chance to handle the dpad key.
3690                    if (mView.dispatchUnhandledMove(focused, direction)) {
3691                        finishInputEvent(q, true);
3692                        return;
3693                    }
3694                }
3695            }
3696        }
3697
3698        // Key was unhandled.
3699        finishInputEvent(q, false);
3700    }
3701
3702    /* drag/drop */
3703    void setLocalDragState(Object obj) {
3704        mLocalDragState = obj;
3705    }
3706
3707    private void handleDragEvent(DragEvent event) {
3708        // From the root, only drag start/end/location are dispatched.  entered/exited
3709        // are determined and dispatched by the viewgroup hierarchy, who then report
3710        // that back here for ultimate reporting back to the framework.
3711        if (mView != null && mAdded) {
3712            final int what = event.mAction;
3713
3714            if (what == DragEvent.ACTION_DRAG_EXITED) {
3715                // A direct EXITED event means that the window manager knows we've just crossed
3716                // a window boundary, so the current drag target within this one must have
3717                // just been exited.  Send it the usual notifications and then we're done
3718                // for now.
3719                mView.dispatchDragEvent(event);
3720            } else {
3721                // Cache the drag description when the operation starts, then fill it in
3722                // on subsequent calls as a convenience
3723                if (what == DragEvent.ACTION_DRAG_STARTED) {
3724                    mCurrentDragView = null;    // Start the current-recipient tracking
3725                    mDragDescription = event.mClipDescription;
3726                } else {
3727                    event.mClipDescription = mDragDescription;
3728                }
3729
3730                // For events with a [screen] location, translate into window coordinates
3731                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3732                    mDragPoint.set(event.mX, event.mY);
3733                    if (mTranslator != null) {
3734                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3735                    }
3736
3737                    if (mCurScrollY != 0) {
3738                        mDragPoint.offset(0, mCurScrollY);
3739                    }
3740
3741                    event.mX = mDragPoint.x;
3742                    event.mY = mDragPoint.y;
3743                }
3744
3745                // Remember who the current drag target is pre-dispatch
3746                final View prevDragView = mCurrentDragView;
3747
3748                // Now dispatch the drag/drop event
3749                boolean result = mView.dispatchDragEvent(event);
3750
3751                // If we changed apparent drag target, tell the OS about it
3752                if (prevDragView != mCurrentDragView) {
3753                    try {
3754                        if (prevDragView != null) {
3755                            sWindowSession.dragRecipientExited(mWindow);
3756                        }
3757                        if (mCurrentDragView != null) {
3758                            sWindowSession.dragRecipientEntered(mWindow);
3759                        }
3760                    } catch (RemoteException e) {
3761                        Slog.e(TAG, "Unable to note drag target change");
3762                    }
3763                }
3764
3765                // Report the drop result when we're done
3766                if (what == DragEvent.ACTION_DROP) {
3767                    mDragDescription = null;
3768                    try {
3769                        Log.i(TAG, "Reporting drop result: " + result);
3770                        sWindowSession.reportDropResult(mWindow, result);
3771                    } catch (RemoteException e) {
3772                        Log.e(TAG, "Unable to report drop result");
3773                    }
3774                }
3775
3776                // When the drag operation ends, release any local state object
3777                // that may have been in use
3778                if (what == DragEvent.ACTION_DRAG_ENDED) {
3779                    setLocalDragState(null);
3780                }
3781            }
3782        }
3783        event.recycle();
3784    }
3785
3786    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
3787        if (mSeq != args.seq) {
3788            // The sequence has changed, so we need to update our value and make
3789            // sure to do a traversal afterward so the window manager is given our
3790            // most recent data.
3791            mSeq = args.seq;
3792            mAttachInfo.mForceReportNewAttributes = true;
3793            scheduleTraversals();
3794        }
3795        if (mView == null) return;
3796        if (args.localChanges != 0) {
3797            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
3798        }
3799        if (mAttachInfo != null) {
3800            int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
3801            if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
3802                mAttachInfo.mGlobalSystemUiVisibility = visibility;
3803                mView.dispatchSystemUiVisibilityChanged(visibility);
3804            }
3805        }
3806    }
3807
3808    public void handleDispatchDoneAnimating() {
3809        if (mWindowsAnimating) {
3810            mWindowsAnimating = false;
3811            if (!mDirty.isEmpty() || mIsAnimating)  {
3812                scheduleTraversals();
3813            }
3814        }
3815    }
3816
3817    public void getLastTouchPoint(Point outLocation) {
3818        outLocation.x = (int) mLastTouchPoint.x;
3819        outLocation.y = (int) mLastTouchPoint.y;
3820    }
3821
3822    public void setDragFocus(View newDragTarget) {
3823        if (mCurrentDragView != newDragTarget) {
3824            mCurrentDragView = newDragTarget;
3825        }
3826    }
3827
3828    private AudioManager getAudioManager() {
3829        if (mView == null) {
3830            throw new IllegalStateException("getAudioManager called when there is no mView");
3831        }
3832        if (mAudioManager == null) {
3833            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3834        }
3835        return mAudioManager;
3836    }
3837
3838    public AccessibilityInteractionController getAccessibilityInteractionController() {
3839        if (mView == null) {
3840            throw new IllegalStateException("getAccessibilityInteractionController"
3841                    + " called when there is no mView");
3842        }
3843        if (mAccessibilityInteractionController == null) {
3844            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
3845        }
3846        return mAccessibilityInteractionController;
3847    }
3848
3849    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3850            boolean insetsPending) throws RemoteException {
3851
3852        float appScale = mAttachInfo.mApplicationScale;
3853        boolean restore = false;
3854        if (params != null && mTranslator != null) {
3855            restore = true;
3856            params.backup();
3857            mTranslator.translateWindowLayout(params);
3858        }
3859        if (params != null) {
3860            if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
3861        }
3862        mPendingConfiguration.seq = 0;
3863        //Log.d(TAG, ">>>>>> CALLING relayout");
3864        if (params != null && mOrigWindowType != params.type) {
3865            // For compatibility with old apps, don't crash here.
3866            if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
3867                Slog.w(TAG, "Window type can not be changed after "
3868                        + "the window is added; ignoring change of " + mView);
3869                params.type = mOrigWindowType;
3870            }
3871        }
3872        int relayoutResult = sWindowSession.relayout(
3873                mWindow, mSeq, params,
3874                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3875                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
3876                viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0,
3877                mWinFrame, mPendingContentInsets, mPendingVisibleInsets,
3878                mPendingConfiguration, mSurface);
3879        //Log.d(TAG, "<<<<<< BACK FROM relayout");
3880        if (restore) {
3881            params.restore();
3882        }
3883
3884        if (mTranslator != null) {
3885            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3886            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3887            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
3888        }
3889        return relayoutResult;
3890    }
3891
3892    /**
3893     * {@inheritDoc}
3894     */
3895    public void playSoundEffect(int effectId) {
3896        checkThread();
3897
3898        try {
3899            final AudioManager audioManager = getAudioManager();
3900
3901            switch (effectId) {
3902                case SoundEffectConstants.CLICK:
3903                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3904                    return;
3905                case SoundEffectConstants.NAVIGATION_DOWN:
3906                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3907                    return;
3908                case SoundEffectConstants.NAVIGATION_LEFT:
3909                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3910                    return;
3911                case SoundEffectConstants.NAVIGATION_RIGHT:
3912                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3913                    return;
3914                case SoundEffectConstants.NAVIGATION_UP:
3915                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3916                    return;
3917                default:
3918                    throw new IllegalArgumentException("unknown effect id " + effectId +
3919                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
3920            }
3921        } catch (IllegalStateException e) {
3922            // Exception thrown by getAudioManager() when mView is null
3923            Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3924            e.printStackTrace();
3925        }
3926    }
3927
3928    /**
3929     * {@inheritDoc}
3930     */
3931    public boolean performHapticFeedback(int effectId, boolean always) {
3932        try {
3933            return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3934        } catch (RemoteException e) {
3935            return false;
3936        }
3937    }
3938
3939    /**
3940     * {@inheritDoc}
3941     */
3942    public View focusSearch(View focused, int direction) {
3943        checkThread();
3944        if (!(mView instanceof ViewGroup)) {
3945            return null;
3946        }
3947        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3948    }
3949
3950    public void debug() {
3951        mView.debug();
3952    }
3953
3954    public void dumpGfxInfo(int[] info) {
3955        info[0] = info[1] = 0;
3956        if (mView != null) {
3957            getGfxInfo(mView, info);
3958        }
3959    }
3960
3961    private static void getGfxInfo(View view, int[] info) {
3962        DisplayList displayList = view.mDisplayList;
3963        info[0]++;
3964        if (displayList != null) {
3965            info[1] += displayList.getSize();
3966        }
3967
3968        if (view instanceof ViewGroup) {
3969            ViewGroup group = (ViewGroup) view;
3970
3971            int count = group.getChildCount();
3972            for (int i = 0; i < count; i++) {
3973                getGfxInfo(group.getChildAt(i), info);
3974            }
3975        }
3976    }
3977
3978    public void die(boolean immediate) {
3979        if (immediate) {
3980            doDie();
3981        } else {
3982            if (!mIsDrawing) {
3983                destroyHardwareRenderer();
3984            } else {
3985                Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
3986                        "  window=" + this + ", title=" + mWindowAttributes.getTitle());
3987            }
3988            mHandler.sendEmptyMessage(MSG_DIE);
3989        }
3990    }
3991
3992    void doDie() {
3993        checkThread();
3994        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
3995        synchronized (this) {
3996            if (mAdded) {
3997                dispatchDetachedFromWindow();
3998            }
3999
4000            if (mAdded && !mFirst) {
4001                destroyHardwareRenderer();
4002
4003                if (mView != null) {
4004                    int viewVisibility = mView.getVisibility();
4005                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
4006                    if (mWindowAttributesChanged || viewVisibilityChanged) {
4007                        // If layout params have been changed, first give them
4008                        // to the window manager to make sure it has the correct
4009                        // animation info.
4010                        try {
4011                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
4012                                    & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) {
4013                                sWindowSession.finishDrawing(mWindow);
4014                            }
4015                        } catch (RemoteException e) {
4016                        }
4017                    }
4018
4019                    mSurface.release();
4020                }
4021            }
4022
4023            mAdded = false;
4024        }
4025    }
4026
4027    public void requestUpdateConfiguration(Configuration config) {
4028        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
4029        mHandler.sendMessage(msg);
4030    }
4031
4032    public void loadSystemProperties() {
4033        boolean layout = SystemProperties.getBoolean(
4034                View.DEBUG_LAYOUT_PROPERTY, false);
4035        if (layout != mAttachInfo.mDebugLayout) {
4036            mAttachInfo.mDebugLayout = layout;
4037            if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
4038                mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
4039            }
4040        }
4041    }
4042
4043    private void destroyHardwareRenderer() {
4044        AttachInfo attachInfo = mAttachInfo;
4045        HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer;
4046
4047        if (hardwareRenderer != null) {
4048            if (mView != null) {
4049                hardwareRenderer.destroyHardwareResources(mView);
4050            }
4051            hardwareRenderer.destroy(true);
4052            hardwareRenderer.setRequested(false);
4053
4054            attachInfo.mHardwareRenderer = null;
4055            attachInfo.mHardwareAccelerated = false;
4056        }
4057    }
4058
4059    void dispatchImeFinishedEvent(int seq, boolean handled) {
4060        Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT);
4061        msg.arg1 = seq;
4062        msg.arg2 = handled ? 1 : 0;
4063        msg.setAsynchronous(true);
4064        mHandler.sendMessage(msg);
4065    }
4066
4067    public void dispatchFinishInputConnection(InputConnection connection) {
4068        Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
4069        mHandler.sendMessage(msg);
4070    }
4071
4072    public void dispatchResized(int w, int h, Rect contentInsets,
4073            Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4074        if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
4075                + " h=" + h + " contentInsets=" + contentInsets.toShortString()
4076                + " visibleInsets=" + visibleInsets.toShortString()
4077                + " reportDraw=" + reportDraw);
4078        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED);
4079        if (mTranslator != null) {
4080            mTranslator.translateRectInScreenToAppWindow(contentInsets);
4081            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
4082            w *= mTranslator.applicationInvertedScale;
4083            h *= mTranslator.applicationInvertedScale;
4084        }
4085        msg.arg1 = w;
4086        msg.arg2 = h;
4087        ResizedInfo ri = new ResizedInfo();
4088        ri.contentInsets = new Rect(contentInsets);
4089        ri.visibleInsets = new Rect(visibleInsets);
4090        ri.newConfig = newConfig;
4091        msg.obj = ri;
4092        mHandler.sendMessage(msg);
4093    }
4094
4095    public void dispatchMoved(int newX, int newY) {
4096        if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
4097        if (mTranslator != null) {
4098            PointF point = new PointF(newX, newY);
4099            mTranslator.translatePointInScreenToAppWindow(point);
4100            newX = (int) (point.x + 0.5);
4101            newY = (int) (point.y + 0.5);
4102        }
4103        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
4104        mHandler.sendMessage(msg);
4105    }
4106
4107    /**
4108     * Represents a pending input event that is waiting in a queue.
4109     *
4110     * Input events are processed in serial order by the timestamp specified by
4111     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
4112     * one input event to the application at a time and waits for the application
4113     * to finish handling it before delivering the next one.
4114     *
4115     * However, because the application or IME can synthesize and inject multiple
4116     * key events at a time without going through the input dispatcher, we end up
4117     * needing a queue on the application's side.
4118     */
4119    private static final class QueuedInputEvent {
4120        public static final int FLAG_DELIVER_POST_IME = 1;
4121
4122        public QueuedInputEvent mNext;
4123
4124        public InputEvent mEvent;
4125        public InputEventReceiver mReceiver;
4126        public int mFlags;
4127    }
4128
4129    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
4130            InputEventReceiver receiver, int flags) {
4131        QueuedInputEvent q = mQueuedInputEventPool;
4132        if (q != null) {
4133            mQueuedInputEventPoolSize -= 1;
4134            mQueuedInputEventPool = q.mNext;
4135            q.mNext = null;
4136        } else {
4137            q = new QueuedInputEvent();
4138        }
4139
4140        q.mEvent = event;
4141        q.mReceiver = receiver;
4142        q.mFlags = flags;
4143        return q;
4144    }
4145
4146    private void recycleQueuedInputEvent(QueuedInputEvent q) {
4147        q.mEvent = null;
4148        q.mReceiver = null;
4149
4150        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
4151            mQueuedInputEventPoolSize += 1;
4152            q.mNext = mQueuedInputEventPool;
4153            mQueuedInputEventPool = q;
4154        }
4155    }
4156
4157    void enqueueInputEvent(InputEvent event) {
4158        enqueueInputEvent(event, null, 0, false);
4159    }
4160
4161    void enqueueInputEvent(InputEvent event,
4162            InputEventReceiver receiver, int flags, boolean processImmediately) {
4163        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
4164
4165        // Always enqueue the input event in order, regardless of its time stamp.
4166        // We do this because the application or the IME may inject key events
4167        // in response to touch events and we want to ensure that the injected keys
4168        // are processed in the order they were received and we cannot trust that
4169        // the time stamp of injected events are monotonic.
4170        QueuedInputEvent last = mFirstPendingInputEvent;
4171        if (last == null) {
4172            mFirstPendingInputEvent = q;
4173        } else {
4174            while (last.mNext != null) {
4175                last = last.mNext;
4176            }
4177            last.mNext = q;
4178        }
4179
4180        if (processImmediately) {
4181            doProcessInputEvents();
4182        } else {
4183            scheduleProcessInputEvents();
4184        }
4185    }
4186
4187    private void scheduleProcessInputEvents() {
4188        if (!mProcessInputEventsScheduled) {
4189            mProcessInputEventsScheduled = true;
4190            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
4191            msg.setAsynchronous(true);
4192            mHandler.sendMessage(msg);
4193        }
4194    }
4195
4196    void doProcessInputEvents() {
4197        while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) {
4198            QueuedInputEvent q = mFirstPendingInputEvent;
4199            mFirstPendingInputEvent = q.mNext;
4200            q.mNext = null;
4201            mCurrentInputEvent = q;
4202            deliverInputEvent(q);
4203        }
4204
4205        // We are done processing all input events that we can process right now
4206        // so we can clear the pending flag immediately.
4207        if (mProcessInputEventsScheduled) {
4208            mProcessInputEventsScheduled = false;
4209            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
4210        }
4211    }
4212
4213    private void finishInputEvent(QueuedInputEvent q, boolean handled) {
4214        if (q != mCurrentInputEvent) {
4215            throw new IllegalStateException("finished input event out of order");
4216        }
4217
4218        if (q.mReceiver != null) {
4219            q.mReceiver.finishInputEvent(q.mEvent, handled);
4220        } else {
4221            q.mEvent.recycleIfNeededAfterDispatch();
4222        }
4223
4224        recycleQueuedInputEvent(q);
4225
4226        mCurrentInputEvent = null;
4227        if (mFirstPendingInputEvent != null) {
4228            scheduleProcessInputEvents();
4229        }
4230    }
4231
4232    void scheduleConsumeBatchedInput() {
4233        if (!mConsumeBatchedInputScheduled) {
4234            mConsumeBatchedInputScheduled = true;
4235            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
4236                    mConsumedBatchedInputRunnable, null);
4237        }
4238    }
4239
4240    void unscheduleConsumeBatchedInput() {
4241        if (mConsumeBatchedInputScheduled) {
4242            mConsumeBatchedInputScheduled = false;
4243            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
4244                    mConsumedBatchedInputRunnable, null);
4245        }
4246    }
4247
4248    void doConsumeBatchedInput(long frameTimeNanos) {
4249        if (mConsumeBatchedInputScheduled) {
4250            mConsumeBatchedInputScheduled = false;
4251            if (mInputEventReceiver != null) {
4252                mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos);
4253            }
4254            doProcessInputEvents();
4255        }
4256    }
4257
4258    final class TraversalRunnable implements Runnable {
4259        @Override
4260        public void run() {
4261            doTraversal();
4262        }
4263    }
4264    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
4265
4266    final class WindowInputEventReceiver extends InputEventReceiver {
4267        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
4268            super(inputChannel, looper);
4269        }
4270
4271        @Override
4272        public void onInputEvent(InputEvent event) {
4273            enqueueInputEvent(event, this, 0, true);
4274        }
4275
4276        @Override
4277        public void onBatchedInputEventPending() {
4278            scheduleConsumeBatchedInput();
4279        }
4280
4281        @Override
4282        public void dispose() {
4283            unscheduleConsumeBatchedInput();
4284            super.dispose();
4285        }
4286    }
4287    WindowInputEventReceiver mInputEventReceiver;
4288
4289    final class ConsumeBatchedInputRunnable implements Runnable {
4290        @Override
4291        public void run() {
4292            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
4293        }
4294    }
4295    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
4296            new ConsumeBatchedInputRunnable();
4297    boolean mConsumeBatchedInputScheduled;
4298
4299    final class InvalidateOnAnimationRunnable implements Runnable {
4300        private boolean mPosted;
4301        private ArrayList<View> mViews = new ArrayList<View>();
4302        private ArrayList<AttachInfo.InvalidateInfo> mViewRects =
4303                new ArrayList<AttachInfo.InvalidateInfo>();
4304        private View[] mTempViews;
4305        private AttachInfo.InvalidateInfo[] mTempViewRects;
4306
4307        public void addView(View view) {
4308            synchronized (this) {
4309                mViews.add(view);
4310                postIfNeededLocked();
4311            }
4312        }
4313
4314        public void addViewRect(AttachInfo.InvalidateInfo info) {
4315            synchronized (this) {
4316                mViewRects.add(info);
4317                postIfNeededLocked();
4318            }
4319        }
4320
4321        public void removeView(View view) {
4322            synchronized (this) {
4323                mViews.remove(view);
4324
4325                for (int i = mViewRects.size(); i-- > 0; ) {
4326                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
4327                    if (info.target == view) {
4328                        mViewRects.remove(i);
4329                        info.release();
4330                    }
4331                }
4332
4333                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
4334                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
4335                    mPosted = false;
4336                }
4337            }
4338        }
4339
4340        @Override
4341        public void run() {
4342            final int viewCount;
4343            final int viewRectCount;
4344            synchronized (this) {
4345                mPosted = false;
4346
4347                viewCount = mViews.size();
4348                if (viewCount != 0) {
4349                    mTempViews = mViews.toArray(mTempViews != null
4350                            ? mTempViews : new View[viewCount]);
4351                    mViews.clear();
4352                }
4353
4354                viewRectCount = mViewRects.size();
4355                if (viewRectCount != 0) {
4356                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
4357                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
4358                    mViewRects.clear();
4359                }
4360            }
4361
4362            for (int i = 0; i < viewCount; i++) {
4363                mTempViews[i].invalidate();
4364                mTempViews[i] = null;
4365            }
4366
4367            for (int i = 0; i < viewRectCount; i++) {
4368                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
4369                info.target.invalidate(info.left, info.top, info.right, info.bottom);
4370                info.release();
4371            }
4372        }
4373
4374        private void postIfNeededLocked() {
4375            if (!mPosted) {
4376                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
4377                mPosted = true;
4378            }
4379        }
4380    }
4381    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
4382            new InvalidateOnAnimationRunnable();
4383
4384    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
4385        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
4386        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4387    }
4388
4389    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
4390            long delayMilliseconds) {
4391        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
4392        mHandler.sendMessageDelayed(msg, delayMilliseconds);
4393    }
4394
4395    public void dispatchInvalidateOnAnimation(View view) {
4396        mInvalidateOnAnimationRunnable.addView(view);
4397    }
4398
4399    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
4400        mInvalidateOnAnimationRunnable.addViewRect(info);
4401    }
4402
4403    public void enqueueDisplayList(DisplayList displayList) {
4404        mDisplayLists.add(displayList);
4405
4406        mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST);
4407        Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST);
4408        mHandler.sendMessage(msg);
4409    }
4410
4411    public void dequeueDisplayList(DisplayList displayList) {
4412        if (mDisplayLists.remove(displayList)) {
4413            displayList.invalidate();
4414            if (mDisplayLists.size() == 0) {
4415                mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST);
4416            }
4417        }
4418    }
4419
4420    public void cancelInvalidate(View view) {
4421        mHandler.removeMessages(MSG_INVALIDATE, view);
4422        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
4423        // them to the pool
4424        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
4425        mInvalidateOnAnimationRunnable.removeView(view);
4426    }
4427
4428    public void dispatchKey(KeyEvent event) {
4429        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event);
4430        msg.setAsynchronous(true);
4431        mHandler.sendMessage(msg);
4432    }
4433
4434    public void dispatchKeyFromIme(KeyEvent event) {
4435        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
4436        msg.setAsynchronous(true);
4437        mHandler.sendMessage(msg);
4438    }
4439
4440    public void dispatchUnhandledKey(KeyEvent event) {
4441        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4442            final KeyCharacterMap kcm = event.getKeyCharacterMap();
4443            final int keyCode = event.getKeyCode();
4444            final int metaState = event.getMetaState();
4445
4446            // Check for fallback actions specified by the key character map.
4447            KeyCharacterMap.FallbackAction fallbackAction =
4448                    kcm.getFallbackAction(keyCode, metaState);
4449            if (fallbackAction != null) {
4450                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
4451                KeyEvent fallbackEvent = KeyEvent.obtain(
4452                        event.getDownTime(), event.getEventTime(),
4453                        event.getAction(), fallbackAction.keyCode,
4454                        event.getRepeatCount(), fallbackAction.metaState,
4455                        event.getDeviceId(), event.getScanCode(),
4456                        flags, event.getSource(), null);
4457                fallbackAction.recycle();
4458
4459                dispatchKey(fallbackEvent);
4460            }
4461        }
4462    }
4463
4464    public void dispatchAppVisibility(boolean visible) {
4465        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
4466        msg.arg1 = visible ? 1 : 0;
4467        mHandler.sendMessage(msg);
4468    }
4469
4470    public void dispatchScreenStateChange(boolean on) {
4471        Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE);
4472        msg.arg1 = on ? 1 : 0;
4473        mHandler.sendMessage(msg);
4474    }
4475
4476    public void dispatchGetNewSurface() {
4477        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
4478        mHandler.sendMessage(msg);
4479    }
4480
4481    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4482        Message msg = Message.obtain();
4483        msg.what = MSG_WINDOW_FOCUS_CHANGED;
4484        msg.arg1 = hasFocus ? 1 : 0;
4485        msg.arg2 = inTouchMode ? 1 : 0;
4486        mHandler.sendMessage(msg);
4487    }
4488
4489    public void dispatchCloseSystemDialogs(String reason) {
4490        Message msg = Message.obtain();
4491        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
4492        msg.obj = reason;
4493        mHandler.sendMessage(msg);
4494    }
4495
4496    public void dispatchDragEvent(DragEvent event) {
4497        final int what;
4498        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
4499            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
4500            mHandler.removeMessages(what);
4501        } else {
4502            what = MSG_DISPATCH_DRAG_EVENT;
4503        }
4504        Message msg = mHandler.obtainMessage(what, event);
4505        mHandler.sendMessage(msg);
4506    }
4507
4508    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4509            int localValue, int localChanges) {
4510        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
4511        args.seq = seq;
4512        args.globalVisibility = globalVisibility;
4513        args.localValue = localValue;
4514        args.localChanges = localChanges;
4515        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
4516    }
4517
4518    public void dispatchDoneAnimating() {
4519        mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
4520    }
4521
4522    public void dispatchCheckFocus() {
4523        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
4524            // This will result in a call to checkFocus() below.
4525            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
4526        }
4527    }
4528
4529    /**
4530     * Post a callback to send a
4531     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4532     * This event is send at most once every
4533     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
4534     */
4535    private void postSendWindowContentChangedCallback(View source) {
4536        if (mSendWindowContentChangedAccessibilityEvent == null) {
4537            mSendWindowContentChangedAccessibilityEvent =
4538                new SendWindowContentChangedAccessibilityEvent();
4539        }
4540        View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource;
4541        if (oldSource == null) {
4542            mSendWindowContentChangedAccessibilityEvent.mSource = source;
4543            mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent,
4544                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
4545        } else {
4546            mSendWindowContentChangedAccessibilityEvent.mSource =
4547                    getCommonPredecessor(oldSource, source);
4548        }
4549    }
4550
4551    /**
4552     * Remove a posted callback to send a
4553     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4554     */
4555    private void removeSendWindowContentChangedCallback() {
4556        if (mSendWindowContentChangedAccessibilityEvent != null) {
4557            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
4558        }
4559    }
4560
4561    public boolean showContextMenuForChild(View originalView) {
4562        return false;
4563    }
4564
4565    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
4566        return null;
4567    }
4568
4569    public void createContextMenu(ContextMenu menu) {
4570    }
4571
4572    public void childDrawableStateChanged(View child) {
4573    }
4574
4575    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
4576        if (mView == null) {
4577            return false;
4578        }
4579        // Intercept accessibility focus events fired by virtual nodes to keep
4580        // track of accessibility focus position in such nodes.
4581        final int eventType = event.getEventType();
4582        switch (eventType) {
4583            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4584                final long sourceNodeId = event.getSourceNodeId();
4585                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4586                        sourceNodeId);
4587                View source = mView.findViewByAccessibilityId(accessibilityViewId);
4588                if (source != null) {
4589                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4590                    if (provider != null) {
4591                        AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(
4592                                AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId));
4593                        setAccessibilityFocus(source, node);
4594                    }
4595                }
4596            } break;
4597            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4598                final long sourceNodeId = event.getSourceNodeId();
4599                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4600                        sourceNodeId);
4601                View source = mView.findViewByAccessibilityId(accessibilityViewId);
4602                if (source != null) {
4603                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4604                    if (provider != null) {
4605                        setAccessibilityFocus(null, null);
4606                    }
4607                }
4608            } break;
4609        }
4610        mAccessibilityManager.sendAccessibilityEvent(event);
4611        return true;
4612    }
4613
4614    @Override
4615    public void childAccessibilityStateChanged(View child) {
4616        postSendWindowContentChangedCallback(child);
4617    }
4618
4619    private View getCommonPredecessor(View first, View second) {
4620        if (mAttachInfo != null) {
4621            if (mTempHashSet == null) {
4622                mTempHashSet = new HashSet<View>();
4623            }
4624            HashSet<View> seen = mTempHashSet;
4625            seen.clear();
4626            View firstCurrent = first;
4627            while (firstCurrent != null) {
4628                seen.add(firstCurrent);
4629                ViewParent firstCurrentParent = firstCurrent.mParent;
4630                if (firstCurrentParent instanceof View) {
4631                    firstCurrent = (View) firstCurrentParent;
4632                } else {
4633                    firstCurrent = null;
4634                }
4635            }
4636            View secondCurrent = second;
4637            while (secondCurrent != null) {
4638                if (seen.contains(secondCurrent)) {
4639                    seen.clear();
4640                    return secondCurrent;
4641                }
4642                ViewParent secondCurrentParent = secondCurrent.mParent;
4643                if (secondCurrentParent instanceof View) {
4644                    secondCurrent = (View) secondCurrentParent;
4645                } else {
4646                    secondCurrent = null;
4647                }
4648            }
4649            seen.clear();
4650        }
4651        return null;
4652    }
4653
4654    void checkThread() {
4655        if (mThread != Thread.currentThread()) {
4656            throw new CalledFromWrongThreadException(
4657                    "Only the original thread that created a view hierarchy can touch its views.");
4658        }
4659    }
4660
4661    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
4662        // ViewAncestor never intercepts touch event, so this can be a no-op
4663    }
4664
4665    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
4666            boolean immediate) {
4667        return scrollToRectOrFocus(rectangle, immediate);
4668    }
4669
4670    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
4671        // Do nothing.
4672    }
4673
4674    class TakenSurfaceHolder extends BaseSurfaceHolder {
4675        @Override
4676        public boolean onAllowLockCanvas() {
4677            return mDrawingAllowed;
4678        }
4679
4680        @Override
4681        public void onRelayoutContainer() {
4682            // Not currently interesting -- from changing between fixed and layout size.
4683        }
4684
4685        public void setFormat(int format) {
4686            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
4687        }
4688
4689        public void setType(int type) {
4690            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
4691        }
4692
4693        @Override
4694        public void onUpdateSurface() {
4695            // We take care of format and type changes on our own.
4696            throw new IllegalStateException("Shouldn't be here");
4697        }
4698
4699        public boolean isCreating() {
4700            return mIsCreating;
4701        }
4702
4703        @Override
4704        public void setFixedSize(int width, int height) {
4705            throw new UnsupportedOperationException(
4706                    "Currently only support sizing from layout");
4707        }
4708
4709        public void setKeepScreenOn(boolean screenOn) {
4710            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
4711        }
4712    }
4713
4714    static final class InputMethodCallback implements InputMethodManager.FinishedEventCallback {
4715        private WeakReference<ViewRootImpl> mViewAncestor;
4716
4717        public InputMethodCallback(ViewRootImpl viewAncestor) {
4718            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4719        }
4720
4721        @Override
4722        public void finishedEvent(int seq, boolean handled) {
4723            final ViewRootImpl viewAncestor = mViewAncestor.get();
4724            if (viewAncestor != null) {
4725                viewAncestor.dispatchImeFinishedEvent(seq, handled);
4726            }
4727        }
4728    }
4729
4730    static class W extends IWindow.Stub {
4731        private final WeakReference<ViewRootImpl> mViewAncestor;
4732
4733        W(ViewRootImpl viewAncestor) {
4734            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4735        }
4736
4737        public void resized(int w, int h, Rect contentInsets,
4738                Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4739            final ViewRootImpl viewAncestor = mViewAncestor.get();
4740            if (viewAncestor != null) {
4741                viewAncestor.dispatchResized(w, h, contentInsets,
4742                        visibleInsets, reportDraw, newConfig);
4743            }
4744        }
4745
4746        @Override
4747        public void moved(int newX, int newY) {
4748            final ViewRootImpl viewAncestor = mViewAncestor.get();
4749            if (viewAncestor != null) {
4750                viewAncestor.dispatchMoved(newX, newY);
4751            }
4752        }
4753
4754        public void dispatchAppVisibility(boolean visible) {
4755            final ViewRootImpl viewAncestor = mViewAncestor.get();
4756            if (viewAncestor != null) {
4757                viewAncestor.dispatchAppVisibility(visible);
4758            }
4759        }
4760
4761        public void dispatchScreenState(boolean on) {
4762            final ViewRootImpl viewAncestor = mViewAncestor.get();
4763            if (viewAncestor != null) {
4764                viewAncestor.dispatchScreenStateChange(on);
4765            }
4766        }
4767
4768        public void dispatchGetNewSurface() {
4769            final ViewRootImpl viewAncestor = mViewAncestor.get();
4770            if (viewAncestor != null) {
4771                viewAncestor.dispatchGetNewSurface();
4772            }
4773        }
4774
4775        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4776            final ViewRootImpl viewAncestor = mViewAncestor.get();
4777            if (viewAncestor != null) {
4778                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
4779            }
4780        }
4781
4782        private static int checkCallingPermission(String permission) {
4783            try {
4784                return ActivityManagerNative.getDefault().checkPermission(
4785                        permission, Binder.getCallingPid(), Binder.getCallingUid());
4786            } catch (RemoteException e) {
4787                return PackageManager.PERMISSION_DENIED;
4788            }
4789        }
4790
4791        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
4792            final ViewRootImpl viewAncestor = mViewAncestor.get();
4793            if (viewAncestor != null) {
4794                final View view = viewAncestor.mView;
4795                if (view != null) {
4796                    if (checkCallingPermission(Manifest.permission.DUMP) !=
4797                            PackageManager.PERMISSION_GRANTED) {
4798                        throw new SecurityException("Insufficient permissions to invoke"
4799                                + " executeCommand() from pid=" + Binder.getCallingPid()
4800                                + ", uid=" + Binder.getCallingUid());
4801                    }
4802
4803                    OutputStream clientStream = null;
4804                    try {
4805                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
4806                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
4807                    } catch (IOException e) {
4808                        e.printStackTrace();
4809                    } finally {
4810                        if (clientStream != null) {
4811                            try {
4812                                clientStream.close();
4813                            } catch (IOException e) {
4814                                e.printStackTrace();
4815                            }
4816                        }
4817                    }
4818                }
4819            }
4820        }
4821
4822        public void closeSystemDialogs(String reason) {
4823            final ViewRootImpl viewAncestor = mViewAncestor.get();
4824            if (viewAncestor != null) {
4825                viewAncestor.dispatchCloseSystemDialogs(reason);
4826            }
4827        }
4828
4829        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
4830                boolean sync) {
4831            if (sync) {
4832                try {
4833                    sWindowSession.wallpaperOffsetsComplete(asBinder());
4834                } catch (RemoteException e) {
4835                }
4836            }
4837        }
4838
4839        public void dispatchWallpaperCommand(String action, int x, int y,
4840                int z, Bundle extras, boolean sync) {
4841            if (sync) {
4842                try {
4843                    sWindowSession.wallpaperCommandComplete(asBinder(), null);
4844                } catch (RemoteException e) {
4845                }
4846            }
4847        }
4848
4849        /* Drag/drop */
4850        public void dispatchDragEvent(DragEvent event) {
4851            final ViewRootImpl viewAncestor = mViewAncestor.get();
4852            if (viewAncestor != null) {
4853                viewAncestor.dispatchDragEvent(event);
4854            }
4855        }
4856
4857        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4858                int localValue, int localChanges) {
4859            final ViewRootImpl viewAncestor = mViewAncestor.get();
4860            if (viewAncestor != null) {
4861                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
4862                        localValue, localChanges);
4863            }
4864        }
4865
4866        public void doneAnimating() {
4867            final ViewRootImpl viewAncestor = mViewAncestor.get();
4868            if (viewAncestor != null) {
4869                viewAncestor.dispatchDoneAnimating();
4870            }
4871        }
4872    }
4873
4874    /**
4875     * Maintains state information for a single trackball axis, generating
4876     * discrete (DPAD) movements based on raw trackball motion.
4877     */
4878    static final class TrackballAxis {
4879        /**
4880         * The maximum amount of acceleration we will apply.
4881         */
4882        static final float MAX_ACCELERATION = 20;
4883
4884        /**
4885         * The maximum amount of time (in milliseconds) between events in order
4886         * for us to consider the user to be doing fast trackball movements,
4887         * and thus apply an acceleration.
4888         */
4889        static final long FAST_MOVE_TIME = 150;
4890
4891        /**
4892         * Scaling factor to the time (in milliseconds) between events to how
4893         * much to multiple/divide the current acceleration.  When movement
4894         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4895         * FAST_MOVE_TIME it divides it.
4896         */
4897        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4898
4899        float position;
4900        float absPosition;
4901        float acceleration = 1;
4902        long lastMoveTime = 0;
4903        int step;
4904        int dir;
4905        int nonAccelMovement;
4906
4907        void reset(int _step) {
4908            position = 0;
4909            acceleration = 1;
4910            lastMoveTime = 0;
4911            step = _step;
4912            dir = 0;
4913        }
4914
4915        /**
4916         * Add trackball movement into the state.  If the direction of movement
4917         * has been reversed, the state is reset before adding the
4918         * movement (so that you don't have to compensate for any previously
4919         * collected movement before see the result of the movement in the
4920         * new direction).
4921         *
4922         * @return Returns the absolute value of the amount of movement
4923         * collected so far.
4924         */
4925        float collect(float off, long time, String axis) {
4926            long normTime;
4927            if (off > 0) {
4928                normTime = (long)(off * FAST_MOVE_TIME);
4929                if (dir < 0) {
4930                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4931                    position = 0;
4932                    step = 0;
4933                    acceleration = 1;
4934                    lastMoveTime = 0;
4935                }
4936                dir = 1;
4937            } else if (off < 0) {
4938                normTime = (long)((-off) * FAST_MOVE_TIME);
4939                if (dir > 0) {
4940                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4941                    position = 0;
4942                    step = 0;
4943                    acceleration = 1;
4944                    lastMoveTime = 0;
4945                }
4946                dir = -1;
4947            } else {
4948                normTime = 0;
4949            }
4950
4951            // The number of milliseconds between each movement that is
4952            // considered "normal" and will not result in any acceleration
4953            // or deceleration, scaled by the offset we have here.
4954            if (normTime > 0) {
4955                long delta = time - lastMoveTime;
4956                lastMoveTime = time;
4957                float acc = acceleration;
4958                if (delta < normTime) {
4959                    // The user is scrolling rapidly, so increase acceleration.
4960                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4961                    if (scale > 1) acc *= scale;
4962                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4963                            + off + " normTime=" + normTime + " delta=" + delta
4964                            + " scale=" + scale + " acc=" + acc);
4965                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4966                } else {
4967                    // The user is scrolling slowly, so decrease acceleration.
4968                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4969                    if (scale > 1) acc /= scale;
4970                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4971                            + off + " normTime=" + normTime + " delta=" + delta
4972                            + " scale=" + scale + " acc=" + acc);
4973                    acceleration = acc > 1 ? acc : 1;
4974                }
4975            }
4976            position += off;
4977            return (absPosition = Math.abs(position));
4978        }
4979
4980        /**
4981         * Generate the number of discrete movement events appropriate for
4982         * the currently collected trackball movement.
4983         *
4984         * @param precision The minimum movement required to generate the
4985         * first discrete movement.
4986         *
4987         * @return Returns the number of discrete movements, either positive
4988         * or negative, or 0 if there is not enough trackball movement yet
4989         * for a discrete movement.
4990         */
4991        int generate(float precision) {
4992            int movement = 0;
4993            nonAccelMovement = 0;
4994            do {
4995                final int dir = position >= 0 ? 1 : -1;
4996                switch (step) {
4997                    // If we are going to execute the first step, then we want
4998                    // to do this as soon as possible instead of waiting for
4999                    // a full movement, in order to make things look responsive.
5000                    case 0:
5001                        if (absPosition < precision) {
5002                            return movement;
5003                        }
5004                        movement += dir;
5005                        nonAccelMovement += dir;
5006                        step = 1;
5007                        break;
5008                    // If we have generated the first movement, then we need
5009                    // to wait for the second complete trackball motion before
5010                    // generating the second discrete movement.
5011                    case 1:
5012                        if (absPosition < 2) {
5013                            return movement;
5014                        }
5015                        movement += dir;
5016                        nonAccelMovement += dir;
5017                        position += dir > 0 ? -2 : 2;
5018                        absPosition = Math.abs(position);
5019                        step = 2;
5020                        break;
5021                    // After the first two, we generate discrete movements
5022                    // consistently with the trackball, applying an acceleration
5023                    // if the trackball is moving quickly.  This is a simple
5024                    // acceleration on top of what we already compute based
5025                    // on how quickly the wheel is being turned, to apply
5026                    // a longer increasing acceleration to continuous movement
5027                    // in one direction.
5028                    default:
5029                        if (absPosition < 1) {
5030                            return movement;
5031                        }
5032                        movement += dir;
5033                        position += dir >= 0 ? -1 : 1;
5034                        absPosition = Math.abs(position);
5035                        float acc = acceleration;
5036                        acc *= 1.1f;
5037                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
5038                        break;
5039                }
5040            } while (true);
5041        }
5042    }
5043
5044    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
5045        public CalledFromWrongThreadException(String msg) {
5046            super(msg);
5047        }
5048    }
5049
5050    private SurfaceHolder mHolder = new SurfaceHolder() {
5051        // we only need a SurfaceHolder for opengl. it would be nice
5052        // to implement everything else though, especially the callback
5053        // support (opengl doesn't make use of it right now, but eventually
5054        // will).
5055        public Surface getSurface() {
5056            return mSurface;
5057        }
5058
5059        public boolean isCreating() {
5060            return false;
5061        }
5062
5063        public void addCallback(Callback callback) {
5064        }
5065
5066        public void removeCallback(Callback callback) {
5067        }
5068
5069        public void setFixedSize(int width, int height) {
5070        }
5071
5072        public void setSizeFromLayout() {
5073        }
5074
5075        public void setFormat(int format) {
5076        }
5077
5078        public void setType(int type) {
5079        }
5080
5081        public void setKeepScreenOn(boolean screenOn) {
5082        }
5083
5084        public Canvas lockCanvas() {
5085            return null;
5086        }
5087
5088        public Canvas lockCanvas(Rect dirty) {
5089            return null;
5090        }
5091
5092        public void unlockCanvasAndPost(Canvas canvas) {
5093        }
5094        public Rect getSurfaceFrame() {
5095            return null;
5096        }
5097    };
5098
5099    static RunQueue getRunQueue() {
5100        RunQueue rq = sRunQueues.get();
5101        if (rq != null) {
5102            return rq;
5103        }
5104        rq = new RunQueue();
5105        sRunQueues.set(rq);
5106        return rq;
5107    }
5108
5109    /**
5110     * The run queue is used to enqueue pending work from Views when no Handler is
5111     * attached.  The work is executed during the next call to performTraversals on
5112     * the thread.
5113     * @hide
5114     */
5115    static final class RunQueue {
5116        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
5117
5118        void post(Runnable action) {
5119            postDelayed(action, 0);
5120        }
5121
5122        void postDelayed(Runnable action, long delayMillis) {
5123            HandlerAction handlerAction = new HandlerAction();
5124            handlerAction.action = action;
5125            handlerAction.delay = delayMillis;
5126
5127            synchronized (mActions) {
5128                mActions.add(handlerAction);
5129            }
5130        }
5131
5132        void removeCallbacks(Runnable action) {
5133            final HandlerAction handlerAction = new HandlerAction();
5134            handlerAction.action = action;
5135
5136            synchronized (mActions) {
5137                final ArrayList<HandlerAction> actions = mActions;
5138
5139                while (actions.remove(handlerAction)) {
5140                    // Keep going
5141                }
5142            }
5143        }
5144
5145        void executeActions(Handler handler) {
5146            synchronized (mActions) {
5147                final ArrayList<HandlerAction> actions = mActions;
5148                final int count = actions.size();
5149
5150                for (int i = 0; i < count; i++) {
5151                    final HandlerAction handlerAction = actions.get(i);
5152                    handler.postDelayed(handlerAction.action, handlerAction.delay);
5153                }
5154
5155                actions.clear();
5156            }
5157        }
5158
5159        private static class HandlerAction {
5160            Runnable action;
5161            long delay;
5162
5163            @Override
5164            public boolean equals(Object o) {
5165                if (this == o) return true;
5166                if (o == null || getClass() != o.getClass()) return false;
5167
5168                HandlerAction that = (HandlerAction) o;
5169                return !(action != null ? !action.equals(that.action) : that.action != null);
5170
5171            }
5172
5173            @Override
5174            public int hashCode() {
5175                int result = action != null ? action.hashCode() : 0;
5176                result = 31 * result + (int) (delay ^ (delay >>> 32));
5177                return result;
5178            }
5179        }
5180    }
5181
5182    /**
5183     * Class for managing the accessibility interaction connection
5184     * based on the global accessibility state.
5185     */
5186    final class AccessibilityInteractionConnectionManager
5187            implements AccessibilityStateChangeListener {
5188        public void onAccessibilityStateChanged(boolean enabled) {
5189            if (enabled) {
5190                ensureConnection();
5191                if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
5192                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
5193                    View focusedView = mView.findFocus();
5194                    if (focusedView != null && focusedView != mView) {
5195                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5196                    }
5197                }
5198            } else {
5199                ensureNoConnection();
5200                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
5201            }
5202        }
5203
5204        public void ensureConnection() {
5205            if (mAttachInfo != null) {
5206                final boolean registered =
5207                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5208                if (!registered) {
5209                    mAttachInfo.mAccessibilityWindowId =
5210                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
5211                                new AccessibilityInteractionConnection(ViewRootImpl.this));
5212                }
5213            }
5214        }
5215
5216        public void ensureNoConnection() {
5217            final boolean registered =
5218                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5219            if (registered) {
5220                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED;
5221                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
5222            }
5223        }
5224    }
5225
5226    /**
5227     * This class is an interface this ViewAncestor provides to the
5228     * AccessibilityManagerService to the latter can interact with
5229     * the view hierarchy in this ViewAncestor.
5230     */
5231    static final class AccessibilityInteractionConnection
5232            extends IAccessibilityInteractionConnection.Stub {
5233        private final WeakReference<ViewRootImpl> mViewRootImpl;
5234
5235        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
5236            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
5237        }
5238
5239        @Override
5240        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
5241                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5242                int interrogatingPid, long interrogatingTid) {
5243            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5244            if (viewRootImpl != null && viewRootImpl.mView != null) {
5245                viewRootImpl.getAccessibilityInteractionController()
5246                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
5247                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
5248            } else {
5249                // We cannot make the call and notify the caller so it does not wait.
5250                try {
5251                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5252                } catch (RemoteException re) {
5253                    /* best effort - ignore */
5254                }
5255            }
5256        }
5257
5258        @Override
5259        public void performAccessibilityAction(long accessibilityNodeId, int action,
5260                Bundle arguments, int interactionId,
5261                IAccessibilityInteractionConnectionCallback callback, int flags,
5262                int interogatingPid, long interrogatingTid) {
5263            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5264            if (viewRootImpl != null && viewRootImpl.mView != null) {
5265                viewRootImpl.getAccessibilityInteractionController()
5266                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
5267                            interactionId, callback, flags, interogatingPid, interrogatingTid);
5268            } else {
5269                // We cannot make the call and notify the caller so it does not wait.
5270                try {
5271                    callback.setPerformAccessibilityActionResult(false, interactionId);
5272                } catch (RemoteException re) {
5273                    /* best effort - ignore */
5274                }
5275            }
5276        }
5277
5278        @Override
5279        public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId,
5280                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5281                int interrogatingPid, long interrogatingTid) {
5282            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5283            if (viewRootImpl != null && viewRootImpl.mView != null) {
5284                viewRootImpl.getAccessibilityInteractionController()
5285                    .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId,
5286                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
5287            } else {
5288                // We cannot make the call and notify the caller so it does not wait.
5289                try {
5290                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5291                } catch (RemoteException re) {
5292                    /* best effort - ignore */
5293                }
5294            }
5295        }
5296
5297        @Override
5298        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
5299                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5300                int interrogatingPid, long interrogatingTid) {
5301            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5302            if (viewRootImpl != null && viewRootImpl.mView != null) {
5303                viewRootImpl.getAccessibilityInteractionController()
5304                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
5305                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
5306            } else {
5307                // We cannot make the call and notify the caller so it does not wait.
5308                try {
5309                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5310                } catch (RemoteException re) {
5311                    /* best effort - ignore */
5312                }
5313            }
5314        }
5315
5316        @Override
5317        public void findFocus(long accessibilityNodeId, int focusType, int interactionId,
5318                IAccessibilityInteractionConnectionCallback callback, int flags,
5319                int interrogatingPid, long interrogatingTid) {
5320            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5321            if (viewRootImpl != null && viewRootImpl.mView != null) {
5322                viewRootImpl.getAccessibilityInteractionController()
5323                    .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback,
5324                            flags, interrogatingPid, interrogatingTid);
5325            } else {
5326                // We cannot make the call and notify the caller so it does not wait.
5327                try {
5328                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5329                } catch (RemoteException re) {
5330                    /* best effort - ignore */
5331                }
5332            }
5333        }
5334
5335        @Override
5336        public void focusSearch(long accessibilityNodeId, int direction, int interactionId,
5337                IAccessibilityInteractionConnectionCallback callback, int flags,
5338                int interrogatingPid, long interrogatingTid) {
5339            ViewRootImpl viewRootImpl = mViewRootImpl.get();
5340            if (viewRootImpl != null && viewRootImpl.mView != null) {
5341                viewRootImpl.getAccessibilityInteractionController()
5342                    .focusSearchClientThread(accessibilityNodeId, direction, interactionId,
5343                            callback, flags, interrogatingPid, interrogatingTid);
5344            } else {
5345                // We cannot make the call and notify the caller so it does not wait.
5346                try {
5347                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5348                } catch (RemoteException re) {
5349                    /* best effort - ignore */
5350                }
5351            }
5352        }
5353    }
5354
5355    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
5356        public View mSource;
5357
5358        public void run() {
5359            if (mSource != null) {
5360                mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
5361                mSource.resetAccessibilityStateChanged();
5362                mSource = null;
5363            }
5364        }
5365    }
5366}
5367