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