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