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