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