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