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