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