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