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