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