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