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