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