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