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