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