OSDN Git Service

Add new MotionEvent actions for button press and release.
[android-x86/frameworks-base.git] / core / java / android / view / ViewRootImpl.java
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
17 package android.view;
18
19 import android.Manifest;
20 import android.animation.LayoutTransition;
21 import android.app.ActivityManagerNative;
22 import android.content.ClipDescription;
23 import android.content.ComponentCallbacks;
24 import android.content.Context;
25 import android.content.pm.PackageManager;
26 import android.content.res.CompatibilityInfo;
27 import android.content.res.Configuration;
28 import android.content.res.Resources;
29 import android.graphics.Canvas;
30 import android.graphics.Matrix;
31 import android.graphics.Paint;
32 import android.graphics.PixelFormat;
33 import android.graphics.Point;
34 import android.graphics.PointF;
35 import android.graphics.PorterDuff;
36 import android.graphics.Rect;
37 import android.graphics.Region;
38 import android.graphics.drawable.Drawable;
39 import android.hardware.display.DisplayManager;
40 import android.hardware.display.DisplayManager.DisplayListener;
41 import android.media.AudioManager;
42 import android.os.Binder;
43 import android.os.Build;
44 import android.os.Bundle;
45 import android.os.Debug;
46 import android.os.Handler;
47 import android.os.Looper;
48 import android.os.Message;
49 import android.os.ParcelFileDescriptor;
50 import android.os.Process;
51 import android.os.RemoteException;
52 import android.os.SystemClock;
53 import android.os.SystemProperties;
54 import android.os.Trace;
55 import android.util.AndroidRuntimeException;
56 import android.util.DisplayMetrics;
57 import android.util.Log;
58 import android.util.Slog;
59 import android.util.TimeUtils;
60 import android.util.TypedValue;
61 import android.view.Surface.OutOfResourcesException;
62 import android.view.View.AttachInfo;
63 import android.view.View.MeasureSpec;
64 import android.view.accessibility.AccessibilityEvent;
65 import android.view.accessibility.AccessibilityManager;
66 import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
67 import android.view.accessibility.AccessibilityManager.HighTextContrastChangeListener;
68 import android.view.accessibility.AccessibilityNodeInfo;
69 import android.view.accessibility.AccessibilityNodeProvider;
70 import android.view.accessibility.IAccessibilityInteractionConnection;
71 import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
72 import android.view.animation.AccelerateDecelerateInterpolator;
73 import android.view.animation.Interpolator;
74 import android.view.inputmethod.InputConnection;
75 import android.view.inputmethod.InputMethodManager;
76 import android.widget.Scroller;
77
78 import com.android.internal.R;
79 import com.android.internal.os.SomeArgs;
80 import com.android.internal.util.ScreenShapeHelper;
81 import com.android.internal.view.BaseSurfaceHolder;
82 import com.android.internal.view.RootViewSurfaceTaker;
83
84 import java.io.FileDescriptor;
85 import java.io.IOException;
86 import java.io.OutputStream;
87 import java.io.PrintWriter;
88 import java.lang.ref.WeakReference;
89 import java.util.ArrayList;
90 import java.util.HashSet;
91
92 /**
93  * The top of a view hierarchy, implementing the needed protocol between View
94  * and the WindowManager.  This is for the most part an internal implementation
95  * detail of {@link WindowManagerGlobal}.
96  *
97  * {@hide}
98  */
99 @SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
100 public final class ViewRootImpl implements ViewParent,
101         View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
102     private static final String TAG = "ViewRootImpl";
103     private static final boolean DBG = false;
104     private static final boolean LOCAL_LOGV = false;
105     /** @noinspection PointlessBooleanExpression*/
106     private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
107     private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
108     private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
109     private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
110     private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
111     private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
112     private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
113     private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
114     private static final boolean DEBUG_FPS = false;
115     private static final boolean DEBUG_INPUT_STAGES = false || LOCAL_LOGV;
116
117     /**
118      * Set this system property to true to force the view hierarchy to render
119      * at 60 Hz. This can be used to measure the potential framerate.
120      */
121     private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering";
122
123     // properties used by emulator to determine display shape
124     public static final String PROPERTY_EMULATOR_CIRCULAR = "ro.emulator.circular";
125     public static final String PROPERTY_EMULATOR_WIN_OUTSET_BOTTOM_PX =
126             "ro.emu.win_outset_bottom_px";
127
128     /**
129      * Maximum time we allow the user to roll the trackball enough to generate
130      * a key event, before resetting the counters.
131      */
132     static final int MAX_TRACKBALL_DELAY = 250;
133
134     static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
135
136     static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
137     static boolean sFirstDrawComplete = false;
138
139     static final ArrayList<ComponentCallbacks> sConfigCallbacks
140             = new ArrayList<ComponentCallbacks>();
141
142     final Context mContext;
143     final IWindowSession mWindowSession;
144     final Display mDisplay;
145     final DisplayManager mDisplayManager;
146     final String mBasePackageName;
147
148     final int[] mTmpLocation = new int[2];
149
150     final TypedValue mTmpValue = new TypedValue();
151
152     final Thread mThread;
153
154     final WindowLeaked mLocation;
155
156     final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
157
158     final W mWindow;
159
160     final int mTargetSdkVersion;
161
162     int mSeq;
163
164     View mView;
165
166     View mAccessibilityFocusedHost;
167     AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
168
169     int mViewVisibility;
170     boolean mAppVisible = true;
171     int mOrigWindowType = -1;
172
173     // Set to true if the owner of this window is in the stopped state,
174     // so the window should no longer be active.
175     boolean mStopped = false;
176
177     boolean mLastInCompatMode = false;
178
179     SurfaceHolder.Callback2 mSurfaceHolderCallback;
180     BaseSurfaceHolder mSurfaceHolder;
181     boolean mIsCreating;
182     boolean mDrawingAllowed;
183
184     final Region mTransparentRegion;
185     final Region mPreviousTransparentRegion;
186
187     int mWidth;
188     int mHeight;
189     Rect mDirty;
190     boolean mIsAnimating;
191
192     CompatibilityInfo.Translator mTranslator;
193
194     final View.AttachInfo mAttachInfo;
195     InputChannel mInputChannel;
196     InputQueue.Callback mInputQueueCallback;
197     InputQueue mInputQueue;
198     FallbackEventHandler mFallbackEventHandler;
199     Choreographer mChoreographer;
200
201     final Rect mTempRect; // used in the transaction to not thrash the heap.
202     final Rect mVisRect; // used to retrieve visible rect of focused view.
203
204     boolean mTraversalScheduled;
205     int mTraversalBarrier;
206     boolean mWillDrawSoon;
207     /** Set to true while in performTraversals for detecting when die(true) is called from internal
208      * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
209     boolean mIsInTraversal;
210     boolean mApplyInsetsRequested;
211     boolean mLayoutRequested;
212     boolean mFirst;
213     boolean mReportNextDraw;
214     boolean mFullRedrawNeeded;
215     boolean mNewSurfaceNeeded;
216     boolean mHasHadWindowFocus;
217     boolean mLastWasImTarget;
218     boolean mWindowsAnimating;
219     boolean mDrawDuringWindowsAnimating;
220     boolean mIsDrawing;
221     int mLastSystemUiVisibility;
222     int mClientWindowLayoutFlags;
223     boolean mLastOverscanRequested;
224
225     // Pool of queued input events.
226     private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
227     private QueuedInputEvent mQueuedInputEventPool;
228     private int mQueuedInputEventPoolSize;
229
230     /* Input event queue.
231      * Pending input events are input events waiting to be delivered to the input stages
232      * and handled by the application.
233      */
234     QueuedInputEvent mPendingInputEventHead;
235     QueuedInputEvent mPendingInputEventTail;
236     int mPendingInputEventCount;
237     boolean mProcessInputEventsScheduled;
238     boolean mUnbufferedInputDispatch;
239     String mPendingInputEventQueueLengthCounterName = "pq";
240
241     InputStage mFirstInputStage;
242     InputStage mFirstPostImeInputStage;
243     InputStage mSyntheticInputStage;
244
245     boolean mWindowAttributesChanged = false;
246     int mWindowAttributesChangesFlag = 0;
247
248     // These can be accessed by any thread, must be protected with a lock.
249     // Surface can never be reassigned or cleared (use Surface.clear()).
250     final Surface mSurface = new Surface();
251
252     boolean mAdded;
253     boolean mAddedTouchMode;
254
255     final DisplayAdjustments mDisplayAdjustments;
256
257     // These are accessed by multiple threads.
258     final Rect mWinFrame; // frame given by window manager.
259
260     final Rect mPendingOverscanInsets = new Rect();
261     final Rect mPendingVisibleInsets = new Rect();
262     final Rect mPendingStableInsets = new Rect();
263     final Rect mPendingContentInsets = new Rect();
264     final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
265             = new ViewTreeObserver.InternalInsetsInfo();
266
267     final Rect mDispatchContentInsets = new Rect();
268     final Rect mDispatchStableInsets = new Rect();
269
270     private WindowInsets mLastWindowInsets;
271
272     final Configuration mLastConfiguration = new Configuration();
273     final Configuration mPendingConfiguration = new Configuration();
274
275     boolean mScrollMayChange;
276     int mSoftInputMode;
277     WeakReference<View> mLastScrolledFocus;
278     int mScrollY;
279     int mCurScrollY;
280     Scroller mScroller;
281     HardwareLayer mResizeBuffer;
282     long mResizeBufferStartTime;
283     int mResizeBufferDuration;
284     // Used to block the creation of the ResizeBuffer due to invalidations in
285     // the previous DisplayList tree that must prevent re-execution.
286     // Currently this means a functor was detached.
287     boolean mBlockResizeBuffer;
288     static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
289     private ArrayList<LayoutTransition> mPendingTransitions;
290
291     final ViewConfiguration mViewConfiguration;
292
293     /* Drag/drop */
294     ClipDescription mDragDescription;
295     View mCurrentDragView;
296     volatile Object mLocalDragState;
297     final PointF mDragPoint = new PointF();
298     final PointF mLastTouchPoint = new PointF();
299
300     private boolean mProfileRendering;
301     private Choreographer.FrameCallback mRenderProfiler;
302     private boolean mRenderProfilingEnabled;
303
304     // Variables to track frames per second, enabled via DEBUG_FPS flag
305     private long mFpsStartTime = -1;
306     private long mFpsPrevTime = -1;
307     private int mFpsNumFrames;
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     HighContrastTextManager mHighContrastTextManager;
320
321     SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
322
323     HashSet<View> mTempHashSet;
324
325     private final int mDensity;
326     private final int mNoncompatDensity;
327
328     private boolean mInLayout = false;
329     ArrayList<View> mLayoutRequesters = new ArrayList<View>();
330     boolean mHandlingLayoutInLayoutRequest = false;
331
332     private int mViewLayoutDirectionInitial;
333
334     /** Set to true once doDie() has been called. */
335     private boolean mRemoved;
336
337     private final boolean mWindowIsRound;
338
339     /**
340      * Consistency verifier for debugging purposes.
341      */
342     protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
343             InputEventConsistencyVerifier.isInstrumentationEnabled() ?
344                     new InputEventConsistencyVerifier(this, 0) : null;
345
346     static final class SystemUiVisibilityInfo {
347         int seq;
348         int globalVisibility;
349         int localValue;
350         int localChanges;
351     }
352
353     public ViewRootImpl(Context context, Display display) {
354         mContext = context;
355         mWindowSession = WindowManagerGlobal.getWindowSession();
356         mDisplay = display;
357         mBasePackageName = context.getBasePackageName();
358
359         mDisplayAdjustments = display.getDisplayAdjustments();
360
361         mThread = Thread.currentThread();
362         mLocation = new WindowLeaked(null);
363         mLocation.fillInStackTrace();
364         mWidth = -1;
365         mHeight = -1;
366         mDirty = new Rect();
367         mTempRect = new Rect();
368         mVisRect = new Rect();
369         mWinFrame = new Rect();
370         mWindow = new W(this);
371         mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
372         mViewVisibility = View.GONE;
373         mTransparentRegion = new Region();
374         mPreviousTransparentRegion = new Region();
375         mFirst = true; // true for the first time the view is added
376         mAdded = false;
377         mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
378         mAccessibilityManager = AccessibilityManager.getInstance(context);
379         mAccessibilityInteractionConnectionManager =
380             new AccessibilityInteractionConnectionManager();
381         mAccessibilityManager.addAccessibilityStateChangeListener(
382                 mAccessibilityInteractionConnectionManager);
383         mHighContrastTextManager = new HighContrastTextManager();
384         mAccessibilityManager.addHighTextContrastStateChangeListener(
385                 mHighContrastTextManager);
386         mViewConfiguration = ViewConfiguration.get(context);
387         mDensity = context.getResources().getDisplayMetrics().densityDpi;
388         mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
389         mFallbackEventHandler = new PhoneFallbackEventHandler(context);
390         mChoreographer = Choreographer.getInstance();
391         mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
392         loadSystemProperties();
393         mWindowIsRound = ScreenShapeHelper.getWindowIsRound(context.getResources());
394     }
395
396     public static void addFirstDrawHandler(Runnable callback) {
397         synchronized (sFirstDrawHandlers) {
398             if (!sFirstDrawComplete) {
399                 sFirstDrawHandlers.add(callback);
400             }
401         }
402     }
403
404     public static void addConfigCallback(ComponentCallbacks callback) {
405         synchronized (sConfigCallbacks) {
406             sConfigCallbacks.add(callback);
407         }
408     }
409
410     // FIXME for perf testing only
411     private boolean mProfile = false;
412
413     /**
414      * Call this to profile the next traversal call.
415      * FIXME for perf testing only. Remove eventually
416      */
417     public void profile() {
418         mProfile = true;
419     }
420
421     /**
422      * Indicates whether we are in touch mode. Calling this method triggers an IPC
423      * call and should be avoided whenever possible.
424      *
425      * @return True, if the device is in touch mode, false otherwise.
426      *
427      * @hide
428      */
429     static boolean isInTouchMode() {
430         IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
431         if (windowSession != null) {
432             try {
433                 return windowSession.getInTouchMode();
434             } catch (RemoteException e) {
435             }
436         }
437         return false;
438     }
439
440     /**
441      * We have one child
442      */
443     public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
444         synchronized (this) {
445             if (mView == null) {
446                 mView = view;
447
448                 mAttachInfo.mDisplayState = mDisplay.getState();
449                 mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);
450
451                 mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
452                 mFallbackEventHandler.setView(view);
453                 mWindowAttributes.copyFrom(attrs);
454                 if (mWindowAttributes.packageName == null) {
455                     mWindowAttributes.packageName = mBasePackageName;
456                 }
457                 attrs = mWindowAttributes;
458                 // Keep track of the actual window flags supplied by the client.
459                 mClientWindowLayoutFlags = attrs.flags;
460
461                 setAccessibilityFocus(null, null);
462
463                 if (view instanceof RootViewSurfaceTaker) {
464                     mSurfaceHolderCallback =
465                             ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
466                     if (mSurfaceHolderCallback != null) {
467                         mSurfaceHolder = new TakenSurfaceHolder();
468                         mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
469                     }
470                 }
471
472                 // Compute surface insets required to draw at specified Z value.
473                 // TODO: Use real shadow insets for a constant max Z.
474                 if (!attrs.hasManualSurfaceInsets) {
475                     final int surfaceInset = (int) Math.ceil(view.getZ() * 2);
476                     attrs.surfaceInsets.set(surfaceInset, surfaceInset, surfaceInset, surfaceInset);
477                 }
478
479                 CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
480                 mTranslator = compatibilityInfo.getTranslator();
481
482                 // If the application owns the surface, don't enable hardware acceleration
483                 if (mSurfaceHolder == null) {
484                     enableHardwareAcceleration(attrs);
485                 }
486
487                 boolean restore = false;
488                 if (mTranslator != null) {
489                     mSurface.setCompatibilityTranslator(mTranslator);
490                     restore = true;
491                     attrs.backup();
492                     mTranslator.translateWindowLayout(attrs);
493                 }
494                 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
495
496                 if (!compatibilityInfo.supportsScreen()) {
497                     attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
498                     mLastInCompatMode = true;
499                 }
500
501                 mSoftInputMode = attrs.softInputMode;
502                 mWindowAttributesChanged = true;
503                 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
504                 mAttachInfo.mRootView = view;
505                 mAttachInfo.mScalingRequired = mTranslator != null;
506                 mAttachInfo.mApplicationScale =
507                         mTranslator == null ? 1.0f : mTranslator.applicationScale;
508                 if (panelParentView != null) {
509                     mAttachInfo.mPanelParentWindowToken
510                             = panelParentView.getApplicationWindowToken();
511                 }
512                 mAdded = true;
513                 int res; /* = WindowManagerImpl.ADD_OKAY; */
514
515                 // Schedule the first layout -before- adding to the window
516                 // manager, to make sure we do the relayout before receiving
517                 // any other events from the system.
518                 requestLayout();
519                 if ((mWindowAttributes.inputFeatures
520                         & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
521                     mInputChannel = new InputChannel();
522                 }
523                 try {
524                     mOrigWindowType = mWindowAttributes.type;
525                     mAttachInfo.mRecomputeGlobalAttributes = true;
526                     collectViewAttributes();
527                     res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
528                             getHostVisibility(), mDisplay.getDisplayId(),
529                             mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mInputChannel);
530                 } catch (RemoteException e) {
531                     mAdded = false;
532                     mView = null;
533                     mAttachInfo.mRootView = null;
534                     mInputChannel = null;
535                     mFallbackEventHandler.setView(null);
536                     unscheduleTraversals();
537                     setAccessibilityFocus(null, null);
538                     throw new RuntimeException("Adding window failed", e);
539                 } finally {
540                     if (restore) {
541                         attrs.restore();
542                     }
543                 }
544
545                 if (mTranslator != null) {
546                     mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
547                 }
548                 mPendingOverscanInsets.set(0, 0, 0, 0);
549                 mPendingContentInsets.set(mAttachInfo.mContentInsets);
550                 mPendingStableInsets.set(mAttachInfo.mStableInsets);
551                 mPendingVisibleInsets.set(0, 0, 0, 0);
552                 try {
553                     relayoutWindow(attrs, getHostVisibility(), false);
554                 } catch (RemoteException e) {
555                     if (DEBUG_LAYOUT) Log.e(TAG, "failed to relayoutWindow", e);
556                 }
557                 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
558                 if (res < WindowManagerGlobal.ADD_OKAY) {
559                     mAttachInfo.mRootView = null;
560                     mAdded = false;
561                     mFallbackEventHandler.setView(null);
562                     unscheduleTraversals();
563                     setAccessibilityFocus(null, null);
564                     switch (res) {
565                         case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
566                         case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
567                             throw new WindowManager.BadTokenException(
568                                     "Unable to add window -- token " + attrs.token
569                                     + " is not valid; is your activity running?");
570                         case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
571                             throw new WindowManager.BadTokenException(
572                                     "Unable to add window -- token " + attrs.token
573                                     + " is not for an application");
574                         case WindowManagerGlobal.ADD_APP_EXITING:
575                             throw new WindowManager.BadTokenException(
576                                     "Unable to add window -- app for token " + attrs.token
577                                     + " is exiting");
578                         case WindowManagerGlobal.ADD_DUPLICATE_ADD:
579                             throw new WindowManager.BadTokenException(
580                                     "Unable to add window -- window " + mWindow
581                                     + " has already been added");
582                         case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
583                             // Silently ignore -- we would have just removed it
584                             // right away, anyway.
585                             return;
586                         case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
587                             throw new WindowManager.BadTokenException(
588                                     "Unable to add window " + mWindow +
589                                     " -- another window of this type already exists");
590                         case WindowManagerGlobal.ADD_PERMISSION_DENIED:
591                             throw new WindowManager.BadTokenException(
592                                     "Unable to add window " + mWindow +
593                                     " -- permission denied for this window type");
594                         case WindowManagerGlobal.ADD_INVALID_DISPLAY:
595                             throw new WindowManager.InvalidDisplayException(
596                                     "Unable to add window " + mWindow +
597                                     " -- the specified display can not be found");
598                         case WindowManagerGlobal.ADD_INVALID_TYPE:
599                             throw new WindowManager.InvalidDisplayException(
600                                     "Unable to add window " + mWindow
601                                     + " -- the specified window type is not valid");
602                     }
603                     throw new RuntimeException(
604                             "Unable to add window -- unknown error code " + res);
605                 }
606
607                 if (view instanceof RootViewSurfaceTaker) {
608                     mInputQueueCallback =
609                         ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
610                 }
611                 if (mInputChannel != null) {
612                     if (mInputQueueCallback != null) {
613                         mInputQueue = new InputQueue();
614                         mInputQueueCallback.onInputQueueCreated(mInputQueue);
615                     }
616                     mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
617                             Looper.myLooper());
618                 }
619
620                 view.assignParent(this);
621                 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
622                 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
623
624                 if (mAccessibilityManager.isEnabled()) {
625                     mAccessibilityInteractionConnectionManager.ensureConnection();
626                 }
627
628                 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
629                     view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
630                 }
631
632                 // Set up the input pipeline.
633                 CharSequence counterSuffix = attrs.getTitle();
634                 mSyntheticInputStage = new SyntheticInputStage();
635                 InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
636                 InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
637                         "aq:native-post-ime:" + counterSuffix);
638                 InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
639                 InputStage imeStage = new ImeInputStage(earlyPostImeStage,
640                         "aq:ime:" + counterSuffix);
641                 InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
642                 InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
643                         "aq:native-pre-ime:" + counterSuffix);
644
645                 mFirstInputStage = nativePreImeStage;
646                 mFirstPostImeInputStage = earlyPostImeStage;
647                 mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
648             }
649         }
650     }
651
652     /** Whether the window is in local focus mode or not */
653     private boolean isInLocalFocusMode() {
654         return (mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE) != 0;
655     }
656
657     public CharSequence getTitle() {
658         return mWindowAttributes.getTitle();
659     }
660
661     void destroyHardwareResources() {
662         if (mAttachInfo.mHardwareRenderer != null) {
663             mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
664             mAttachInfo.mHardwareRenderer.destroy();
665         }
666     }
667
668     public void detachFunctor(long functor) {
669         // TODO: Make the resize buffer some other way to not need this block
670         mBlockResizeBuffer = true;
671         if (mAttachInfo.mHardwareRenderer != null) {
672             // Fence so that any pending invokeFunctor() messages will be processed
673             // before we return from detachFunctor.
674             mAttachInfo.mHardwareRenderer.stopDrawing();
675         }
676     }
677
678     /**
679      * Schedules the functor for execution in either kModeProcess or
680      * kModeProcessNoContext, depending on whether or not there is an EGLContext.
681      *
682      * @param functor The native functor to invoke
683      * @param waitForCompletion If true, this will not return until the functor
684      *                          has invoked. If false, the functor may be invoked
685      *                          asynchronously.
686      */
687     public void invokeFunctor(long functor, boolean waitForCompletion) {
688         ThreadedRenderer.invokeFunctor(functor, waitForCompletion);
689     }
690
691     public void registerAnimatingRenderNode(RenderNode animator) {
692         if (mAttachInfo.mHardwareRenderer != null) {
693             mAttachInfo.mHardwareRenderer.registerAnimatingRenderNode(animator);
694         } else {
695             if (mAttachInfo.mPendingAnimatingRenderNodes == null) {
696                 mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>();
697             }
698             mAttachInfo.mPendingAnimatingRenderNodes.add(animator);
699         }
700     }
701
702     private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
703         mAttachInfo.mHardwareAccelerated = false;
704         mAttachInfo.mHardwareAccelerationRequested = false;
705
706         // Don't enable hardware acceleration when the application is in compatibility mode
707         if (mTranslator != null) return;
708
709         // Try to enable hardware acceleration if requested
710         final boolean hardwareAccelerated =
711                 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
712
713         if (hardwareAccelerated) {
714             if (!HardwareRenderer.isAvailable()) {
715                 return;
716             }
717
718             // Persistent processes (including the system) should not do
719             // accelerated rendering on low-end devices.  In that case,
720             // sRendererDisabled will be set.  In addition, the system process
721             // itself should never do accelerated rendering.  In that case, both
722             // sRendererDisabled and sSystemRendererDisabled are set.  When
723             // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
724             // can be used by code on the system process to escape that and enable
725             // HW accelerated drawing.  (This is basically for the lock screen.)
726
727             final boolean fakeHwAccelerated = (attrs.privateFlags &
728                     WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
729             final boolean forceHwAccelerated = (attrs.privateFlags &
730                     WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
731
732             if (fakeHwAccelerated) {
733                 // This is exclusively for the preview windows the window manager
734                 // shows for launching applications, so they will look more like
735                 // the app being launched.
736                 mAttachInfo.mHardwareAccelerationRequested = true;
737             } else if (!HardwareRenderer.sRendererDisabled
738                     || (HardwareRenderer.sSystemRendererDisabled && forceHwAccelerated)) {
739                 if (mAttachInfo.mHardwareRenderer != null) {
740                     mAttachInfo.mHardwareRenderer.destroy();
741                 }
742
743                 final Rect insets = attrs.surfaceInsets;
744                 final boolean hasSurfaceInsets = insets.left != 0 || insets.right != 0
745                         || insets.top != 0 || insets.bottom != 0;
746                 final boolean translucent = attrs.format != PixelFormat.OPAQUE || hasSurfaceInsets;
747                 mAttachInfo.mHardwareRenderer = HardwareRenderer.create(mContext, translucent);
748                 if (mAttachInfo.mHardwareRenderer != null) {
749                     mAttachInfo.mHardwareRenderer.setName(attrs.getTitle().toString());
750                     mAttachInfo.mHardwareAccelerated =
751                             mAttachInfo.mHardwareAccelerationRequested = true;
752                 }
753             }
754         }
755     }
756
757     public View getView() {
758         return mView;
759     }
760
761     final WindowLeaked getLocation() {
762         return mLocation;
763     }
764
765     void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
766         synchronized (this) {
767             final int oldInsetLeft = mWindowAttributes.surfaceInsets.left;
768             final int oldInsetTop = mWindowAttributes.surfaceInsets.top;
769             final int oldInsetRight = mWindowAttributes.surfaceInsets.right;
770             final int oldInsetBottom = mWindowAttributes.surfaceInsets.bottom;
771             final int oldSoftInputMode = mWindowAttributes.softInputMode;
772             final boolean oldHasManualSurfaceInsets = mWindowAttributes.hasManualSurfaceInsets;
773
774             // Keep track of the actual window flags supplied by the client.
775             mClientWindowLayoutFlags = attrs.flags;
776
777             // Preserve compatible window flag if exists.
778             final int compatibleWindowFlag = mWindowAttributes.privateFlags
779                     & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
780
781             // Transfer over system UI visibility values as they carry current state.
782             attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
783             attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
784
785             mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
786             if ((mWindowAttributesChangesFlag
787                     & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) {
788                 // Recompute system ui visibility.
789                 mAttachInfo.mRecomputeGlobalAttributes = true;
790             }
791             if (mWindowAttributes.packageName == null) {
792                 mWindowAttributes.packageName = mBasePackageName;
793             }
794             mWindowAttributes.privateFlags |= compatibleWindowFlag;
795
796             // Restore old surface insets.
797             mWindowAttributes.surfaceInsets.set(
798                     oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
799             mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
800
801             applyKeepScreenOnFlag(mWindowAttributes);
802
803             if (newView) {
804                 mSoftInputMode = attrs.softInputMode;
805                 requestLayout();
806             }
807
808             // Don't lose the mode we last auto-computed.
809             if ((attrs.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
810                     == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
811                 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
812                         & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
813                         | (oldSoftInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
814             }
815
816             mWindowAttributesChanged = true;
817             scheduleTraversals();
818         }
819     }
820
821     void handleAppVisibility(boolean visible) {
822         if (mAppVisible != visible) {
823             mAppVisible = visible;
824             scheduleTraversals();
825             if (!mAppVisible) {
826                 WindowManagerGlobal.trimForeground();
827             }
828         }
829     }
830
831     void handleGetNewSurface() {
832         mNewSurfaceNeeded = true;
833         mFullRedrawNeeded = true;
834         scheduleTraversals();
835     }
836
837     private final DisplayListener mDisplayListener = new DisplayListener() {
838         @Override
839         public void onDisplayChanged(int displayId) {
840             if (mView != null && mDisplay.getDisplayId() == displayId) {
841                 final int oldDisplayState = mAttachInfo.mDisplayState;
842                 final int newDisplayState = mDisplay.getState();
843                 if (oldDisplayState != newDisplayState) {
844                     mAttachInfo.mDisplayState = newDisplayState;
845                     pokeDrawLockIfNeeded();
846                     if (oldDisplayState != Display.STATE_UNKNOWN) {
847                         final int oldScreenState = toViewScreenState(oldDisplayState);
848                         final int newScreenState = toViewScreenState(newDisplayState);
849                         if (oldScreenState != newScreenState) {
850                             mView.dispatchScreenStateChanged(newScreenState);
851                         }
852                         if (oldDisplayState == Display.STATE_OFF) {
853                             // Draw was suppressed so we need to for it to happen here.
854                             mFullRedrawNeeded = true;
855                             scheduleTraversals();
856                         }
857                     }
858                 }
859             }
860         }
861
862         @Override
863         public void onDisplayRemoved(int displayId) {
864         }
865
866         @Override
867         public void onDisplayAdded(int displayId) {
868         }
869
870         private int toViewScreenState(int displayState) {
871             return displayState == Display.STATE_OFF ?
872                     View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON;
873         }
874     };
875
876     void pokeDrawLockIfNeeded() {
877         final int displayState = mAttachInfo.mDisplayState;
878         if (mView != null && mAdded && mTraversalScheduled
879                 && (displayState == Display.STATE_DOZE
880                         || displayState == Display.STATE_DOZE_SUSPEND)) {
881             try {
882                 mWindowSession.pokeDrawLock(mWindow);
883             } catch (RemoteException ex) {
884                 // System server died, oh well.
885             }
886         }
887     }
888
889     @Override
890     public void requestFitSystemWindows() {
891         checkThread();
892         mApplyInsetsRequested = true;
893         scheduleTraversals();
894     }
895
896     @Override
897     public void requestLayout() {
898         if (!mHandlingLayoutInLayoutRequest) {
899             checkThread();
900             mLayoutRequested = true;
901             scheduleTraversals();
902         }
903     }
904
905     @Override
906     public boolean isLayoutRequested() {
907         return mLayoutRequested;
908     }
909
910     void invalidate() {
911         mDirty.set(0, 0, mWidth, mHeight);
912         if (!mWillDrawSoon) {
913             scheduleTraversals();
914         }
915     }
916
917     void invalidateWorld(View view) {
918         view.invalidate();
919         if (view instanceof ViewGroup) {
920             ViewGroup parent = (ViewGroup) view;
921             for (int i = 0; i < parent.getChildCount(); i++) {
922                 invalidateWorld(parent.getChildAt(i));
923             }
924         }
925     }
926
927     @Override
928     public void invalidateChild(View child, Rect dirty) {
929         invalidateChildInParent(null, dirty);
930     }
931
932     @Override
933     public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
934         checkThread();
935         if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
936
937         if (dirty == null) {
938             invalidate();
939             return null;
940         } else if (dirty.isEmpty() && !mIsAnimating) {
941             return null;
942         }
943
944         if (mCurScrollY != 0 || mTranslator != null) {
945             mTempRect.set(dirty);
946             dirty = mTempRect;
947             if (mCurScrollY != 0) {
948                 dirty.offset(0, -mCurScrollY);
949             }
950             if (mTranslator != null) {
951                 mTranslator.translateRectInAppWindowToScreen(dirty);
952             }
953             if (mAttachInfo.mScalingRequired) {
954                 dirty.inset(-1, -1);
955             }
956         }
957
958         final Rect localDirty = mDirty;
959         if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
960             mAttachInfo.mSetIgnoreDirtyState = true;
961             mAttachInfo.mIgnoreDirtyState = true;
962         }
963
964         // Add the new dirty rect to the current one
965         localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
966         // Intersect with the bounds of the window to skip
967         // updates that lie outside of the visible region
968         final float appScale = mAttachInfo.mApplicationScale;
969         final boolean intersected = localDirty.intersect(0, 0,
970                 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
971         if (!intersected) {
972             localDirty.setEmpty();
973         }
974         if (!mWillDrawSoon && (intersected || mIsAnimating)) {
975             scheduleTraversals();
976         }
977
978         return null;
979     }
980
981     void setStopped(boolean stopped) {
982         if (mStopped != stopped) {
983             mStopped = stopped;
984             if (!stopped) {
985                 scheduleTraversals();
986             }
987         }
988     }
989
990     @Override
991     public ViewParent getParent() {
992         return null;
993     }
994
995     @Override
996     public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
997         if (child != mView) {
998             throw new RuntimeException("child is not mine, honest!");
999         }
1000         // Note: don't apply scroll offset, because we want to know its
1001         // visibility in the virtual canvas being given to the view hierarchy.
1002         return r.intersect(0, 0, mWidth, mHeight);
1003     }
1004
1005     @Override
1006     public void bringChildToFront(View child) {
1007     }
1008
1009     int getHostVisibility() {
1010         return mAppVisible ? mView.getVisibility() : View.GONE;
1011     }
1012
1013     void disposeResizeBuffer() {
1014         if (mResizeBuffer != null) {
1015             mResizeBuffer.destroy();
1016             mResizeBuffer = null;
1017         }
1018     }
1019
1020     /**
1021      * Add LayoutTransition to the list of transitions to be started in the next traversal.
1022      * This list will be cleared after the transitions on the list are start()'ed. These
1023      * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
1024      * happens during the layout phase of traversal, which we want to complete before any of the
1025      * animations are started (because those animations may side-effect properties that layout
1026      * depends upon, like the bounding rectangles of the affected views). So we add the transition
1027      * to the list and it is started just prior to starting the drawing phase of traversal.
1028      *
1029      * @param transition The LayoutTransition to be started on the next traversal.
1030      *
1031      * @hide
1032      */
1033     public void requestTransitionStart(LayoutTransition transition) {
1034         if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
1035             if (mPendingTransitions == null) {
1036                  mPendingTransitions = new ArrayList<LayoutTransition>();
1037             }
1038             mPendingTransitions.add(transition);
1039         }
1040     }
1041
1042     /**
1043      * Notifies the HardwareRenderer that a new frame will be coming soon.
1044      * Currently only {@link ThreadedRenderer} cares about this, and uses
1045      * this knowledge to adjust the scheduling of off-thread animations
1046      */
1047     void notifyRendererOfFramePending() {
1048         if (mAttachInfo.mHardwareRenderer != null) {
1049             mAttachInfo.mHardwareRenderer.notifyFramePending();
1050         }
1051     }
1052
1053     void scheduleTraversals() {
1054         if (!mTraversalScheduled) {
1055             mTraversalScheduled = true;
1056             mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
1057             mChoreographer.postCallback(
1058                     Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1059             if (!mUnbufferedInputDispatch) {
1060                 scheduleConsumeBatchedInput();
1061             }
1062             notifyRendererOfFramePending();
1063             pokeDrawLockIfNeeded();
1064         }
1065     }
1066
1067     void unscheduleTraversals() {
1068         if (mTraversalScheduled) {
1069             mTraversalScheduled = false;
1070             mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1071             mChoreographer.removeCallbacks(
1072                     Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1073         }
1074     }
1075
1076     void doTraversal() {
1077         if (mTraversalScheduled) {
1078             mTraversalScheduled = false;
1079             mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1080
1081             if (mProfile) {
1082                 Debug.startMethodTracing("ViewAncestor");
1083             }
1084
1085             Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
1086             try {
1087                 performTraversals();
1088             } finally {
1089                 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1090             }
1091
1092             if (mProfile) {
1093                 Debug.stopMethodTracing();
1094                 mProfile = false;
1095             }
1096         }
1097     }
1098
1099     private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1100         // Update window's global keep screen on flag: if a view has requested
1101         // that the screen be kept on, then it is always set; otherwise, it is
1102         // set to whatever the client last requested for the global state.
1103         if (mAttachInfo.mKeepScreenOn) {
1104             params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1105         } else {
1106             params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1107                     | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1108         }
1109     }
1110
1111     private boolean collectViewAttributes() {
1112         if (mAttachInfo.mRecomputeGlobalAttributes) {
1113             //Log.i(TAG, "Computing view hierarchy attributes!");
1114             mAttachInfo.mRecomputeGlobalAttributes = false;
1115             boolean oldScreenOn = mAttachInfo.mKeepScreenOn;
1116             mAttachInfo.mKeepScreenOn = false;
1117             mAttachInfo.mSystemUiVisibility = 0;
1118             mAttachInfo.mHasSystemUiListeners = false;
1119             mView.dispatchCollectViewAttributes(mAttachInfo, 0);
1120             mAttachInfo.mSystemUiVisibility &= ~mAttachInfo.mDisabledSystemUiVisibility;
1121             WindowManager.LayoutParams params = mWindowAttributes;
1122             mAttachInfo.mSystemUiVisibility |= getImpliedSystemUiVisibility(params);
1123             if (mAttachInfo.mKeepScreenOn != oldScreenOn
1124                     || mAttachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1125                     || mAttachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
1126                 applyKeepScreenOnFlag(params);
1127                 params.subtreeSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1128                 params.hasSystemUiListeners = mAttachInfo.mHasSystemUiListeners;
1129                 mView.dispatchWindowSystemUiVisiblityChanged(mAttachInfo.mSystemUiVisibility);
1130                 return true;
1131             }
1132         }
1133         return false;
1134     }
1135
1136     private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
1137         int vis = 0;
1138         // Translucent decor window flags imply stable system ui visibility.
1139         if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
1140             vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
1141         }
1142         if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) {
1143             vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
1144         }
1145         return vis;
1146     }
1147
1148     private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1149             final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1150         int childWidthMeasureSpec;
1151         int childHeightMeasureSpec;
1152         boolean windowSizeMayChange = false;
1153
1154         if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
1155                 "Measuring " + host + " in display " + desiredWindowWidth
1156                 + "x" + desiredWindowHeight + "...");
1157
1158         boolean goodMeasure = false;
1159         if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1160             // On large screens, we don't want to allow dialogs to just
1161             // stretch to fill the entire width of the screen to display
1162             // one line of text.  First try doing the layout at a smaller
1163             // size to see if it will fit.
1164             final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1165             res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1166             int baseSize = 0;
1167             if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1168                 baseSize = (int)mTmpValue.getDimension(packageMetrics);
1169             }
1170             if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
1171             if (baseSize != 0 && desiredWindowWidth > baseSize) {
1172                 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1173                 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1174                 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1175                 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1176                         + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1177                 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1178                     goodMeasure = true;
1179                 } else {
1180                     // Didn't fit in that size... try expanding a bit.
1181                     baseSize = (baseSize+desiredWindowWidth)/2;
1182                     if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
1183                             + baseSize);
1184                     childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1185                     performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1186                     if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1187                             + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1188                     if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1189                         if (DEBUG_DIALOG) Log.v(TAG, "Good!");
1190                         goodMeasure = true;
1191                     }
1192                 }
1193             }
1194         }
1195
1196         if (!goodMeasure) {
1197             childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1198             childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1199             performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1200             if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1201                 windowSizeMayChange = true;
1202             }
1203         }
1204
1205         if (DBG) {
1206             System.out.println("======================================");
1207             System.out.println("performTraversals -- after measure");
1208             host.debug();
1209         }
1210
1211         return windowSizeMayChange;
1212     }
1213
1214     /**
1215      * Modifies the input matrix such that it maps view-local coordinates to
1216      * on-screen coordinates.
1217      *
1218      * @param m input matrix to modify
1219      */
1220     void transformMatrixToGlobal(Matrix m) {
1221         m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
1222     }
1223
1224     /**
1225      * Modifies the input matrix such that it maps on-screen coordinates to
1226      * view-local coordinates.
1227      *
1228      * @param m input matrix to modify
1229      */
1230     void transformMatrixToLocal(Matrix m) {
1231         m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
1232     }
1233
1234     /* package */ WindowInsets getWindowInsets(boolean forceConstruct) {
1235         if (mLastWindowInsets == null || forceConstruct) {
1236             mDispatchContentInsets.set(mAttachInfo.mContentInsets);
1237             mDispatchStableInsets.set(mAttachInfo.mStableInsets);
1238             Rect contentInsets = mDispatchContentInsets;
1239             Rect stableInsets = mDispatchStableInsets;
1240             // For dispatch we preserve old logic, but for direct requests from Views we allow to
1241             // immediately use pending insets.
1242             if (!forceConstruct
1243                     && (!mPendingContentInsets.equals(contentInsets) ||
1244                         !mPendingStableInsets.equals(stableInsets))) {
1245                 contentInsets = mPendingContentInsets;
1246                 stableInsets = mPendingStableInsets;
1247             }
1248             mLastWindowInsets = new WindowInsets(contentInsets,
1249                     null /* windowDecorInsets */, stableInsets, mWindowIsRound);
1250         }
1251         return mLastWindowInsets;
1252     }
1253
1254     void dispatchApplyInsets(View host) {
1255         host.dispatchApplyWindowInsets(getWindowInsets(true /* forceConstruct */));
1256     }
1257
1258     private void performTraversals() {
1259         // cache mView since it is used so much below...
1260         final View host = mView;
1261
1262         if (DBG) {
1263             System.out.println("======================================");
1264             System.out.println("performTraversals");
1265             host.debug();
1266         }
1267
1268         if (host == null || !mAdded)
1269             return;
1270
1271         mIsInTraversal = true;
1272         mWillDrawSoon = true;
1273         boolean windowSizeMayChange = false;
1274         boolean newSurface = false;
1275         boolean surfaceChanged = false;
1276         WindowManager.LayoutParams lp = mWindowAttributes;
1277
1278         int desiredWindowWidth;
1279         int desiredWindowHeight;
1280
1281         final int viewVisibility = getHostVisibility();
1282         boolean viewVisibilityChanged = mViewVisibility != viewVisibility
1283                 || mNewSurfaceNeeded;
1284
1285         WindowManager.LayoutParams params = null;
1286         if (mWindowAttributesChanged) {
1287             mWindowAttributesChanged = false;
1288             surfaceChanged = true;
1289             params = lp;
1290         }
1291         CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
1292         if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1293             params = lp;
1294             mFullRedrawNeeded = true;
1295             mLayoutRequested = true;
1296             if (mLastInCompatMode) {
1297                 params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1298                 mLastInCompatMode = false;
1299             } else {
1300                 params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1301                 mLastInCompatMode = true;
1302             }
1303         }
1304
1305         mWindowAttributesChangesFlag = 0;
1306
1307         Rect frame = mWinFrame;
1308         if (mFirst) {
1309             mFullRedrawNeeded = true;
1310             mLayoutRequested = true;
1311
1312             if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
1313                     || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
1314                 // NOTE -- system code, won't try to do compat mode.
1315                 Point size = new Point();
1316                 mDisplay.getRealSize(size);
1317                 desiredWindowWidth = size.x;
1318                 desiredWindowHeight = size.y;
1319             } else {
1320                 DisplayMetrics packageMetrics =
1321                     mView.getContext().getResources().getDisplayMetrics();
1322                 desiredWindowWidth = packageMetrics.widthPixels;
1323                 desiredWindowHeight = packageMetrics.heightPixels;
1324             }
1325
1326             // We used to use the following condition to choose 32 bits drawing caches:
1327             // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1328             // However, windows are now always 32 bits by default, so choose 32 bits
1329             mAttachInfo.mUse32BitDrawingCache = true;
1330             mAttachInfo.mHasWindowFocus = false;
1331             mAttachInfo.mWindowVisibility = viewVisibility;
1332             mAttachInfo.mRecomputeGlobalAttributes = false;
1333             viewVisibilityChanged = false;
1334             mLastConfiguration.setTo(host.getResources().getConfiguration());
1335             mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1336             // Set the layout direction if it has not been set before (inherit is the default)
1337             if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1338                 host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1339             }
1340             host.dispatchAttachedToWindow(mAttachInfo, 0);
1341             mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
1342             dispatchApplyInsets(host);
1343             //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
1344
1345         } else {
1346             desiredWindowWidth = frame.width();
1347             desiredWindowHeight = frame.height();
1348             if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
1349                 if (DEBUG_ORIENTATION) Log.v(TAG,
1350                         "View " + host + " resized to: " + frame);
1351                 mFullRedrawNeeded = true;
1352                 mLayoutRequested = true;
1353                 windowSizeMayChange = true;
1354             }
1355         }
1356
1357         if (viewVisibilityChanged) {
1358             mAttachInfo.mWindowVisibility = viewVisibility;
1359             host.dispatchWindowVisibilityChanged(viewVisibility);
1360             if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1361                 destroyHardwareResources();
1362             }
1363             if (viewVisibility == View.GONE) {
1364                 // After making a window gone, we will count it as being
1365                 // shown for the first time the next time it gets focus.
1366                 mHasHadWindowFocus = false;
1367             }
1368         }
1369
1370         // Non-visible windows can't hold accessibility focus.
1371         if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
1372             host.clearAccessibilityFocus();
1373         }
1374
1375         // Execute enqueued actions on every traversal in case a detached view enqueued an action
1376         getRunQueue().executeActions(mAttachInfo.mHandler);
1377
1378         boolean insetsChanged = false;
1379
1380         boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
1381         if (layoutRequested) {
1382
1383             final Resources res = mView.getContext().getResources();
1384
1385             if (mFirst) {
1386                 // make sure touch mode code executes by setting cached value
1387                 // to opposite of the added touch mode.
1388                 mAttachInfo.mInTouchMode = !mAddedTouchMode;
1389                 ensureTouchModeLocally(mAddedTouchMode);
1390             } else {
1391                 if (!mPendingOverscanInsets.equals(mAttachInfo.mOverscanInsets)) {
1392                     insetsChanged = true;
1393                 }
1394                 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
1395                     insetsChanged = true;
1396                 }
1397                 if (!mPendingStableInsets.equals(mAttachInfo.mStableInsets)) {
1398                     insetsChanged = true;
1399                 }
1400                 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
1401                     mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1402                     if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1403                             + mAttachInfo.mVisibleInsets);
1404                 }
1405                 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1406                         || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
1407                     windowSizeMayChange = true;
1408
1409                     if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
1410                             || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
1411                         // NOTE -- system code, won't try to do compat mode.
1412                         Point size = new Point();
1413                         mDisplay.getRealSize(size);
1414                         desiredWindowWidth = size.x;
1415                         desiredWindowHeight = size.y;
1416                     } else {
1417                         DisplayMetrics packageMetrics = res.getDisplayMetrics();
1418                         desiredWindowWidth = packageMetrics.widthPixels;
1419                         desiredWindowHeight = packageMetrics.heightPixels;
1420                     }
1421                 }
1422             }
1423
1424             // Ask host how big it wants to be
1425             windowSizeMayChange |= measureHierarchy(host, lp, res,
1426                     desiredWindowWidth, desiredWindowHeight);
1427         }
1428
1429         if (collectViewAttributes()) {
1430             params = lp;
1431         }
1432         if (mAttachInfo.mForceReportNewAttributes) {
1433             mAttachInfo.mForceReportNewAttributes = false;
1434             params = lp;
1435         }
1436
1437         if (mFirst || mAttachInfo.mViewVisibilityChanged) {
1438             mAttachInfo.mViewVisibilityChanged = false;
1439             int resizeMode = mSoftInputMode &
1440                     WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1441             // If we are in auto resize mode, then we need to determine
1442             // what mode to use now.
1443             if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1444                 final int N = mAttachInfo.mScrollContainers.size();
1445                 for (int i=0; i<N; i++) {
1446                     if (mAttachInfo.mScrollContainers.get(i).isShown()) {
1447                         resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1448                     }
1449                 }
1450                 if (resizeMode == 0) {
1451                     resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1452                 }
1453                 if ((lp.softInputMode &
1454                         WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1455                     lp.softInputMode = (lp.softInputMode &
1456                             ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1457                             resizeMode;
1458                     params = lp;
1459                 }
1460             }
1461         }
1462
1463         if (params != null) {
1464             if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1465                 if (!PixelFormat.formatHasAlpha(params.format)) {
1466                     params.format = PixelFormat.TRANSLUCENT;
1467                 }
1468             }
1469             mAttachInfo.mOverscanRequested = (params.flags
1470                     & WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN) != 0;
1471         }
1472
1473         if (mApplyInsetsRequested) {
1474             mApplyInsetsRequested = false;
1475             mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1476             dispatchApplyInsets(host);
1477             if (mLayoutRequested) {
1478                 // Short-circuit catching a new layout request here, so
1479                 // we don't need to go through two layout passes when things
1480                 // change due to fitting system windows, which can happen a lot.
1481                 windowSizeMayChange |= measureHierarchy(host, lp,
1482                         mView.getContext().getResources(),
1483                         desiredWindowWidth, desiredWindowHeight);
1484             }
1485         }
1486
1487         if (layoutRequested) {
1488             // Clear this now, so that if anything requests a layout in the
1489             // rest of this function we will catch it and re-run a full
1490             // layout pass.
1491             mLayoutRequested = false;
1492         }
1493
1494         boolean windowShouldResize = layoutRequested && windowSizeMayChange
1495             && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
1496                 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1497                         frame.width() < desiredWindowWidth && frame.width() != mWidth)
1498                 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1499                         frame.height() < desiredWindowHeight && frame.height() != mHeight));
1500
1501         // Determine whether to compute insets.
1502         // If there are no inset listeners remaining then we may still need to compute
1503         // insets in case the old insets were non-empty and must be reset.
1504         final boolean computesInternalInsets =
1505                 mAttachInfo.mTreeObserver.hasComputeInternalInsetsListeners()
1506                 || mAttachInfo.mHasNonEmptyGivenInternalInsets;
1507
1508         boolean insetsPending = false;
1509         int relayoutResult = 0;
1510
1511         if (mFirst || windowShouldResize || insetsChanged ||
1512                 viewVisibilityChanged || params != null) {
1513
1514             if (viewVisibility == View.VISIBLE) {
1515                 // If this window is giving internal insets to the window
1516                 // manager, and it is being added or changing its visibility,
1517                 // then we want to first give the window manager "fake"
1518                 // insets to cause it to effectively ignore the content of
1519                 // the window during layout.  This avoids it briefly causing
1520                 // other windows to resize/move based on the raw frame of the
1521                 // window, waiting until we can finish laying out this window
1522                 // and get back to the window manager with the ultimately
1523                 // computed insets.
1524                 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1525             }
1526
1527             if (mSurfaceHolder != null) {
1528                 mSurfaceHolder.mSurfaceLock.lock();
1529                 mDrawingAllowed = true;
1530             }
1531
1532             boolean hwInitialized = false;
1533             boolean contentInsetsChanged = false;
1534             boolean hadSurface = mSurface.isValid();
1535
1536             try {
1537                 if (DEBUG_LAYOUT) {
1538                     Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1539                             host.getMeasuredHeight() + ", params=" + params);
1540                 }
1541
1542                 if (mAttachInfo.mHardwareRenderer != null) {
1543                     // relayoutWindow may decide to destroy mSurface. As that decision
1544                     // happens in WindowManager service, we need to be defensive here
1545                     // and stop using the surface in case it gets destroyed.
1546                     if (mAttachInfo.mHardwareRenderer.pauseSurface(mSurface)) {
1547                         // Animations were running so we need to push a frame
1548                         // to resume them
1549                         mDirty.set(0, 0, mWidth, mHeight);
1550                     }
1551                     mChoreographer.mFrameInfo.addFlags(FrameInfo.FLAG_WINDOW_LAYOUT_CHANGED);
1552                 }
1553                 final int surfaceGenerationId = mSurface.getGenerationId();
1554                 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1555                 if (!mDrawDuringWindowsAnimating &&
1556                         (relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) {
1557                     mWindowsAnimating = true;
1558                 }
1559
1560                 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1561                         + " overscan=" + mPendingOverscanInsets.toShortString()
1562                         + " content=" + mPendingContentInsets.toShortString()
1563                         + " visible=" + mPendingVisibleInsets.toShortString()
1564                         + " visible=" + mPendingStableInsets.toShortString()
1565                         + " surface=" + mSurface);
1566
1567                 if (mPendingConfiguration.seq != 0) {
1568                     if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1569                             + mPendingConfiguration);
1570                     updateConfiguration(mPendingConfiguration, !mFirst);
1571                     mPendingConfiguration.seq = 0;
1572                 }
1573
1574                 final boolean overscanInsetsChanged = !mPendingOverscanInsets.equals(
1575                         mAttachInfo.mOverscanInsets);
1576                 contentInsetsChanged = !mPendingContentInsets.equals(
1577                         mAttachInfo.mContentInsets);
1578                 final boolean visibleInsetsChanged = !mPendingVisibleInsets.equals(
1579                         mAttachInfo.mVisibleInsets);
1580                 final boolean stableInsetsChanged = !mPendingStableInsets.equals(
1581                         mAttachInfo.mStableInsets);
1582                 if (contentInsetsChanged) {
1583                     if (mWidth > 0 && mHeight > 0 && lp != null &&
1584                             ((lp.systemUiVisibility|lp.subtreeSystemUiVisibility)
1585                                     & View.SYSTEM_UI_LAYOUT_FLAGS) == 0 &&
1586                             mSurface != null && mSurface.isValid() &&
1587                             !mAttachInfo.mTurnOffWindowResizeAnim &&
1588                             mAttachInfo.mHardwareRenderer != null &&
1589                             mAttachInfo.mHardwareRenderer.isEnabled() &&
1590                             lp != null && !PixelFormat.formatHasAlpha(lp.format)
1591                             && !mBlockResizeBuffer) {
1592
1593                         disposeResizeBuffer();
1594
1595 // TODO: Again....
1596 //                        if (mResizeBuffer == null) {
1597 //                            mResizeBuffer = mAttachInfo.mHardwareRenderer.createDisplayListLayer(
1598 //                                    mWidth, mHeight);
1599 //                        }
1600 //                        mResizeBuffer.prepare(mWidth, mHeight, false);
1601 //                        RenderNode layerRenderNode = mResizeBuffer.startRecording();
1602 //                        HardwareCanvas layerCanvas = layerRenderNode.start(mWidth, mHeight);
1603 //                        try {
1604 //                            final int restoreCount = layerCanvas.save();
1605 //
1606 //                            int yoff;
1607 //                            final boolean scrolling = mScroller != null
1608 //                                    && mScroller.computeScrollOffset();
1609 //                            if (scrolling) {
1610 //                                yoff = mScroller.getCurrY();
1611 //                                mScroller.abortAnimation();
1612 //                            } else {
1613 //                                yoff = mScrollY;
1614 //                            }
1615 //
1616 //                            layerCanvas.translate(0, -yoff);
1617 //                            if (mTranslator != null) {
1618 //                                mTranslator.translateCanvas(layerCanvas);
1619 //                            }
1620 //
1621 //                            RenderNode renderNode = mView.mRenderNode;
1622 //                            if (renderNode != null && renderNode.isValid()) {
1623 //                                layerCanvas.drawDisplayList(renderNode, null,
1624 //                                        RenderNode.FLAG_CLIP_CHILDREN);
1625 //                            } else {
1626 //                                mView.draw(layerCanvas);
1627 //                            }
1628 //
1629 //                            drawAccessibilityFocusedDrawableIfNeeded(layerCanvas);
1630 //
1631 //                            mResizeBufferStartTime = SystemClock.uptimeMillis();
1632 //                            mResizeBufferDuration = mView.getResources().getInteger(
1633 //                                    com.android.internal.R.integer.config_mediumAnimTime);
1634 //
1635 //                            layerCanvas.restoreToCount(restoreCount);
1636 //                            layerRenderNode.end(layerCanvas);
1637 //                            layerRenderNode.setCaching(true);
1638 //                            layerRenderNode.setLeftTopRightBottom(0, 0, mWidth, mHeight);
1639 //                            mTempRect.set(0, 0, mWidth, mHeight);
1640 //                        } finally {
1641 //                            mResizeBuffer.endRecording(mTempRect);
1642 //                        }
1643 //                        mAttachInfo.mHardwareRenderer.flushLayerUpdates();
1644                     }
1645                     mAttachInfo.mContentInsets.set(mPendingContentInsets);
1646                     if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1647                             + mAttachInfo.mContentInsets);
1648                 }
1649                 if (overscanInsetsChanged) {
1650                     mAttachInfo.mOverscanInsets.set(mPendingOverscanInsets);
1651                     if (DEBUG_LAYOUT) Log.v(TAG, "Overscan insets changing to: "
1652                             + mAttachInfo.mOverscanInsets);
1653                     // Need to relayout with content insets.
1654                     contentInsetsChanged = true;
1655                 }
1656                 if (stableInsetsChanged) {
1657                     mAttachInfo.mStableInsets.set(mPendingStableInsets);
1658                     if (DEBUG_LAYOUT) Log.v(TAG, "Decor insets changing to: "
1659                             + mAttachInfo.mStableInsets);
1660                     // Need to relayout with content insets.
1661                     contentInsetsChanged = true;
1662                 }
1663                 if (contentInsetsChanged || mLastSystemUiVisibility !=
1664                         mAttachInfo.mSystemUiVisibility || mApplyInsetsRequested
1665                         || mLastOverscanRequested != mAttachInfo.mOverscanRequested) {
1666                     mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1667                     mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1668                     mApplyInsetsRequested = false;
1669                     dispatchApplyInsets(host);
1670                 }
1671                 if (visibleInsetsChanged) {
1672                     mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1673                     if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1674                             + mAttachInfo.mVisibleInsets);
1675                 }
1676
1677                 if (!hadSurface) {
1678                     if (mSurface.isValid()) {
1679                         // If we are creating a new surface, then we need to
1680                         // completely redraw it.  Also, when we get to the
1681                         // point of drawing it we will hold off and schedule
1682                         // a new traversal instead.  This is so we can tell the
1683                         // window manager about all of the windows being displayed
1684                         // before actually drawing them, so it can display then
1685                         // all at once.
1686                         newSurface = true;
1687                         mFullRedrawNeeded = true;
1688                         mPreviousTransparentRegion.setEmpty();
1689
1690                         if (mAttachInfo.mHardwareRenderer != null) {
1691                             try {
1692                                 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
1693                                         mSurface);
1694                             } catch (OutOfResourcesException e) {
1695                                 handleOutOfResourcesException(e);
1696                                 return;
1697                             }
1698                         }
1699                     }
1700                 } else if (!mSurface.isValid()) {
1701                     // If the surface has been removed, then reset the scroll
1702                     // positions.
1703                     if (mLastScrolledFocus != null) {
1704                         mLastScrolledFocus.clear();
1705                     }
1706                     mScrollY = mCurScrollY = 0;
1707                     if (mView instanceof RootViewSurfaceTaker) {
1708                         ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
1709                     }
1710                     if (mScroller != null) {
1711                         mScroller.abortAnimation();
1712                     }
1713                     disposeResizeBuffer();
1714                     // Our surface is gone
1715                     if (mAttachInfo.mHardwareRenderer != null &&
1716                             mAttachInfo.mHardwareRenderer.isEnabled()) {
1717                         mAttachInfo.mHardwareRenderer.destroy();
1718                     }
1719                 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1720                         mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1721                     mFullRedrawNeeded = true;
1722                     try {
1723                         mAttachInfo.mHardwareRenderer.updateSurface(mSurface);
1724                     } catch (OutOfResourcesException e) {
1725                         handleOutOfResourcesException(e);
1726                         return;
1727                     }
1728                 }
1729             } catch (RemoteException e) {
1730             }
1731
1732             if (DEBUG_ORIENTATION) Log.v(
1733                     TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1734
1735             mAttachInfo.mWindowLeft = frame.left;
1736             mAttachInfo.mWindowTop = frame.top;
1737
1738             // !!FIXME!! This next section handles the case where we did not get the
1739             // window size we asked for. We should avoid this by getting a maximum size from
1740             // the window session beforehand.
1741             if (mWidth != frame.width() || mHeight != frame.height()) {
1742                 mWidth = frame.width();
1743                 mHeight = frame.height();
1744             }
1745
1746             if (mSurfaceHolder != null) {
1747                 // The app owns the surface; tell it about what is going on.
1748                 if (mSurface.isValid()) {
1749                     // XXX .copyFrom() doesn't work!
1750                     //mSurfaceHolder.mSurface.copyFrom(mSurface);
1751                     mSurfaceHolder.mSurface = mSurface;
1752                 }
1753                 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1754                 mSurfaceHolder.mSurfaceLock.unlock();
1755                 if (mSurface.isValid()) {
1756                     if (!hadSurface) {
1757                         mSurfaceHolder.ungetCallbacks();
1758
1759                         mIsCreating = true;
1760                         mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1761                         SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1762                         if (callbacks != null) {
1763                             for (SurfaceHolder.Callback c : callbacks) {
1764                                 c.surfaceCreated(mSurfaceHolder);
1765                             }
1766                         }
1767                         surfaceChanged = true;
1768                     }
1769                     if (surfaceChanged) {
1770                         mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1771                                 lp.format, mWidth, mHeight);
1772                         SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1773                         if (callbacks != null) {
1774                             for (SurfaceHolder.Callback c : callbacks) {
1775                                 c.surfaceChanged(mSurfaceHolder, lp.format,
1776                                         mWidth, mHeight);
1777                             }
1778                         }
1779                     }
1780                     mIsCreating = false;
1781                 } else if (hadSurface) {
1782                     mSurfaceHolder.ungetCallbacks();
1783                     SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1784                     mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1785                     if (callbacks != null) {
1786                         for (SurfaceHolder.Callback c : callbacks) {
1787                             c.surfaceDestroyed(mSurfaceHolder);
1788                         }
1789                     }
1790                     mSurfaceHolder.mSurfaceLock.lock();
1791                     try {
1792                         mSurfaceHolder.mSurface = new Surface();
1793                     } finally {
1794                         mSurfaceHolder.mSurfaceLock.unlock();
1795                     }
1796                 }
1797             }
1798
1799             if (mAttachInfo.mHardwareRenderer != null &&
1800                     mAttachInfo.mHardwareRenderer.isEnabled()) {
1801                 if (hwInitialized ||
1802                         mWidth != mAttachInfo.mHardwareRenderer.getWidth() ||
1803                         mHeight != mAttachInfo.mHardwareRenderer.getHeight()) {
1804                     mAttachInfo.mHardwareRenderer.setup(
1805                             mWidth, mHeight, mWindowAttributes.surfaceInsets);
1806                     if (!hwInitialized) {
1807                         mAttachInfo.mHardwareRenderer.invalidate(mSurface);
1808                         mFullRedrawNeeded = true;
1809                     }
1810                 }
1811             }
1812
1813             if (!mStopped || mReportNextDraw) {
1814                 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1815                         (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
1816                 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1817                         || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1818                     int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1819                     int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1820
1821                     if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed!  mWidth="
1822                             + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1823                             + " mHeight=" + mHeight
1824                             + " measuredHeight=" + host.getMeasuredHeight()
1825                             + " coveredInsetsChanged=" + contentInsetsChanged);
1826
1827                      // Ask host how big it wants to be
1828                     performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1829
1830                     // Implementation of weights from WindowManager.LayoutParams
1831                     // We just grow the dimensions as needed and re-measure if
1832                     // needs be
1833                     int width = host.getMeasuredWidth();
1834                     int height = host.getMeasuredHeight();
1835                     boolean measureAgain = false;
1836
1837                     if (lp.horizontalWeight > 0.0f) {
1838                         width += (int) ((mWidth - width) * lp.horizontalWeight);
1839                         childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1840                                 MeasureSpec.EXACTLY);
1841                         measureAgain = true;
1842                     }
1843                     if (lp.verticalWeight > 0.0f) {
1844                         height += (int) ((mHeight - height) * lp.verticalWeight);
1845                         childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1846                                 MeasureSpec.EXACTLY);
1847                         measureAgain = true;
1848                     }
1849
1850                     if (measureAgain) {
1851                         if (DEBUG_LAYOUT) Log.v(TAG,
1852                                 "And hey let's measure once more: width=" + width
1853                                 + " height=" + height);
1854                         performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1855                     }
1856
1857                     layoutRequested = true;
1858                 }
1859             }
1860         } else {
1861             // Not the first pass and no window/insets/visibility change but the window
1862             // may have moved and we need check that and if so to update the left and right
1863             // in the attach info. We translate only the window frame since on window move
1864             // the window manager tells us only for the new frame but the insets are the
1865             // same and we do not want to translate them more than once.
1866
1867             // TODO: Well, we are checking whether the frame has changed similarly
1868             // to how this is done for the insets. This is however incorrect since
1869             // the insets and the frame are translated. For example, the old frame
1870             // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
1871             // reported frame is (2, 2 - 2, 2) which implies no change but this is not
1872             // true since we are comparing a not translated value to a translated one.
1873             // This scenario is rare but we may want to fix that.
1874
1875             final boolean windowMoved = (mAttachInfo.mWindowLeft != frame.left
1876                     || mAttachInfo.mWindowTop != frame.top);
1877             if (windowMoved) {
1878                 if (mTranslator != null) {
1879                     mTranslator.translateRectInScreenToAppWinFrame(frame);
1880                 }
1881                 mAttachInfo.mWindowLeft = frame.left;
1882                 mAttachInfo.mWindowTop = frame.top;
1883             }
1884         }
1885
1886         final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
1887         boolean triggerGlobalLayoutListener = didLayout
1888                 || mAttachInfo.mRecomputeGlobalAttributes;
1889         if (didLayout) {
1890             performLayout(lp, desiredWindowWidth, desiredWindowHeight);
1891
1892             // By this point all views have been sized and positioned
1893             // We can compute the transparent area
1894
1895             if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1896                 // start out transparent
1897                 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1898                 host.getLocationInWindow(mTmpLocation);
1899                 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1900                         mTmpLocation[0] + host.mRight - host.mLeft,
1901                         mTmpLocation[1] + host.mBottom - host.mTop);
1902
1903                 host.gatherTransparentRegion(mTransparentRegion);
1904                 if (mTranslator != null) {
1905                     mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1906                 }
1907
1908                 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1909                     mPreviousTransparentRegion.set(mTransparentRegion);
1910                     mFullRedrawNeeded = true;
1911                     // reconfigure window manager
1912                     try {
1913                         mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1914                     } catch (RemoteException e) {
1915                     }
1916                 }
1917             }
1918
1919             if (DBG) {
1920                 System.out.println("======================================");
1921                 System.out.println("performTraversals -- after setFrame");
1922                 host.debug();
1923             }
1924         }
1925
1926         if (triggerGlobalLayoutListener) {
1927             mAttachInfo.mRecomputeGlobalAttributes = false;
1928             mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
1929         }
1930
1931         if (computesInternalInsets) {
1932             // Clear the original insets.
1933             final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
1934             insets.reset();
1935
1936             // Compute new insets in place.
1937             mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
1938             mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
1939
1940             // Tell the window manager.
1941             if (insetsPending || !mLastGivenInsets.equals(insets)) {
1942                 mLastGivenInsets.set(insets);
1943
1944                 // Translate insets to screen coordinates if needed.
1945                 final Rect contentInsets;
1946                 final Rect visibleInsets;
1947                 final Region touchableRegion;
1948                 if (mTranslator != null) {
1949                     contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1950                     visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1951                     touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1952                 } else {
1953                     contentInsets = insets.contentInsets;
1954                     visibleInsets = insets.visibleInsets;
1955                     touchableRegion = insets.touchableRegion;
1956                 }
1957
1958                 try {
1959                     mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
1960                             contentInsets, visibleInsets, touchableRegion);
1961                 } catch (RemoteException e) {
1962                 }
1963             }
1964         }
1965
1966         boolean skipDraw = false;
1967
1968         if (mFirst) {
1969             // handle first focus request
1970             if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1971                     + mView.hasFocus());
1972             if (mView != null) {
1973                 if (!mView.hasFocus()) {
1974                     mView.requestFocus(View.FOCUS_FORWARD);
1975                     if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1976                             + mView.findFocus());
1977                 } else {
1978                     if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1979                             + mView.findFocus());
1980                 }
1981             }
1982             if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) {
1983                 // The first time we relayout the window, if the system is
1984                 // doing window animations, we want to hold of on any future
1985                 // draws until the animation is done.
1986                 mWindowsAnimating = true;
1987             }
1988         } else if (mWindowsAnimating) {
1989             skipDraw = true;
1990         }
1991
1992         mFirst = false;
1993         mWillDrawSoon = false;
1994         mNewSurfaceNeeded = false;
1995         mViewVisibility = viewVisibility;
1996
1997         if (mAttachInfo.mHasWindowFocus && !isInLocalFocusMode()) {
1998             final boolean imTarget = WindowManager.LayoutParams
1999                     .mayUseInputMethod(mWindowAttributes.flags);
2000             if (imTarget != mLastWasImTarget) {
2001                 mLastWasImTarget = imTarget;
2002                 InputMethodManager imm = InputMethodManager.peekInstance();
2003                 if (imm != null && imTarget) {
2004                     imm.startGettingWindowFocus(mView);
2005                     imm.onWindowFocus(mView, mView.findFocus(),
2006                             mWindowAttributes.softInputMode,
2007                             !mHasHadWindowFocus, mWindowAttributes.flags);
2008                 }
2009             }
2010         }
2011
2012         // Remember if we must report the next draw.
2013         if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
2014             mReportNextDraw = true;
2015         }
2016
2017         boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() ||
2018                 viewVisibility != View.VISIBLE;
2019
2020         if (!cancelDraw && !newSurface) {
2021             if (!skipDraw || mReportNextDraw) {
2022                 if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2023                     for (int i = 0; i < mPendingTransitions.size(); ++i) {
2024                         mPendingTransitions.get(i).startChangingAnimations();
2025                     }
2026                     mPendingTransitions.clear();
2027                 }
2028
2029                 performDraw();
2030             }
2031         } else {
2032             if (viewVisibility == View.VISIBLE) {
2033                 // Try again
2034                 scheduleTraversals();
2035             } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2036                 for (int i = 0; i < mPendingTransitions.size(); ++i) {
2037                     mPendingTransitions.get(i).endChangingAnimations();
2038                 }
2039                 mPendingTransitions.clear();
2040             }
2041         }
2042
2043         mIsInTraversal = false;
2044     }
2045
2046     private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
2047         Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
2048         try {
2049             if (!mWindowSession.outOfMemory(mWindow) &&
2050                     Process.myUid() != Process.SYSTEM_UID) {
2051                 Slog.w(TAG, "No processes killed for memory; killing self");
2052                 Process.killProcess(Process.myPid());
2053             }
2054         } catch (RemoteException ex) {
2055         }
2056         mLayoutRequested = true;    // ask wm for a new surface next time.
2057     }
2058
2059     private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
2060         Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2061         try {
2062             mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2063         } finally {
2064             Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2065         }
2066     }
2067
2068     /**
2069      * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
2070      * is currently undergoing a layout pass.
2071      *
2072      * @return whether the view hierarchy is currently undergoing a layout pass
2073      */
2074     boolean isInLayout() {
2075         return mInLayout;
2076     }
2077
2078     /**
2079      * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
2080      * undergoing a layout pass. requestLayout() should not generally be called during layout,
2081      * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
2082      * all children in that container hierarchy are measured and laid out at the end of the layout
2083      * pass for that container). If requestLayout() is called anyway, we handle it correctly
2084      * by registering all requesters during a frame as it proceeds. At the end of the frame,
2085      * we check all of those views to see if any still have pending layout requests, which
2086      * indicates that they were not correctly handled by their container hierarchy. If that is
2087      * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
2088      * to blank containers, and force a second request/measure/layout pass in this frame. If
2089      * more requestLayout() calls are received during that second layout pass, we post those
2090      * requests to the next frame to avoid possible infinite loops.
2091      *
2092      * <p>The return value from this method indicates whether the request should proceed
2093      * (if it is a request during the first layout pass) or should be skipped and posted to the
2094      * next frame (if it is a request during the second layout pass).</p>
2095      *
2096      * @param view the view that requested the layout.
2097      *
2098      * @return true if request should proceed, false otherwise.
2099      */
2100     boolean requestLayoutDuringLayout(final View view) {
2101         if (view.mParent == null || view.mAttachInfo == null) {
2102             // Would not normally trigger another layout, so just let it pass through as usual
2103             return true;
2104         }
2105         if (!mLayoutRequesters.contains(view)) {
2106             mLayoutRequesters.add(view);
2107         }
2108         if (!mHandlingLayoutInLayoutRequest) {
2109             // Let the request proceed normally; it will be processed in a second layout pass
2110             // if necessary
2111             return true;
2112         } else {
2113             // Don't let the request proceed during the second layout pass.
2114             // It will post to the next frame instead.
2115             return false;
2116         }
2117     }
2118
2119     private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
2120             int desiredWindowHeight) {
2121         mLayoutRequested = false;
2122         mScrollMayChange = true;
2123         mInLayout = true;
2124
2125         final View host = mView;
2126         if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
2127             Log.v(TAG, "Laying out " + host + " to (" +
2128                     host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
2129         }
2130
2131         Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
2132         try {
2133             host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2134
2135             mInLayout = false;
2136             int numViewsRequestingLayout = mLayoutRequesters.size();
2137             if (numViewsRequestingLayout > 0) {
2138                 // requestLayout() was called during layout.
2139                 // If no layout-request flags are set on the requesting views, there is no problem.
2140                 // If some requests are still pending, then we need to clear those flags and do
2141                 // a full request/measure/layout pass to handle this situation.
2142                 ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
2143                         false);
2144                 if (validLayoutRequesters != null) {
2145                     // Set this flag to indicate that any further requests are happening during
2146                     // the second pass, which may result in posting those requests to the next
2147                     // frame instead
2148                     mHandlingLayoutInLayoutRequest = true;
2149
2150                     // Process fresh layout requests, then measure and layout
2151                     int numValidRequests = validLayoutRequesters.size();
2152                     for (int i = 0; i < numValidRequests; ++i) {
2153                         final View view = validLayoutRequesters.get(i);
2154                         Log.w("View", "requestLayout() improperly called by " + view +
2155                                 " during layout: running second layout pass");
2156                         view.requestLayout();
2157                     }
2158                     measureHierarchy(host, lp, mView.getContext().getResources(),
2159                             desiredWindowWidth, desiredWindowHeight);
2160                     mInLayout = true;
2161                     host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2162
2163                     mHandlingLayoutInLayoutRequest = false;
2164
2165                     // Check the valid requests again, this time without checking/clearing the
2166                     // layout flags, since requests happening during the second pass get noop'd
2167                     validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
2168                     if (validLayoutRequesters != null) {
2169                         final ArrayList<View> finalRequesters = validLayoutRequesters;
2170                         // Post second-pass requests to the next frame
2171                         getRunQueue().post(new Runnable() {
2172                             @Override
2173                             public void run() {
2174                                 int numValidRequests = finalRequesters.size();
2175                                 for (int i = 0; i < numValidRequests; ++i) {
2176                                     final View view = finalRequesters.get(i);
2177                                     Log.w("View", "requestLayout() improperly called by " + view +
2178                                             " during second layout pass: posting in next frame");
2179                                     view.requestLayout();
2180                                 }
2181                             }
2182                         });
2183                     }
2184                 }
2185
2186             }
2187         } finally {
2188             Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2189         }
2190         mInLayout = false;
2191     }
2192
2193     /**
2194      * This method is called during layout when there have been calls to requestLayout() during
2195      * layout. It walks through the list of views that requested layout to determine which ones
2196      * still need it, based on visibility in the hierarchy and whether they have already been
2197      * handled (as is usually the case with ListView children).
2198      *
2199      * @param layoutRequesters The list of views that requested layout during layout
2200      * @param secondLayoutRequests Whether the requests were issued during the second layout pass.
2201      * If so, the FORCE_LAYOUT flag was not set on requesters.
2202      * @return A list of the actual views that still need to be laid out.
2203      */
2204     private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters,
2205             boolean secondLayoutRequests) {
2206
2207         int numViewsRequestingLayout = layoutRequesters.size();
2208         ArrayList<View> validLayoutRequesters = null;
2209         for (int i = 0; i < numViewsRequestingLayout; ++i) {
2210             View view = layoutRequesters.get(i);
2211             if (view != null && view.mAttachInfo != null && view.mParent != null &&
2212                     (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) ==
2213                             View.PFLAG_FORCE_LAYOUT)) {
2214                 boolean gone = false;
2215                 View parent = view;
2216                 // Only trigger new requests for views in a non-GONE hierarchy
2217                 while (parent != null) {
2218                     if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) {
2219                         gone = true;
2220                         break;
2221                     }
2222                     if (parent.mParent instanceof View) {
2223                         parent = (View) parent.mParent;
2224                     } else {
2225                         parent = null;
2226                     }
2227                 }
2228                 if (!gone) {
2229                     if (validLayoutRequesters == null) {
2230                         validLayoutRequesters = new ArrayList<View>();
2231                     }
2232                     validLayoutRequesters.add(view);
2233                 }
2234             }
2235         }
2236         if (!secondLayoutRequests) {
2237             // If we're checking the layout flags, then we need to clean them up also
2238             for (int i = 0; i < numViewsRequestingLayout; ++i) {
2239                 View view = layoutRequesters.get(i);
2240                 while (view != null &&
2241                         (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
2242                     view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
2243                     if (view.mParent instanceof View) {
2244                         view = (View) view.mParent;
2245                     } else {
2246                         view = null;
2247                     }
2248                 }
2249             }
2250         }
2251         layoutRequesters.clear();
2252         return validLayoutRequesters;
2253     }
2254
2255     @Override
2256     public void requestTransparentRegion(View child) {
2257         // the test below should not fail unless someone is messing with us
2258         checkThread();
2259         if (mView == child) {
2260             mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
2261             // Need to make sure we re-evaluate the window attributes next
2262             // time around, to ensure the window has the correct format.
2263             mWindowAttributesChanged = true;
2264             mWindowAttributesChangesFlag = 0;
2265             requestLayout();
2266         }
2267     }
2268
2269     /**
2270      * Figures out the measure spec for the root view in a window based on it's
2271      * layout params.
2272      *
2273      * @param windowSize
2274      *            The available width or height of the window
2275      *
2276      * @param rootDimension
2277      *            The layout params for one dimension (width or height) of the
2278      *            window.
2279      *
2280      * @return The measure spec to use to measure the root view.
2281      */
2282     private static int getRootMeasureSpec(int windowSize, int rootDimension) {
2283         int measureSpec;
2284         switch (rootDimension) {
2285
2286         case ViewGroup.LayoutParams.MATCH_PARENT:
2287             // Window can't resize. Force root view to be windowSize.
2288             measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2289             break;
2290         case ViewGroup.LayoutParams.WRAP_CONTENT:
2291             // Window can resize. Set max size for root view.
2292             measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2293             break;
2294         default:
2295             // Window wants to be an exact size. Force root view to be that size.
2296             measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2297             break;
2298         }
2299         return measureSpec;
2300     }
2301
2302     int mHardwareXOffset;
2303     int mHardwareYOffset;
2304     int mResizeAlpha;
2305     final Paint mResizePaint = new Paint();
2306
2307     @Override
2308     public void onHardwarePreDraw(DisplayListCanvas canvas) {
2309         canvas.translate(-mHardwareXOffset, -mHardwareYOffset);
2310     }
2311
2312     @Override
2313     public void onHardwarePostDraw(DisplayListCanvas canvas) {
2314         if (mResizeBuffer != null) {
2315             mResizePaint.setAlpha(mResizeAlpha);
2316             canvas.drawHardwareLayer(mResizeBuffer, mHardwareXOffset, mHardwareYOffset,
2317                     mResizePaint);
2318         }
2319         drawAccessibilityFocusedDrawableIfNeeded(canvas);
2320     }
2321
2322     /**
2323      * @hide
2324      */
2325     void outputDisplayList(View view) {
2326         RenderNode renderNode = view.updateDisplayListIfDirty();
2327         renderNode.output();
2328     }
2329
2330     /**
2331      * @see #PROPERTY_PROFILE_RENDERING
2332      */
2333     private void profileRendering(boolean enabled) {
2334         if (mProfileRendering) {
2335             mRenderProfilingEnabled = enabled;
2336
2337             if (mRenderProfiler != null) {
2338                 mChoreographer.removeFrameCallback(mRenderProfiler);
2339             }
2340             if (mRenderProfilingEnabled) {
2341                 if (mRenderProfiler == null) {
2342                     mRenderProfiler = new Choreographer.FrameCallback() {
2343                         @Override
2344                         public void doFrame(long frameTimeNanos) {
2345                             mDirty.set(0, 0, mWidth, mHeight);
2346                             scheduleTraversals();
2347                             if (mRenderProfilingEnabled) {
2348                                 mChoreographer.postFrameCallback(mRenderProfiler);
2349                             }
2350                         }
2351                     };
2352                 }
2353                 mChoreographer.postFrameCallback(mRenderProfiler);
2354             } else {
2355                 mRenderProfiler = null;
2356             }
2357         }
2358     }
2359
2360     /**
2361      * Called from draw() when DEBUG_FPS is enabled
2362      */
2363     private void trackFPS() {
2364         // Tracks frames per second drawn. First value in a series of draws may be bogus
2365         // because it down not account for the intervening idle time
2366         long nowTime = System.currentTimeMillis();
2367         if (mFpsStartTime < 0) {
2368             mFpsStartTime = mFpsPrevTime = nowTime;
2369             mFpsNumFrames = 0;
2370         } else {
2371             ++mFpsNumFrames;
2372             String thisHash = Integer.toHexString(System.identityHashCode(this));
2373             long frameTime = nowTime - mFpsPrevTime;
2374             long totalTime = nowTime - mFpsStartTime;
2375             Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime);
2376             mFpsPrevTime = nowTime;
2377             if (totalTime > 1000) {
2378                 float fps = (float) mFpsNumFrames * 1000 / totalTime;
2379                 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps);
2380                 mFpsStartTime = nowTime;
2381                 mFpsNumFrames = 0;
2382             }
2383         }
2384     }
2385
2386     private void performDraw() {
2387         if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
2388             return;
2389         }
2390
2391         final boolean fullRedrawNeeded = mFullRedrawNeeded;
2392         mFullRedrawNeeded = false;
2393
2394         mIsDrawing = true;
2395         Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2396         try {
2397             draw(fullRedrawNeeded);
2398         } finally {
2399             mIsDrawing = false;
2400             Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2401         }
2402
2403         // For whatever reason we didn't create a HardwareRenderer, end any
2404         // hardware animations that are now dangling
2405         if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
2406             final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
2407             for (int i = 0; i < count; i++) {
2408                 mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
2409             }
2410             mAttachInfo.mPendingAnimatingRenderNodes.clear();
2411         }
2412
2413         if (mReportNextDraw) {
2414             mReportNextDraw = false;
2415             if (mAttachInfo.mHardwareRenderer != null) {
2416                 mAttachInfo.mHardwareRenderer.fence();
2417             }
2418
2419             if (LOCAL_LOGV) {
2420                 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2421             }
2422             if (mSurfaceHolder != null && mSurface.isValid()) {
2423                 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2424                 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2425                 if (callbacks != null) {
2426                     for (SurfaceHolder.Callback c : callbacks) {
2427                         if (c instanceof SurfaceHolder.Callback2) {
2428                             ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
2429                                     mSurfaceHolder);
2430                         }
2431                     }
2432                 }
2433             }
2434             try {
2435                 mWindowSession.finishDrawing(mWindow);
2436             } catch (RemoteException e) {
2437             }
2438         }
2439     }
2440
2441     private void draw(boolean fullRedrawNeeded) {
2442         Surface surface = mSurface;
2443         if (!surface.isValid()) {
2444             return;
2445         }
2446
2447         if (DEBUG_FPS) {
2448             trackFPS();
2449         }
2450
2451         if (!sFirstDrawComplete) {
2452             synchronized (sFirstDrawHandlers) {
2453                 sFirstDrawComplete = true;
2454                 final int count = sFirstDrawHandlers.size();
2455                 for (int i = 0; i< count; i++) {
2456                     mHandler.post(sFirstDrawHandlers.get(i));
2457                 }
2458             }
2459         }
2460
2461         scrollToRectOrFocus(null, false);
2462
2463         if (mAttachInfo.mViewScrollChanged) {
2464             mAttachInfo.mViewScrollChanged = false;
2465             mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
2466         }
2467
2468         boolean animating = mScroller != null && mScroller.computeScrollOffset();
2469         final int curScrollY;
2470         if (animating) {
2471             curScrollY = mScroller.getCurrY();
2472         } else {
2473             curScrollY = mScrollY;
2474         }
2475         if (mCurScrollY != curScrollY) {
2476             mCurScrollY = curScrollY;
2477             fullRedrawNeeded = true;
2478             if (mView instanceof RootViewSurfaceTaker) {
2479                 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
2480             }
2481         }
2482
2483         final float appScale = mAttachInfo.mApplicationScale;
2484         final boolean scalingRequired = mAttachInfo.mScalingRequired;
2485
2486         int resizeAlpha = 0;
2487         if (mResizeBuffer != null) {
2488             long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
2489             if (deltaTime < mResizeBufferDuration) {
2490                 float amt = deltaTime/(float) mResizeBufferDuration;
2491                 amt = mResizeInterpolator.getInterpolation(amt);
2492                 animating = true;
2493                 resizeAlpha = 255 - (int)(amt*255);
2494             } else {
2495                 disposeResizeBuffer();
2496             }
2497         }
2498
2499         final Rect dirty = mDirty;
2500         if (mSurfaceHolder != null) {
2501             // The app owns the surface, we won't draw.
2502             dirty.setEmpty();
2503             if (animating) {
2504                 if (mScroller != null) {
2505                     mScroller.abortAnimation();
2506                 }
2507                 disposeResizeBuffer();
2508             }
2509             return;
2510         }
2511
2512         if (fullRedrawNeeded) {
2513             mAttachInfo.mIgnoreDirtyState = true;
2514             dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2515         }
2516
2517         if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2518             Log.v(TAG, "Draw " + mView + "/"
2519                     + mWindowAttributes.getTitle()
2520                     + ": dirty={" + dirty.left + "," + dirty.top
2521                     + "," + dirty.right + "," + dirty.bottom + "} surface="
2522                     + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2523                     appScale + ", width=" + mWidth + ", height=" + mHeight);
2524         }
2525
2526         mAttachInfo.mTreeObserver.dispatchOnDraw();
2527
2528         int xOffset = 0;
2529         int yOffset = curScrollY;
2530         final WindowManager.LayoutParams params = mWindowAttributes;
2531         final Rect surfaceInsets = params != null ? params.surfaceInsets : null;
2532         if (surfaceInsets != null) {
2533             xOffset -= surfaceInsets.left;
2534             yOffset -= surfaceInsets.top;
2535
2536             // Offset dirty rect for surface insets.
2537             dirty.offset(surfaceInsets.left, surfaceInsets.right);
2538         }
2539
2540         boolean accessibilityFocusDirty = false;
2541         final Drawable drawable = mAttachInfo.mAccessibilityFocusDrawable;
2542         if (drawable != null) {
2543             final Rect bounds = mAttachInfo.mTmpInvalRect;
2544             final boolean hasFocus = getAccessibilityFocusedRect(bounds);
2545             if (!hasFocus) {
2546                 bounds.setEmpty();
2547             }
2548             if (!bounds.equals(drawable.getBounds())) {
2549                 accessibilityFocusDirty = true;
2550             }
2551         }
2552
2553         mAttachInfo.mDrawingTime =
2554                 mChoreographer.getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
2555
2556         if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
2557             if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
2558                 // If accessibility focus moved, always invalidate the root.
2559                 boolean invalidateRoot = accessibilityFocusDirty;
2560
2561                 // Draw with hardware renderer.
2562                 mIsAnimating = false;
2563
2564                 if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
2565                     mHardwareYOffset = yOffset;
2566                     mHardwareXOffset = xOffset;
2567                     invalidateRoot = true;
2568                 }
2569                 mResizeAlpha = resizeAlpha;
2570
2571                 if (invalidateRoot) {
2572                     mAttachInfo.mHardwareRenderer.invalidateRoot();
2573                 }
2574
2575                 dirty.setEmpty();
2576
2577                 mBlockResizeBuffer = false;
2578                 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
2579             } else {
2580                 // If we get here with a disabled & requested hardware renderer, something went
2581                 // wrong (an invalidate posted right before we destroyed the hardware surface
2582                 // for instance) so we should just bail out. Locking the surface with software
2583                 // rendering at this point would lock it forever and prevent hardware renderer
2584                 // from doing its job when it comes back.
2585                 // Before we request a new frame we must however attempt to reinitiliaze the
2586                 // hardware renderer if it's in requested state. This would happen after an
2587                 // eglTerminate() for instance.
2588                 if (mAttachInfo.mHardwareRenderer != null &&
2589                         !mAttachInfo.mHardwareRenderer.isEnabled() &&
2590                         mAttachInfo.mHardwareRenderer.isRequested()) {
2591
2592                     try {
2593                         mAttachInfo.mHardwareRenderer.initializeIfNeeded(
2594                                 mWidth, mHeight, mSurface, surfaceInsets);
2595                     } catch (OutOfResourcesException e) {
2596                         handleOutOfResourcesException(e);
2597                         return;
2598                     }
2599
2600                     mFullRedrawNeeded = true;
2601                     scheduleTraversals();
2602                     return;
2603                 }
2604
2605                 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
2606                     return;
2607                 }
2608             }
2609         }
2610
2611         if (animating) {
2612             mFullRedrawNeeded = true;
2613             scheduleTraversals();
2614         }
2615     }
2616
2617     /**
2618      * @return true if drawing was successful, false if an error occurred
2619      */
2620     private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
2621             boolean scalingRequired, Rect dirty) {
2622
2623         // Draw with software renderer.
2624         final Canvas canvas;
2625         try {
2626             final int left = dirty.left;
2627             final int top = dirty.top;
2628             final int right = dirty.right;
2629             final int bottom = dirty.bottom;
2630
2631             canvas = mSurface.lockCanvas(dirty);
2632
2633             // The dirty rectangle can be modified by Surface.lockCanvas()
2634             //noinspection ConstantConditions
2635             if (left != dirty.left || top != dirty.top || right != dirty.right
2636                     || bottom != dirty.bottom) {
2637                 attachInfo.mIgnoreDirtyState = true;
2638             }
2639
2640             // TODO: Do this in native
2641             canvas.setDensity(mDensity);
2642         } catch (Surface.OutOfResourcesException e) {
2643             handleOutOfResourcesException(e);
2644             return false;
2645         } catch (IllegalArgumentException e) {
2646             Log.e(TAG, "Could not lock surface", e);
2647             // Don't assume this is due to out of memory, it could be
2648             // something else, and if it is something else then we could
2649             // kill stuff (or ourself) for no reason.
2650             mLayoutRequested = true;    // ask wm for a new surface next time.
2651             return false;
2652         }
2653
2654         try {
2655             if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2656                 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
2657                         + canvas.getWidth() + ", h=" + canvas.getHeight());
2658                 //canvas.drawARGB(255, 255, 0, 0);
2659             }
2660
2661             // If this bitmap's format includes an alpha channel, we
2662             // need to clear it before drawing so that the child will
2663             // properly re-composite its drawing on a transparent
2664             // background. This automatically respects the clip/dirty region
2665             // or
2666             // If we are applying an offset, we need to clear the area
2667             // where the offset doesn't appear to avoid having garbage
2668             // left in the blank areas.
2669             if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
2670                 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2671             }
2672
2673             dirty.setEmpty();
2674             mIsAnimating = false;
2675             mView.mPrivateFlags |= View.PFLAG_DRAWN;
2676
2677             if (DEBUG_DRAW) {
2678                 Context cxt = mView.getContext();
2679                 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
2680                         ", metrics=" + cxt.getResources().getDisplayMetrics() +
2681                         ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2682             }
2683             try {
2684                 canvas.translate(-xoff, -yoff);
2685                 if (mTranslator != null) {
2686                     mTranslator.translateCanvas(canvas);
2687                 }
2688                 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2689                 attachInfo.mSetIgnoreDirtyState = false;
2690
2691                 mView.draw(canvas);
2692
2693                 drawAccessibilityFocusedDrawableIfNeeded(canvas);
2694             } finally {
2695                 if (!attachInfo.mSetIgnoreDirtyState) {
2696                     // Only clear the flag if it was not set during the mView.draw() call
2697                     attachInfo.mIgnoreDirtyState = false;
2698                 }
2699             }
2700         } finally {
2701             try {
2702                 surface.unlockCanvasAndPost(canvas);
2703             } catch (IllegalArgumentException e) {
2704                 Log.e(TAG, "Could not unlock surface", e);
2705                 mLayoutRequested = true;    // ask wm for a new surface next time.
2706                 //noinspection ReturnInsideFinallyBlock
2707                 return false;
2708             }
2709
2710             if (LOCAL_LOGV) {
2711                 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
2712             }
2713         }
2714         return true;
2715     }
2716
2717     /**
2718      * We want to draw a highlight around the current accessibility focused.
2719      * Since adding a style for all possible view is not a viable option we
2720      * have this specialized drawing method.
2721      *
2722      * Note: We are doing this here to be able to draw the highlight for
2723      *       virtual views in addition to real ones.
2724      *
2725      * @param canvas The canvas on which to draw.
2726      */
2727     private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2728         final Rect bounds = mAttachInfo.mTmpInvalRect;
2729         if (getAccessibilityFocusedRect(bounds)) {
2730             final Drawable drawable = getAccessibilityFocusedDrawable();
2731             if (drawable != null) {
2732                 drawable.setBounds(bounds);
2733                 drawable.draw(canvas);
2734             }
2735         } else if (mAttachInfo.mAccessibilityFocusDrawable != null) {
2736             mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0);
2737         }
2738     }
2739
2740     private boolean getAccessibilityFocusedRect(Rect bounds) {
2741         final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2742         if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2743             return false;
2744         }
2745
2746         final View host = mAccessibilityFocusedHost;
2747         if (host == null || host.mAttachInfo == null) {
2748             return false;
2749         }
2750
2751         final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider();
2752         if (provider == null) {
2753             host.getBoundsOnScreen(bounds, true);
2754         } else if (mAccessibilityFocusedVirtualView != null) {
2755             mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2756         } else {
2757             return false;
2758         }
2759
2760         final AttachInfo attachInfo = mAttachInfo;
2761         bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop);
2762         bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth, attachInfo.mViewRootImpl.mHeight);
2763         return !bounds.isEmpty();
2764     }
2765
2766     private Drawable getAccessibilityFocusedDrawable() {
2767         // Lazily load the accessibility focus drawable.
2768         if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2769             final TypedValue value = new TypedValue();
2770             final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2771                     R.attr.accessibilityFocusedDrawable, value, true);
2772             if (resolved) {
2773                 mAttachInfo.mAccessibilityFocusDrawable =
2774                         mView.mContext.getDrawable(value.resourceId);
2775             }
2776         }
2777         return mAttachInfo.mAccessibilityFocusDrawable;
2778     }
2779
2780     /**
2781      * @hide
2782      */
2783     public void setDrawDuringWindowsAnimating(boolean value) {
2784         mDrawDuringWindowsAnimating = value;
2785         if (value) {
2786             handleDispatchDoneAnimating();
2787         }
2788     }
2789
2790     boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2791         final Rect ci = mAttachInfo.mContentInsets;
2792         final Rect vi = mAttachInfo.mVisibleInsets;
2793         int scrollY = 0;
2794         boolean handled = false;
2795
2796         if (vi.left > ci.left || vi.top > ci.top
2797                 || vi.right > ci.right || vi.bottom > ci.bottom) {
2798             // We'll assume that we aren't going to change the scroll
2799             // offset, since we want to avoid that unless it is actually
2800             // going to make the focus visible...  otherwise we scroll
2801             // all over the place.
2802             scrollY = mScrollY;
2803             // We can be called for two different situations: during a draw,
2804             // to update the scroll position if the focus has changed (in which
2805             // case 'rectangle' is null), or in response to a
2806             // requestChildRectangleOnScreen() call (in which case 'rectangle'
2807             // is non-null and we just want to scroll to whatever that
2808             // rectangle is).
2809             final View focus = mView.findFocus();
2810             if (focus == null) {
2811                 return false;
2812             }
2813             View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
2814             if (focus != lastScrolledFocus) {
2815                 // If the focus has changed, then ignore any requests to scroll
2816                 // to a rectangle; first we want to make sure the entire focus
2817                 // view is visible.
2818                 rectangle = null;
2819             }
2820             if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2821                     + " rectangle=" + rectangle + " ci=" + ci
2822                     + " vi=" + vi);
2823             if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) {
2824                 // Optimization: if the focus hasn't changed since last
2825                 // time, and no layout has happened, then just leave things
2826                 // as they are.
2827                 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2828                         + mScrollY + " vi=" + vi.toShortString());
2829             } else {
2830                 // We need to determine if the currently focused view is
2831                 // within the visible part of the window and, if not, apply
2832                 // a pan so it can be seen.
2833                 mLastScrolledFocus = new WeakReference<View>(focus);
2834                 mScrollMayChange = false;
2835                 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2836                 // Try to find the rectangle from the focus view.
2837                 if (focus.getGlobalVisibleRect(mVisRect, null)) {
2838                     if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2839                             + mView.getWidth() + " h=" + mView.getHeight()
2840                             + " ci=" + ci.toShortString()
2841                             + " vi=" + vi.toShortString());
2842                     if (rectangle == null) {
2843                         focus.getFocusedRect(mTempRect);
2844                         if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2845                                 + ": focusRect=" + mTempRect.toShortString());
2846                         if (mView instanceof ViewGroup) {
2847                             ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2848                                     focus, mTempRect);
2849                         }
2850                         if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2851                                 "Focus in window: focusRect="
2852                                 + mTempRect.toShortString()
2853                                 + " visRect=" + mVisRect.toShortString());
2854                     } else {
2855                         mTempRect.set(rectangle);
2856                         if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2857                                 "Request scroll to rect: "
2858                                 + mTempRect.toShortString()
2859                                 + " visRect=" + mVisRect.toShortString());
2860                     }
2861                     if (mTempRect.intersect(mVisRect)) {
2862                         if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2863                                 "Focus window visible rect: "
2864                                 + mTempRect.toShortString());
2865                         if (mTempRect.height() >
2866                                 (mView.getHeight()-vi.top-vi.bottom)) {
2867                             // If the focus simply is not going to fit, then
2868                             // best is probably just to leave things as-is.
2869                             if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2870                                     "Too tall; leaving scrollY=" + scrollY);
2871                         } else if ((mTempRect.top-scrollY) < vi.top) {
2872                             scrollY -= vi.top - (mTempRect.top-scrollY);
2873                             if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2874                                     "Top covered; scrollY=" + scrollY);
2875                         } else if ((mTempRect.bottom-scrollY)
2876                                 > (mView.getHeight()-vi.bottom)) {
2877                             scrollY += (mTempRect.bottom-scrollY)
2878                                     - (mView.getHeight()-vi.bottom);
2879                             if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2880                                     "Bottom covered; scrollY=" + scrollY);
2881                         }
2882                         handled = true;
2883                     }
2884                 }
2885             }
2886         }
2887
2888         if (scrollY != mScrollY) {
2889             if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2890                     + mScrollY + " , new=" + scrollY);
2891             if (!immediate && mResizeBuffer == null) {
2892                 if (mScroller == null) {
2893                     mScroller = new Scroller(mView.getContext());
2894                 }
2895                 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2896             } else if (mScroller != null) {
2897                 mScroller.abortAnimation();
2898             }
2899             mScrollY = scrollY;
2900         }
2901
2902         return handled;
2903     }
2904
2905     /**
2906      * @hide
2907      */
2908     public View getAccessibilityFocusedHost() {
2909         return mAccessibilityFocusedHost;
2910     }
2911
2912     /**
2913      * @hide
2914      */
2915     public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
2916         return mAccessibilityFocusedVirtualView;
2917     }
2918
2919     void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
2920         // If we have a virtual view with accessibility focus we need
2921         // to clear the focus and invalidate the virtual view bounds.
2922         if (mAccessibilityFocusedVirtualView != null) {
2923
2924             AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
2925             View focusHost = mAccessibilityFocusedHost;
2926
2927             // Wipe the state of the current accessibility focus since
2928             // the call into the provider to clear accessibility focus
2929             // will fire an accessibility event which will end up calling
2930             // this method and we want to have clean state when this
2931             // invocation happens.
2932             mAccessibilityFocusedHost = null;
2933             mAccessibilityFocusedVirtualView = null;
2934
2935             // Clear accessibility focus on the host after clearing state since
2936             // this method may be reentrant.
2937             focusHost.clearAccessibilityFocusNoCallbacks();
2938
2939             AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
2940             if (provider != null) {
2941                 // Invalidate the area of the cleared accessibility focus.
2942                 focusNode.getBoundsInParent(mTempRect);
2943                 focusHost.invalidate(mTempRect);
2944                 // Clear accessibility focus in the virtual node.
2945                 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
2946                         focusNode.getSourceNodeId());
2947                 provider.performAction(virtualNodeId,
2948                         AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
2949             }
2950             focusNode.recycle();
2951         }
2952         if (mAccessibilityFocusedHost != null) {
2953             // Clear accessibility focus in the view.
2954             mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2955         }
2956
2957         // Set the new focus host and node.
2958         mAccessibilityFocusedHost = view;
2959         mAccessibilityFocusedVirtualView = node;
2960
2961         if (mAttachInfo.mHardwareRenderer != null) {
2962             mAttachInfo.mHardwareRenderer.invalidateRoot();
2963         }
2964     }
2965
2966     @Override
2967     public void requestChildFocus(View child, View focused) {
2968         if (DEBUG_INPUT_RESIZE) {
2969             Log.v(TAG, "Request child focus: focus now " + focused);
2970         }
2971         checkThread();
2972         scheduleTraversals();
2973     }
2974
2975     @Override
2976     public void clearChildFocus(View child) {
2977         if (DEBUG_INPUT_RESIZE) {
2978             Log.v(TAG, "Clearing child focus");
2979         }
2980         checkThread();
2981         scheduleTraversals();
2982     }
2983
2984     @Override
2985     public ViewParent getParentForAccessibility() {
2986         return null;
2987     }
2988
2989     @Override
2990     public void focusableViewAvailable(View v) {
2991         checkThread();
2992         if (mView != null) {
2993             if (!mView.hasFocus()) {
2994                 v.requestFocus();
2995             } else {
2996                 // the one case where will transfer focus away from the current one
2997                 // is if the current view is a view group that prefers to give focus
2998                 // to its children first AND the view is a descendant of it.
2999                 View focused = mView.findFocus();
3000                 if (focused instanceof ViewGroup) {
3001                     ViewGroup group = (ViewGroup) focused;
3002                     if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3003                             && isViewDescendantOf(v, focused)) {
3004                         v.requestFocus();
3005                     }
3006                 }
3007             }
3008         }
3009     }
3010
3011     @Override
3012     public void recomputeViewAttributes(View child) {
3013         checkThread();
3014         if (mView == child) {
3015             mAttachInfo.mRecomputeGlobalAttributes = true;
3016             if (!mWillDrawSoon) {
3017                 scheduleTraversals();
3018             }
3019         }
3020     }
3021
3022     void dispatchDetachedFromWindow() {
3023         if (mView != null && mView.mAttachInfo != null) {
3024             mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
3025             mView.dispatchDetachedFromWindow();
3026         }
3027
3028         mAccessibilityInteractionConnectionManager.ensureNoConnection();
3029         mAccessibilityManager.removeAccessibilityStateChangeListener(
3030                 mAccessibilityInteractionConnectionManager);
3031         mAccessibilityManager.removeHighTextContrastStateChangeListener(
3032                 mHighContrastTextManager);
3033         removeSendWindowContentChangedCallback();
3034
3035         destroyHardwareRenderer();
3036
3037         setAccessibilityFocus(null, null);
3038
3039         mView.assignParent(null);
3040         mView = null;
3041         mAttachInfo.mRootView = null;
3042
3043         mSurface.release();
3044
3045         if (mInputQueueCallback != null && mInputQueue != null) {
3046             mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
3047             mInputQueue.dispose();
3048             mInputQueueCallback = null;
3049             mInputQueue = null;
3050         }
3051         if (mInputEventReceiver != null) {
3052             mInputEventReceiver.dispose();
3053             mInputEventReceiver = null;
3054         }
3055         try {
3056             mWindowSession.remove(mWindow);
3057         } catch (RemoteException e) {
3058         }
3059
3060         // Dispose the input channel after removing the window so the Window Manager
3061         // doesn't interpret the input channel being closed as an abnormal termination.
3062         if (mInputChannel != null) {
3063             mInputChannel.dispose();
3064             mInputChannel = null;
3065         }
3066
3067         mDisplayManager.unregisterDisplayListener(mDisplayListener);
3068
3069         unscheduleTraversals();
3070     }
3071
3072     void updateConfiguration(Configuration config, boolean force) {
3073         if (DEBUG_CONFIGURATION) Log.v(TAG,
3074                 "Applying new config to window "
3075                 + mWindowAttributes.getTitle()
3076                 + ": " + config);
3077
3078         CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo();
3079         if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
3080             config = new Configuration(config);
3081             ci.applyToConfiguration(mNoncompatDensity, config);
3082         }
3083
3084         synchronized (sConfigCallbacks) {
3085             for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
3086                 sConfigCallbacks.get(i).onConfigurationChanged(config);
3087             }
3088         }
3089         if (mView != null) {
3090             // At this point the resources have been updated to
3091             // have the most recent config, whatever that is.  Use
3092             // the one in them which may be newer.
3093             config = mView.getResources().getConfiguration();
3094             if (force || mLastConfiguration.diff(config) != 0) {
3095                 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
3096                 final int currentLayoutDirection = config.getLayoutDirection();
3097                 mLastConfiguration.setTo(config);
3098                 if (lastLayoutDirection != currentLayoutDirection &&
3099                         mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
3100                     mView.setLayoutDirection(currentLayoutDirection);
3101                 }
3102                 mView.dispatchConfigurationChanged(config);
3103             }
3104         }
3105     }
3106
3107     /**
3108      * Return true if child is an ancestor of parent, (or equal to the parent).
3109      */
3110     public static boolean isViewDescendantOf(View child, View parent) {
3111         if (child == parent) {
3112             return true;
3113         }
3114
3115         final ViewParent theParent = child.getParent();
3116         return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
3117     }
3118
3119     private final static int MSG_INVALIDATE = 1;
3120     private final static int MSG_INVALIDATE_RECT = 2;
3121     private final static int MSG_DIE = 3;
3122     private final static int MSG_RESIZED = 4;
3123     private final static int MSG_RESIZED_REPORT = 5;
3124     private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
3125     private final static int MSG_DISPATCH_INPUT_EVENT = 7;
3126     private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
3127     private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
3128     private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
3129     private final static int MSG_FINISH_INPUT_CONNECTION = 12;
3130     private final static int MSG_CHECK_FOCUS = 13;
3131     private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
3132     private final static int MSG_DISPATCH_DRAG_EVENT = 15;
3133     private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
3134     private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
3135     private final static int MSG_UPDATE_CONFIGURATION = 18;
3136     private final static int MSG_PROCESS_INPUT_EVENTS = 19;
3137     private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
3138     private final static int MSG_DISPATCH_DONE_ANIMATING = 22;
3139     private final static int MSG_INVALIDATE_WORLD = 23;
3140     private final static int MSG_WINDOW_MOVED = 24;
3141     private final static int MSG_SYNTHESIZE_INPUT_EVENT = 25;
3142     private final static int MSG_DISPATCH_WINDOW_SHOWN = 26;
3143
3144     final class ViewRootHandler extends Handler {
3145         @Override
3146         public String getMessageName(Message message) {
3147             switch (message.what) {
3148                 case MSG_INVALIDATE:
3149                     return "MSG_INVALIDATE";
3150                 case MSG_INVALIDATE_RECT:
3151                     return "MSG_INVALIDATE_RECT";
3152                 case MSG_DIE:
3153                     return "MSG_DIE";
3154                 case MSG_RESIZED:
3155                     return "MSG_RESIZED";
3156                 case MSG_RESIZED_REPORT:
3157                     return "MSG_RESIZED_REPORT";
3158                 case MSG_WINDOW_FOCUS_CHANGED:
3159                     return "MSG_WINDOW_FOCUS_CHANGED";
3160                 case MSG_DISPATCH_INPUT_EVENT:
3161                     return "MSG_DISPATCH_INPUT_EVENT";
3162                 case MSG_DISPATCH_APP_VISIBILITY:
3163                     return "MSG_DISPATCH_APP_VISIBILITY";
3164                 case MSG_DISPATCH_GET_NEW_SURFACE:
3165                     return "MSG_DISPATCH_GET_NEW_SURFACE";
3166                 case MSG_DISPATCH_KEY_FROM_IME:
3167                     return "MSG_DISPATCH_KEY_FROM_IME";
3168                 case MSG_FINISH_INPUT_CONNECTION:
3169                     return "MSG_FINISH_INPUT_CONNECTION";
3170                 case MSG_CHECK_FOCUS:
3171                     return "MSG_CHECK_FOCUS";
3172                 case MSG_CLOSE_SYSTEM_DIALOGS:
3173                     return "MSG_CLOSE_SYSTEM_DIALOGS";
3174                 case MSG_DISPATCH_DRAG_EVENT:
3175                     return "MSG_DISPATCH_DRAG_EVENT";
3176                 case MSG_DISPATCH_DRAG_LOCATION_EVENT:
3177                     return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
3178                 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
3179                     return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
3180                 case MSG_UPDATE_CONFIGURATION:
3181                     return "MSG_UPDATE_CONFIGURATION";
3182                 case MSG_PROCESS_INPUT_EVENTS:
3183                     return "MSG_PROCESS_INPUT_EVENTS";
3184                 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
3185                     return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
3186                 case MSG_DISPATCH_DONE_ANIMATING:
3187                     return "MSG_DISPATCH_DONE_ANIMATING";
3188                 case MSG_WINDOW_MOVED:
3189                     return "MSG_WINDOW_MOVED";
3190                 case MSG_SYNTHESIZE_INPUT_EVENT:
3191                     return "MSG_SYNTHESIZE_INPUT_EVENT";
3192                 case MSG_DISPATCH_WINDOW_SHOWN:
3193                     return "MSG_DISPATCH_WINDOW_SHOWN";
3194             }
3195             return super.getMessageName(message);
3196         }
3197
3198         @Override
3199         public void handleMessage(Message msg) {
3200             switch (msg.what) {
3201             case MSG_INVALIDATE:
3202                 ((View) msg.obj).invalidate();
3203                 break;
3204             case MSG_INVALIDATE_RECT:
3205                 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
3206                 info.target.invalidate(info.left, info.top, info.right, info.bottom);
3207                 info.recycle();
3208                 break;
3209             case MSG_PROCESS_INPUT_EVENTS:
3210                 mProcessInputEventsScheduled = false;
3211                 doProcessInputEvents();
3212                 break;
3213             case MSG_DISPATCH_APP_VISIBILITY:
3214                 handleAppVisibility(msg.arg1 != 0);
3215                 break;
3216             case MSG_DISPATCH_GET_NEW_SURFACE:
3217                 handleGetNewSurface();
3218                 break;
3219             case MSG_RESIZED: {
3220                 // Recycled in the fall through...
3221                 SomeArgs args = (SomeArgs) msg.obj;
3222                 if (mWinFrame.equals(args.arg1)
3223                         && mPendingOverscanInsets.equals(args.arg5)
3224                         && mPendingContentInsets.equals(args.arg2)
3225                         && mPendingStableInsets.equals(args.arg6)
3226                         && mPendingVisibleInsets.equals(args.arg3)
3227                         && args.arg4 == null) {
3228                     break;
3229                 }
3230                 } // fall through...
3231             case MSG_RESIZED_REPORT:
3232                 if (mAdded) {
3233                     SomeArgs args = (SomeArgs) msg.obj;
3234
3235                     Configuration config = (Configuration) args.arg4;
3236                     if (config != null) {
3237                         updateConfiguration(config, false);
3238                     }
3239
3240                     mWinFrame.set((Rect) args.arg1);
3241                     mPendingOverscanInsets.set((Rect) args.arg5);
3242                     mPendingContentInsets.set((Rect) args.arg2);
3243                     mPendingStableInsets.set((Rect) args.arg6);
3244                     mPendingVisibleInsets.set((Rect) args.arg3);
3245
3246                     args.recycle();
3247
3248                     if (msg.what == MSG_RESIZED_REPORT) {
3249                         mReportNextDraw = true;
3250                     }
3251
3252                     requestLayout();
3253                 }
3254                 break;
3255             case MSG_WINDOW_MOVED:
3256                 if (mAdded) {
3257                     final int w = mWinFrame.width();
3258                     final int h = mWinFrame.height();
3259                     final int l = msg.arg1;
3260                     final int t = msg.arg2;
3261                     mWinFrame.left = l;
3262                     mWinFrame.right = l + w;
3263                     mWinFrame.top = t;
3264                     mWinFrame.bottom = t + h;
3265
3266                     requestLayout();
3267                 }
3268                 break;
3269             case MSG_WINDOW_FOCUS_CHANGED: {
3270                 if (mAdded) {
3271                     boolean hasWindowFocus = msg.arg1 != 0;
3272                     mAttachInfo.mHasWindowFocus = hasWindowFocus;
3273
3274                     profileRendering(hasWindowFocus);
3275
3276                     if (hasWindowFocus) {
3277                         boolean inTouchMode = msg.arg2 != 0;
3278                         ensureTouchModeLocally(inTouchMode);
3279
3280                         if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){
3281                             mFullRedrawNeeded = true;
3282                             try {
3283                                 final WindowManager.LayoutParams lp = mWindowAttributes;
3284                                 final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null;
3285                                 mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3286                                         mWidth, mHeight, mSurface, surfaceInsets);
3287                             } catch (OutOfResourcesException e) {
3288                                 Log.e(TAG, "OutOfResourcesException locking surface", e);
3289                                 try {
3290                                     if (!mWindowSession.outOfMemory(mWindow)) {
3291                                         Slog.w(TAG, "No processes killed for memory; killing self");
3292                                         Process.killProcess(Process.myPid());
3293                                     }
3294                                 } catch (RemoteException ex) {
3295                                 }
3296                                 // Retry in a bit.
3297                                 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3298                                 return;
3299                             }
3300                         }
3301                     }
3302
3303                     mLastWasImTarget = WindowManager.LayoutParams
3304                             .mayUseInputMethod(mWindowAttributes.flags);
3305
3306                     InputMethodManager imm = InputMethodManager.peekInstance();
3307                     if (mView != null) {
3308                         if (hasWindowFocus && imm != null && mLastWasImTarget &&
3309                                 !isInLocalFocusMode()) {
3310                             imm.startGettingWindowFocus(mView);
3311                         }
3312                         mAttachInfo.mKeyDispatchState.reset();
3313                         mView.dispatchWindowFocusChanged(hasWindowFocus);
3314                         mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
3315                     }
3316
3317                     // Note: must be done after the focus change callbacks,
3318                     // so all of the view state is set up correctly.
3319                     if (hasWindowFocus) {
3320                         if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3321                             imm.onWindowFocus(mView, mView.findFocus(),
3322                                     mWindowAttributes.softInputMode,
3323                                     !mHasHadWindowFocus, mWindowAttributes.flags);
3324                         }
3325                         // Clear the forward bit.  We can just do this directly, since
3326                         // the window manager doesn't care about it.
3327                         mWindowAttributes.softInputMode &=
3328                                 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3329                         ((WindowManager.LayoutParams)mView.getLayoutParams())
3330                                 .softInputMode &=
3331                                     ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3332                         mHasHadWindowFocus = true;
3333                     }
3334
3335                     if (mView != null && mAccessibilityManager.isEnabled()) {
3336                         if (hasWindowFocus) {
3337                             mView.sendAccessibilityEvent(
3338                                     AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3339                         }
3340                     }
3341                 }
3342             } break;
3343             case MSG_DIE:
3344                 doDie();
3345                 break;
3346             case MSG_DISPATCH_INPUT_EVENT: {
3347                 SomeArgs args = (SomeArgs)msg.obj;
3348                 InputEvent event = (InputEvent)args.arg1;
3349                 InputEventReceiver receiver = (InputEventReceiver)args.arg2;
3350                 enqueueInputEvent(event, receiver, 0, true);
3351                 args.recycle();
3352             } break;
3353             case MSG_SYNTHESIZE_INPUT_EVENT: {
3354                 InputEvent event = (InputEvent)msg.obj;
3355                 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true);
3356             } break;
3357             case MSG_DISPATCH_KEY_FROM_IME: {
3358                 if (LOCAL_LOGV) Log.v(
3359                     TAG, "Dispatching key "
3360                     + msg.obj + " from IME to " + mView);
3361                 KeyEvent event = (KeyEvent)msg.obj;
3362                 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3363                     // The IME is trying to say this event is from the
3364                     // system!  Bad bad bad!
3365                     //noinspection UnusedAssignment
3366                     event = KeyEvent.changeFlags(event, event.getFlags() &
3367                             ~KeyEvent.FLAG_FROM_SYSTEM);
3368                 }
3369                 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3370             } break;
3371             case MSG_FINISH_INPUT_CONNECTION: {
3372                 InputMethodManager imm = InputMethodManager.peekInstance();
3373                 if (imm != null) {
3374                     imm.reportFinishInputConnection((InputConnection)msg.obj);
3375                 }
3376             } break;
3377             case MSG_CHECK_FOCUS: {
3378                 InputMethodManager imm = InputMethodManager.peekInstance();
3379                 if (imm != null) {
3380                     imm.checkFocus();
3381                 }
3382             } break;
3383             case MSG_CLOSE_SYSTEM_DIALOGS: {
3384                 if (mView != null) {
3385                     mView.onCloseSystemDialogs((String)msg.obj);
3386                 }
3387             } break;
3388             case MSG_DISPATCH_DRAG_EVENT:
3389             case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3390                 DragEvent event = (DragEvent)msg.obj;
3391                 event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
3392                 handleDragEvent(event);
3393             } break;
3394             case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3395                 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3396             } break;
3397             case MSG_UPDATE_CONFIGURATION: {
3398                 Configuration config = (Configuration)msg.obj;
3399                 if (config.isOtherSeqNewer(mLastConfiguration)) {
3400                     config = mLastConfiguration;
3401                 }
3402                 updateConfiguration(config, false);
3403             } break;
3404             case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3405                 setAccessibilityFocus(null, null);
3406             } break;
3407             case MSG_DISPATCH_DONE_ANIMATING: {
3408                 handleDispatchDoneAnimating();
3409             } break;
3410             case MSG_INVALIDATE_WORLD: {
3411                 if (mView != null) {
3412                     invalidateWorld(mView);
3413                 }
3414             } break;
3415             case MSG_DISPATCH_WINDOW_SHOWN: {
3416                 handleDispatchWindowShown();
3417             }
3418             }
3419         }
3420     }
3421
3422     final ViewRootHandler mHandler = new ViewRootHandler();
3423
3424     /**
3425      * Something in the current window tells us we need to change the touch mode.  For
3426      * example, we are not in touch mode, and the user touches the screen.
3427      *
3428      * If the touch mode has changed, tell the window manager, and handle it locally.
3429      *
3430      * @param inTouchMode Whether we want to be in touch mode.
3431      * @return True if the touch mode changed and focus changed was changed as a result
3432      */
3433     boolean ensureTouchMode(boolean inTouchMode) {
3434         if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3435                 + "touch mode is " + mAttachInfo.mInTouchMode);
3436         if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3437
3438         // tell the window manager
3439         try {
3440             if (!isInLocalFocusMode()) {
3441                 mWindowSession.setInTouchMode(inTouchMode);
3442             }
3443         } catch (RemoteException e) {
3444             throw new RuntimeException(e);
3445         }
3446
3447         // handle the change
3448         return ensureTouchModeLocally(inTouchMode);
3449     }
3450
3451     /**
3452      * Ensure that the touch mode for this window is set, and if it is changing,
3453      * take the appropriate action.
3454      * @param inTouchMode Whether we want to be in touch mode.
3455      * @return True if the touch mode changed and focus changed was changed as a result
3456      */
3457     private boolean ensureTouchModeLocally(boolean inTouchMode) {
3458         if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3459                 + "touch mode is " + mAttachInfo.mInTouchMode);
3460
3461         if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3462
3463         mAttachInfo.mInTouchMode = inTouchMode;
3464         mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3465
3466         return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3467     }
3468
3469     private boolean enterTouchMode() {
3470         if (mView != null && mView.hasFocus()) {
3471             // note: not relying on mFocusedView here because this could
3472             // be when the window is first being added, and mFocused isn't
3473             // set yet.
3474             final View focused = mView.findFocus();
3475             if (focused != null && !focused.isFocusableInTouchMode()) {
3476                 final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused);
3477                 if (ancestorToTakeFocus != null) {
3478                     // there is an ancestor that wants focus after its
3479                     // descendants that is focusable in touch mode.. give it
3480                     // focus
3481                     return ancestorToTakeFocus.requestFocus();
3482                 } else {
3483                     // There's nothing to focus. Clear and propagate through the
3484                     // hierarchy, but don't attempt to place new focus.
3485                     focused.clearFocusInternal(null, true, false);
3486                     return true;
3487                 }
3488             }
3489         }
3490         return false;
3491     }
3492
3493     /**
3494      * Find an ancestor of focused that wants focus after its descendants and is
3495      * focusable in touch mode.
3496      * @param focused The currently focused view.
3497      * @return An appropriate view, or null if no such view exists.
3498      */
3499     private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3500         ViewParent parent = focused.getParent();
3501         while (parent instanceof ViewGroup) {
3502             final ViewGroup vgParent = (ViewGroup) parent;
3503             if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3504                     && vgParent.isFocusableInTouchMode()) {
3505                 return vgParent;
3506             }
3507             if (vgParent.isRootNamespace()) {
3508                 return null;
3509             } else {
3510                 parent = vgParent.getParent();
3511             }
3512         }
3513         return null;
3514     }
3515
3516     private boolean leaveTouchMode() {
3517         if (mView != null) {
3518             if (mView.hasFocus()) {
3519                 View focusedView = mView.findFocus();
3520                 if (!(focusedView instanceof ViewGroup)) {
3521                     // some view has focus, let it keep it
3522                     return false;
3523                 } else if (((ViewGroup) focusedView).getDescendantFocusability() !=
3524                         ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3525                     // some view group has focus, and doesn't prefer its children
3526                     // over itself for focus, so let them keep it.
3527                     return false;
3528                 }
3529             }
3530
3531             // find the best view to give focus to in this brave new non-touch-mode
3532             // world
3533             final View focused = focusSearch(null, View.FOCUS_DOWN);
3534             if (focused != null) {
3535                 return focused.requestFocus(View.FOCUS_DOWN);
3536             }
3537         }
3538         return false;
3539     }
3540
3541     /**
3542      * Base class for implementing a stage in the chain of responsibility
3543      * for processing input events.
3544      * <p>
3545      * Events are delivered to the stage by the {@link #deliver} method.  The stage
3546      * then has the choice of finishing the event or forwarding it to the next stage.
3547      * </p>
3548      */
3549     abstract class InputStage {
3550         private final InputStage mNext;
3551
3552         protected static final int FORWARD = 0;
3553         protected static final int FINISH_HANDLED = 1;
3554         protected static final int FINISH_NOT_HANDLED = 2;
3555
3556         /**
3557          * Creates an input stage.
3558          * @param next The next stage to which events should be forwarded.
3559          */
3560         public InputStage(InputStage next) {
3561             mNext = next;
3562         }
3563
3564         /**
3565          * Delivers an event to be processed.
3566          */
3567         public final void deliver(QueuedInputEvent q) {
3568             if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
3569                 forward(q);
3570             } else if (shouldDropInputEvent(q)) {
3571                 finish(q, false);
3572             } else {
3573                 apply(q, onProcess(q));
3574             }
3575         }
3576
3577         /**
3578          * Marks the the input event as finished then forwards it to the next stage.
3579          */
3580         protected void finish(QueuedInputEvent q, boolean handled) {
3581             q.mFlags |= QueuedInputEvent.FLAG_FINISHED;
3582             if (handled) {
3583                 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;
3584             }
3585             forward(q);
3586         }
3587
3588         /**
3589          * Forwards the event to the next stage.
3590          */
3591         protected void forward(QueuedInputEvent q) {
3592             onDeliverToNext(q);
3593         }
3594
3595         /**
3596          * Applies a result code from {@link #onProcess} to the specified event.
3597          */
3598         protected void apply(QueuedInputEvent q, int result) {
3599             if (result == FORWARD) {
3600                 forward(q);
3601             } else if (result == FINISH_HANDLED) {
3602                 finish(q, true);
3603             } else if (result == FINISH_NOT_HANDLED) {
3604                 finish(q, false);
3605             } else {
3606                 throw new IllegalArgumentException("Invalid result: " + result);
3607             }
3608         }
3609
3610         /**
3611          * Called when an event is ready to be processed.
3612          * @return A result code indicating how the event was handled.
3613          */
3614         protected int onProcess(QueuedInputEvent q) {
3615             return FORWARD;
3616         }
3617
3618         /**
3619          * Called when an event is being delivered to the next stage.
3620          */
3621         protected void onDeliverToNext(QueuedInputEvent q) {
3622             if (DEBUG_INPUT_STAGES) {
3623                 Log.v(TAG, "Done with " + getClass().getSimpleName() + ". " + q);
3624             }
3625             if (mNext != null) {
3626                 mNext.deliver(q);
3627             } else {
3628                 finishInputEvent(q);
3629             }
3630         }
3631
3632         protected boolean shouldDropInputEvent(QueuedInputEvent q) {
3633             if (mView == null || !mAdded) {
3634                 Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent);
3635                 return true;
3636             } else if ((!mAttachInfo.mHasWindowFocus || mStopped)
3637                     && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
3638                 // This is a focus event and the window doesn't currently have input focus or
3639                 // has stopped. This could be an event that came back from the previous stage
3640                 // but the window has lost focus or stopped in the meantime.
3641                 if (isTerminalInputEvent(q.mEvent)) {
3642                     // Don't drop terminal input events, however mark them as canceled.
3643                     q.mEvent.cancel();
3644                     Slog.w(TAG, "Cancelling event due to no window focus: " + q.mEvent);
3645                     return false;
3646                 }
3647
3648                 // Drop non-terminal input events.
3649                 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent);
3650                 return true;
3651             }
3652             return false;
3653         }
3654
3655         void dump(String prefix, PrintWriter writer) {
3656             if (mNext != null) {
3657                 mNext.dump(prefix, writer);
3658             }
3659         }
3660     }
3661
3662     /**
3663      * Base class for implementing an input pipeline stage that supports
3664      * asynchronous and out-of-order processing of input events.
3665      * <p>
3666      * In addition to what a normal input stage can do, an asynchronous
3667      * input stage may also defer an input event that has been delivered to it
3668      * and finish or forward it later.
3669      * </p>
3670      */
3671     abstract class AsyncInputStage extends InputStage {
3672         private final String mTraceCounter;
3673
3674         private QueuedInputEvent mQueueHead;
3675         private QueuedInputEvent mQueueTail;
3676         private int mQueueLength;
3677
3678         protected static final int DEFER = 3;
3679
3680         /**
3681          * Creates an asynchronous input stage.
3682          * @param next The next stage to which events should be forwarded.
3683          * @param traceCounter The name of a counter to record the size of
3684          * the queue of pending events.
3685          */
3686         public AsyncInputStage(InputStage next, String traceCounter) {
3687             super(next);
3688             mTraceCounter = traceCounter;
3689         }
3690
3691         /**
3692          * Marks the event as deferred, which is to say that it will be handled
3693          * asynchronously.  The caller is responsible for calling {@link #forward}
3694          * or {@link #finish} later when it is done handling the event.
3695          */
3696         protected void defer(QueuedInputEvent q) {
3697             q.mFlags |= QueuedInputEvent.FLAG_DEFERRED;
3698             enqueue(q);
3699         }
3700
3701         @Override
3702         protected void forward(QueuedInputEvent q) {
3703             // Clear the deferred flag.
3704             q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
3705
3706             // Fast path if the queue is empty.
3707             QueuedInputEvent curr = mQueueHead;
3708             if (curr == null) {
3709                 super.forward(q);
3710                 return;
3711             }
3712
3713             // Determine whether the event must be serialized behind any others
3714             // before it can be delivered to the next stage.  This is done because
3715             // deferred events might be handled out of order by the stage.
3716             final int deviceId = q.mEvent.getDeviceId();
3717             QueuedInputEvent prev = null;
3718             boolean blocked = false;
3719             while (curr != null && curr != q) {
3720                 if (!blocked && deviceId == curr.mEvent.getDeviceId()) {
3721                     blocked = true;
3722                 }
3723                 prev = curr;
3724                 curr = curr.mNext;
3725             }
3726
3727             // If the event is blocked, then leave it in the queue to be delivered later.
3728             // Note that the event might not yet be in the queue if it was not previously
3729             // deferred so we will enqueue it if needed.
3730             if (blocked) {
3731                 if (curr == null) {
3732                     enqueue(q);
3733                 }
3734                 return;
3735             }
3736
3737             // The event is not blocked.  Deliver it immediately.
3738             if (curr != null) {
3739                 curr = curr.mNext;
3740                 dequeue(q, prev);
3741             }
3742             super.forward(q);
3743
3744             // Dequeuing this event may have unblocked successors.  Deliver them.
3745             while (curr != null) {
3746                 if (deviceId == curr.mEvent.getDeviceId()) {
3747                     if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) {
3748                         break;
3749                     }
3750                     QueuedInputEvent next = curr.mNext;
3751                     dequeue(curr, prev);
3752                     super.forward(curr);
3753                     curr = next;
3754                 } else {
3755                     prev = curr;
3756                     curr = curr.mNext;
3757                 }
3758             }
3759         }
3760
3761         @Override
3762         protected void apply(QueuedInputEvent q, int result) {
3763             if (result == DEFER) {
3764                 defer(q);
3765             } else {
3766                 super.apply(q, result);
3767             }
3768         }
3769
3770         private void enqueue(QueuedInputEvent q) {
3771             if (mQueueTail == null) {
3772                 mQueueHead = q;
3773                 mQueueTail = q;
3774             } else {
3775                 mQueueTail.mNext = q;
3776                 mQueueTail = q;
3777             }
3778
3779             mQueueLength += 1;
3780             Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3781         }
3782
3783         private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) {
3784             if (prev == null) {
3785                 mQueueHead = q.mNext;
3786             } else {
3787                 prev.mNext = q.mNext;
3788             }
3789             if (mQueueTail == q) {
3790                 mQueueTail = prev;
3791             }
3792             q.mNext = null;
3793
3794             mQueueLength -= 1;
3795             Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3796         }
3797
3798         @Override
3799         void dump(String prefix, PrintWriter writer) {
3800             writer.print(prefix);
3801             writer.print(getClass().getName());
3802             writer.print(": mQueueLength=");
3803             writer.println(mQueueLength);
3804
3805             super.dump(prefix, writer);
3806         }
3807     }
3808
3809     /**
3810      * Delivers pre-ime input events to a native activity.
3811      * Does not support pointer events.
3812      */
3813     final class NativePreImeInputStage extends AsyncInputStage
3814             implements InputQueue.FinishedInputEventCallback {
3815         public NativePreImeInputStage(InputStage next, String traceCounter) {
3816             super(next, traceCounter);
3817         }
3818
3819         @Override
3820         protected int onProcess(QueuedInputEvent q) {
3821             if (mInputQueue != null && q.mEvent instanceof KeyEvent) {
3822                 mInputQueue.sendInputEvent(q.mEvent, q, true, this);
3823                 return DEFER;
3824             }
3825             return FORWARD;
3826         }
3827
3828         @Override
3829         public void onFinishedInputEvent(Object token, boolean handled) {
3830             QueuedInputEvent q = (QueuedInputEvent)token;
3831             if (handled) {
3832                 finish(q, true);
3833                 return;
3834             }
3835             forward(q);
3836         }
3837     }
3838
3839     /**
3840      * Delivers pre-ime input events to the view hierarchy.
3841      * Does not support pointer events.
3842      */
3843     final class ViewPreImeInputStage extends InputStage {
3844         public ViewPreImeInputStage(InputStage next) {
3845             super(next);
3846         }
3847
3848         @Override
3849         protected int onProcess(QueuedInputEvent q) {
3850             if (q.mEvent instanceof KeyEvent) {
3851                 return processKeyEvent(q);
3852             }
3853             return FORWARD;
3854         }
3855
3856         private int processKeyEvent(QueuedInputEvent q) {
3857             final KeyEvent event = (KeyEvent)q.mEvent;
3858             if (mView.dispatchKeyEventPreIme(event)) {
3859                 return FINISH_HANDLED;
3860             }
3861             return FORWARD;
3862         }
3863     }
3864
3865     /**
3866      * Delivers input events to the ime.
3867      * Does not support pointer events.
3868      */
3869     final class ImeInputStage extends AsyncInputStage
3870             implements InputMethodManager.FinishedInputEventCallback {
3871         public ImeInputStage(InputStage next, String traceCounter) {
3872             super(next, traceCounter);
3873         }
3874
3875         @Override
3876         protected int onProcess(QueuedInputEvent q) {
3877             if (mLastWasImTarget && !isInLocalFocusMode()) {
3878                 InputMethodManager imm = InputMethodManager.peekInstance();
3879                 if (imm != null) {
3880                     final InputEvent event = q.mEvent;
3881                     if (DEBUG_IMF) Log.v(TAG, "Sending input event to IME: " + event);
3882                     int result = imm.dispatchInputEvent(event, q, this, mHandler);
3883                     if (result == InputMethodManager.DISPATCH_HANDLED) {
3884                         return FINISH_HANDLED;
3885                     } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) {
3886                         // The IME could not handle it, so skip along to the next InputStage
3887                         return FORWARD;
3888                     } else {
3889                         return DEFER; // callback will be invoked later
3890                     }
3891                 }
3892             }
3893             return FORWARD;
3894         }
3895
3896         @Override
3897         public void onFinishedInputEvent(Object token, boolean handled) {
3898             QueuedInputEvent q = (QueuedInputEvent)token;
3899             if (handled) {
3900                 finish(q, true);
3901                 return;
3902             }
3903             forward(q);
3904         }
3905     }
3906
3907     /**
3908      * Performs early processing of post-ime input events.
3909      */
3910     final class EarlyPostImeInputStage extends InputStage {
3911         public EarlyPostImeInputStage(InputStage next) {
3912             super(next);
3913         }
3914
3915         @Override
3916         protected int onProcess(QueuedInputEvent q) {
3917             if (q.mEvent instanceof KeyEvent) {
3918                 return processKeyEvent(q);
3919             } else {
3920                 final int source = q.mEvent.getSource();
3921                 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3922                     return processPointerEvent(q);
3923                 }
3924             }
3925             return FORWARD;
3926         }
3927
3928         private int processKeyEvent(QueuedInputEvent q) {
3929             final KeyEvent event = (KeyEvent)q.mEvent;
3930
3931             // If the key's purpose is to exit touch mode then we consume it
3932             // and consider it handled.
3933             if (checkForLeavingTouchModeAndConsume(event)) {
3934                 return FINISH_HANDLED;
3935             }
3936
3937             // Make sure the fallback event policy sees all keys that will be
3938             // delivered to the view hierarchy.
3939             mFallbackEventHandler.preDispatchKeyEvent(event);
3940             return FORWARD;
3941         }
3942
3943         private int processPointerEvent(QueuedInputEvent q) {
3944             final MotionEvent event = (MotionEvent)q.mEvent;
3945
3946             // Translate the pointer event for compatibility, if needed.
3947             if (mTranslator != null) {
3948                 mTranslator.translateEventInScreenToAppWindow(event);
3949             }
3950
3951             // Enter touch mode on down or scroll.
3952             final int action = event.getAction();
3953             if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3954                 ensureTouchMode(true);
3955             }
3956
3957             // Offset the scroll position.
3958             if (mCurScrollY != 0) {
3959                 event.offsetLocation(0, mCurScrollY);
3960             }
3961
3962             // Remember the touch position for possible drag-initiation.
3963             if (event.isTouchEvent()) {
3964                 mLastTouchPoint.x = event.getRawX();
3965                 mLastTouchPoint.y = event.getRawY();
3966             }
3967             return FORWARD;
3968         }
3969     }
3970
3971     /**
3972      * Delivers post-ime input events to a native activity.
3973      */
3974     final class NativePostImeInputStage extends AsyncInputStage
3975             implements InputQueue.FinishedInputEventCallback {
3976         public NativePostImeInputStage(InputStage next, String traceCounter) {
3977             super(next, traceCounter);
3978         }
3979
3980         @Override
3981         protected int onProcess(QueuedInputEvent q) {
3982             if (mInputQueue != null) {
3983                 mInputQueue.sendInputEvent(q.mEvent, q, false, this);
3984                 return DEFER;
3985             }
3986             return FORWARD;
3987         }
3988
3989         @Override
3990         public void onFinishedInputEvent(Object token, boolean handled) {
3991             QueuedInputEvent q = (QueuedInputEvent)token;
3992             if (handled) {
3993                 finish(q, true);
3994                 return;
3995             }
3996             forward(q);
3997         }
3998     }
3999
4000     /**
4001      * Delivers post-ime input events to the view hierarchy.
4002      */
4003     final class ViewPostImeInputStage extends InputStage {
4004         public ViewPostImeInputStage(InputStage next) {
4005             super(next);
4006         }
4007
4008         @Override
4009         protected int onProcess(QueuedInputEvent q) {
4010             if (q.mEvent instanceof KeyEvent) {
4011                 return processKeyEvent(q);
4012             } else {
4013                 // If delivering a new non-key event, make sure the window is
4014                 // now allowed to start updating.
4015                 handleDispatchDoneAnimating();
4016                 final int source = q.mEvent.getSource();
4017                 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
4018                     return processPointerEvent(q);
4019                 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4020                     return processTrackballEvent(q);
4021                 } else {
4022                     return processGenericMotionEvent(q);
4023                 }
4024             }
4025         }
4026
4027         @Override
4028         protected void onDeliverToNext(QueuedInputEvent q) {
4029             if (mUnbufferedInputDispatch
4030                     && q.mEvent instanceof MotionEvent
4031                     && ((MotionEvent)q.mEvent).isTouchEvent()
4032                     && isTerminalInputEvent(q.mEvent)) {
4033                 mUnbufferedInputDispatch = false;
4034                 scheduleConsumeBatchedInput();
4035             }
4036             super.onDeliverToNext(q);
4037         }
4038
4039         private int processKeyEvent(QueuedInputEvent q) {
4040             final KeyEvent event = (KeyEvent)q.mEvent;
4041
4042             if (event.getAction() != KeyEvent.ACTION_UP) {
4043                 // If delivering a new key event, make sure the window is
4044                 // now allowed to start updating.
4045                 handleDispatchDoneAnimating();
4046             }
4047
4048             // Deliver the key to the view hierarchy.
4049             if (mView.dispatchKeyEvent(event)) {
4050                 return FINISH_HANDLED;
4051             }
4052
4053             if (shouldDropInputEvent(q)) {
4054                 return FINISH_NOT_HANDLED;
4055             }
4056
4057             // If the Control modifier is held, try to interpret the key as a shortcut.
4058             if (event.getAction() == KeyEvent.ACTION_DOWN
4059                     && event.isCtrlPressed()
4060                     && event.getRepeatCount() == 0
4061                     && !KeyEvent.isModifierKey(event.getKeyCode())) {
4062                 if (mView.dispatchKeyShortcutEvent(event)) {
4063                     return FINISH_HANDLED;
4064                 }
4065                 if (shouldDropInputEvent(q)) {
4066                     return FINISH_NOT_HANDLED;
4067                 }
4068             }
4069
4070             // Apply the fallback event policy.
4071             if (mFallbackEventHandler.dispatchKeyEvent(event)) {
4072                 return FINISH_HANDLED;
4073             }
4074             if (shouldDropInputEvent(q)) {
4075                 return FINISH_NOT_HANDLED;
4076             }
4077
4078             // Handle automatic focus changes.
4079             if (event.getAction() == KeyEvent.ACTION_DOWN) {
4080                 int direction = 0;
4081                 switch (event.getKeyCode()) {
4082                     case KeyEvent.KEYCODE_DPAD_LEFT:
4083                         if (event.hasNoModifiers()) {
4084                             direction = View.FOCUS_LEFT;
4085                         }
4086                         break;
4087                     case KeyEvent.KEYCODE_DPAD_RIGHT:
4088                         if (event.hasNoModifiers()) {
4089                             direction = View.FOCUS_RIGHT;
4090                         }
4091                         break;
4092                     case KeyEvent.KEYCODE_DPAD_UP:
4093                         if (event.hasNoModifiers()) {
4094                             direction = View.FOCUS_UP;
4095                         }
4096                         break;
4097                     case KeyEvent.KEYCODE_DPAD_DOWN:
4098                         if (event.hasNoModifiers()) {
4099                             direction = View.FOCUS_DOWN;
4100                         }
4101                         break;
4102                     case KeyEvent.KEYCODE_TAB:
4103                         if (event.hasNoModifiers()) {
4104                             direction = View.FOCUS_FORWARD;
4105                         } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
4106                             direction = View.FOCUS_BACKWARD;
4107                         }
4108                         break;
4109                 }
4110                 if (direction != 0) {
4111                     View focused = mView.findFocus();
4112                     if (focused != null) {
4113                         View v = focused.focusSearch(direction);
4114                         if (v != null && v != focused) {
4115                             // do the math the get the interesting rect
4116                             // of previous focused into the coord system of
4117                             // newly focused view
4118                             focused.getFocusedRect(mTempRect);
4119                             if (mView instanceof ViewGroup) {
4120                                 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
4121                                         focused, mTempRect);
4122                                 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
4123                                         v, mTempRect);
4124                             }
4125                             if (v.requestFocus(direction, mTempRect)) {
4126                                 playSoundEffect(SoundEffectConstants
4127                                         .getContantForFocusDirection(direction));
4128                                 return FINISH_HANDLED;
4129                             }
4130                         }
4131
4132                         // Give the focused view a last chance to handle the dpad key.
4133                         if (mView.dispatchUnhandledMove(focused, direction)) {
4134                             return FINISH_HANDLED;
4135                         }
4136                     } else {
4137                         // find the best view to give focus to in this non-touch-mode with no-focus
4138                         View v = focusSearch(null, direction);
4139                         if (v != null && v.requestFocus(direction)) {
4140                             return FINISH_HANDLED;
4141                         }
4142                     }
4143                 }
4144             }
4145             return FORWARD;
4146         }
4147
4148         private int processPointerEvent(QueuedInputEvent q) {
4149             final MotionEvent event = (MotionEvent)q.mEvent;
4150
4151             mAttachInfo.mUnbufferedDispatchRequested = false;
4152             boolean handled = mView.dispatchPointerEvent(event);
4153             if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4154                 mUnbufferedInputDispatch = true;
4155                 if (mConsumeBatchedInputScheduled) {
4156                     scheduleConsumeBatchedInputImmediately();
4157                 }
4158             }
4159             return handled ? FINISH_HANDLED : FORWARD;
4160         }
4161
4162         private int processTrackballEvent(QueuedInputEvent q) {
4163             final MotionEvent event = (MotionEvent)q.mEvent;
4164
4165             if (mView.dispatchTrackballEvent(event)) {
4166                 return FINISH_HANDLED;
4167             }
4168             return FORWARD;
4169         }
4170
4171         private int processGenericMotionEvent(QueuedInputEvent q) {
4172             final MotionEvent event = (MotionEvent)q.mEvent;
4173
4174             // Deliver the event to the view.
4175             if (mView.dispatchGenericMotionEvent(event)) {
4176                 return FINISH_HANDLED;
4177             }
4178             return FORWARD;
4179         }
4180     }
4181
4182     /**
4183      * Performs synthesis of new input events from unhandled input events.
4184      */
4185     final class SyntheticInputStage extends InputStage {
4186         private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
4187         private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
4188         private final SyntheticTouchNavigationHandler mTouchNavigation =
4189                 new SyntheticTouchNavigationHandler();
4190         private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
4191
4192         public SyntheticInputStage() {
4193             super(null);
4194         }
4195
4196         @Override
4197         protected int onProcess(QueuedInputEvent q) {
4198             q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
4199             if (q.mEvent instanceof MotionEvent) {
4200                 final MotionEvent event = (MotionEvent)q.mEvent;
4201                 final int source = event.getSource();
4202                 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4203                     mTrackball.process(event);
4204                     return FINISH_HANDLED;
4205                 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4206                     mJoystick.process(event);
4207                     return FINISH_HANDLED;
4208                 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4209                         == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4210                     mTouchNavigation.process(event);
4211                     return FINISH_HANDLED;
4212                 }
4213             } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4214                 mKeyboard.process((KeyEvent)q.mEvent);
4215                 return FINISH_HANDLED;
4216             }
4217
4218             return FORWARD;
4219         }
4220
4221         @Override
4222         protected void onDeliverToNext(QueuedInputEvent q) {
4223             if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
4224                 // Cancel related synthetic events if any prior stage has handled the event.
4225                 if (q.mEvent instanceof MotionEvent) {
4226                     final MotionEvent event = (MotionEvent)q.mEvent;
4227                     final int source = event.getSource();
4228                     if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4229                         mTrackball.cancel(event);
4230                     } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4231                         mJoystick.cancel(event);
4232                     } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4233                             == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4234                         mTouchNavigation.cancel(event);
4235                     }
4236                 }
4237             }
4238             super.onDeliverToNext(q);
4239         }
4240     }
4241
4242     /**
4243      * Creates dpad events from unhandled trackball movements.
4244      */
4245     final class SyntheticTrackballHandler {
4246         private final TrackballAxis mX = new TrackballAxis();
4247         private final TrackballAxis mY = new TrackballAxis();
4248         private long mLastTime;
4249
4250         public void process(MotionEvent event) {
4251             // Translate the trackball event into DPAD keys and try to deliver those.
4252             long curTime = SystemClock.uptimeMillis();
4253             if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
4254                 // It has been too long since the last movement,
4255                 // so restart at the beginning.
4256                 mX.reset(0);
4257                 mY.reset(0);
4258                 mLastTime = curTime;
4259             }
4260
4261             final int action = event.getAction();
4262             final int metaState = event.getMetaState();
4263             switch (action) {
4264                 case MotionEvent.ACTION_DOWN:
4265                     mX.reset(2);
4266                     mY.reset(2);
4267                     enqueueInputEvent(new KeyEvent(curTime, curTime,
4268                             KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4269                             KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4270                             InputDevice.SOURCE_KEYBOARD));
4271                     break;
4272                 case MotionEvent.ACTION_UP:
4273                     mX.reset(2);
4274                     mY.reset(2);
4275                     enqueueInputEvent(new KeyEvent(curTime, curTime,
4276                             KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4277                             KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4278                             InputDevice.SOURCE_KEYBOARD));
4279                     break;
4280             }
4281
4282             if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step="
4283                     + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
4284                     + " move=" + event.getX()
4285                     + " / Y=" + mY.position + " step="
4286                     + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
4287                     + " move=" + event.getY());
4288             final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
4289             final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
4290
4291             // Generate DPAD events based on the trackball movement.
4292             // We pick the axis that has moved the most as the direction of
4293             // the DPAD.  When we generate DPAD events for one axis, then the
4294             // other axis is reset -- we don't want to perform DPAD jumps due
4295             // to slight movements in the trackball when making major movements
4296             // along the other axis.
4297             int keycode = 0;
4298             int movement = 0;
4299             float accel = 1;
4300             if (xOff > yOff) {
4301                 movement = mX.generate();
4302                 if (movement != 0) {
4303                     keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
4304                             : KeyEvent.KEYCODE_DPAD_LEFT;
4305                     accel = mX.acceleration;
4306                     mY.reset(2);
4307                 }
4308             } else if (yOff > 0) {
4309                 movement = mY.generate();
4310                 if (movement != 0) {
4311                     keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
4312                             : KeyEvent.KEYCODE_DPAD_UP;
4313                     accel = mY.acceleration;
4314                     mX.reset(2);
4315                 }
4316             }
4317
4318             if (keycode != 0) {
4319                 if (movement < 0) movement = -movement;
4320                 int accelMovement = (int)(movement * accel);
4321                 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
4322                         + " accelMovement=" + accelMovement
4323                         + " accel=" + accel);
4324                 if (accelMovement > movement) {
4325                     if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4326                             + keycode);
4327                     movement--;
4328                     int repeatCount = accelMovement - movement;
4329                     enqueueInputEvent(new KeyEvent(curTime, curTime,
4330                             KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
4331                             KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4332                             InputDevice.SOURCE_KEYBOARD));
4333                 }
4334                 while (movement > 0) {
4335                     if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
4336                             + keycode);
4337                     movement--;
4338                     curTime = SystemClock.uptimeMillis();
4339                     enqueueInputEvent(new KeyEvent(curTime, curTime,
4340                             KeyEvent.ACTION_DOWN, keycode, 0, metaState,
4341                             KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4342                             InputDevice.SOURCE_KEYBOARD));
4343                     enqueueInputEvent(new KeyEvent(curTime, curTime,
4344                             KeyEvent.ACTION_UP, keycode, 0, metaState,
4345                             KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4346                             InputDevice.SOURCE_KEYBOARD));
4347                 }
4348                 mLastTime = curTime;
4349             }
4350         }
4351
4352         public void cancel(MotionEvent event) {
4353             mLastTime = Integer.MIN_VALUE;
4354
4355             // If we reach this, we consumed a trackball event.
4356             // Because we will not translate the trackball event into a key event,
4357             // touch mode will not exit, so we exit touch mode here.
4358             if (mView != null && mAdded) {
4359                 ensureTouchMode(false);
4360             }
4361         }
4362     }
4363
4364     /**
4365      * Maintains state information for a single trackball axis, generating
4366      * discrete (DPAD) movements based on raw trackball motion.
4367      */
4368     static final class TrackballAxis {
4369         /**
4370          * The maximum amount of acceleration we will apply.
4371          */
4372         static final float MAX_ACCELERATION = 20;
4373
4374         /**
4375          * The maximum amount of time (in milliseconds) between events in order
4376          * for us to consider the user to be doing fast trackball movements,
4377          * and thus apply an acceleration.
4378          */
4379         static final long FAST_MOVE_TIME = 150;
4380
4381         /**
4382          * Scaling factor to the time (in milliseconds) between events to how
4383          * much to multiple/divide the current acceleration.  When movement
4384          * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4385          * FAST_MOVE_TIME it divides it.
4386          */
4387         static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4388
4389         static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
4390         static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
4391         static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
4392
4393         float position;
4394         float acceleration = 1;
4395         long lastMoveTime = 0;
4396         int step;
4397         int dir;
4398         int nonAccelMovement;
4399
4400         void reset(int _step) {
4401             position = 0;
4402             acceleration = 1;
4403             lastMoveTime = 0;
4404             step = _step;
4405             dir = 0;
4406         }
4407
4408         /**
4409          * Add trackball movement into the state.  If the direction of movement
4410          * has been reversed, the state is reset before adding the
4411          * movement (so that you don't have to compensate for any previously
4412          * collected movement before see the result of the movement in the
4413          * new direction).
4414          *
4415          * @return Returns the absolute value of the amount of movement
4416          * collected so far.
4417          */
4418         float collect(float off, long time, String axis) {
4419             long normTime;
4420             if (off > 0) {
4421                 normTime = (long)(off * FAST_MOVE_TIME);
4422                 if (dir < 0) {
4423                     if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4424                     position = 0;
4425                     step = 0;
4426                     acceleration = 1;
4427                     lastMoveTime = 0;
4428                 }
4429                 dir = 1;
4430             } else if (off < 0) {
4431                 normTime = (long)((-off) * FAST_MOVE_TIME);
4432                 if (dir > 0) {
4433                     if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4434                     position = 0;
4435                     step = 0;
4436                     acceleration = 1;
4437                     lastMoveTime = 0;
4438                 }
4439                 dir = -1;
4440             } else {
4441                 normTime = 0;
4442             }
4443
4444             // The number of milliseconds between each movement that is
4445             // considered "normal" and will not result in any acceleration
4446             // or deceleration, scaled by the offset we have here.
4447             if (normTime > 0) {
4448                 long delta = time - lastMoveTime;
4449                 lastMoveTime = time;
4450                 float acc = acceleration;
4451                 if (delta < normTime) {
4452                     // The user is scrolling rapidly, so increase acceleration.
4453                     float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4454                     if (scale > 1) acc *= scale;
4455                     if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4456                             + off + " normTime=" + normTime + " delta=" + delta
4457                             + " scale=" + scale + " acc=" + acc);
4458                     acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4459                 } else {
4460                     // The user is scrolling slowly, so decrease acceleration.
4461                     float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4462                     if (scale > 1) acc /= scale;
4463                     if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4464                             + off + " normTime=" + normTime + " delta=" + delta
4465                             + " scale=" + scale + " acc=" + acc);
4466                     acceleration = acc > 1 ? acc : 1;
4467                 }
4468             }
4469             position += off;
4470             return Math.abs(position);
4471         }
4472
4473         /**
4474          * Generate the number of discrete movement events appropriate for
4475          * the currently collected trackball movement.
4476          *
4477          * @return Returns the number of discrete movements, either positive
4478          * or negative, or 0 if there is not enough trackball movement yet
4479          * for a discrete movement.
4480          */
4481         int generate() {
4482             int movement = 0;
4483             nonAccelMovement = 0;
4484             do {
4485                 final int dir = position >= 0 ? 1 : -1;
4486                 switch (step) {
4487                     // If we are going to execute the first step, then we want
4488                     // to do this as soon as possible instead of waiting for
4489                     // a full movement, in order to make things look responsive.
4490                     case 0:
4491                         if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4492                             return movement;
4493                         }
4494                         movement += dir;
4495                         nonAccelMovement += dir;
4496                         step = 1;
4497                         break;
4498                     // If we have generated the first movement, then we need
4499                     // to wait for the second complete trackball motion before
4500                     // generating the second discrete movement.
4501                     case 1:
4502                         if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4503                             return movement;
4504                         }
4505                         movement += dir;
4506                         nonAccelMovement += dir;
4507                         position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
4508                         step = 2;
4509                         break;
4510                     // After the first two, we generate discrete movements
4511                     // consistently with the trackball, applying an acceleration
4512                     // if the trackball is moving quickly.  This is a simple
4513                     // acceleration on top of what we already compute based
4514                     // on how quickly the wheel is being turned, to apply
4515                     // a longer increasing acceleration to continuous movement
4516                     // in one direction.
4517                     default:
4518                         if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4519                             return movement;
4520                         }
4521                         movement += dir;
4522                         position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4523                         float acc = acceleration;
4524                         acc *= 1.1f;
4525                         acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4526                         break;
4527                 }
4528             } while (true);
4529         }
4530     }
4531
4532     /**
4533      * Creates dpad events from unhandled joystick movements.
4534      */
4535     final class SyntheticJoystickHandler extends Handler {
4536         private final static String TAG = "SyntheticJoystickHandler";
4537         private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
4538         private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
4539
4540         private int mLastXDirection;
4541         private int mLastYDirection;
4542         private int mLastXKeyCode;
4543         private int mLastYKeyCode;
4544
4545         public SyntheticJoystickHandler() {
4546             super(true);
4547         }
4548
4549         @Override
4550         public void handleMessage(Message msg) {
4551             switch (msg.what) {
4552                 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
4553                 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
4554                     KeyEvent oldEvent = (KeyEvent)msg.obj;
4555                     KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
4556                             SystemClock.uptimeMillis(),
4557                             oldEvent.getRepeatCount() + 1);
4558                     if (mAttachInfo.mHasWindowFocus) {
4559                         enqueueInputEvent(e);
4560                         Message m = obtainMessage(msg.what, e);
4561                         m.setAsynchronous(true);
4562                         sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
4563                     }
4564                 } break;
4565             }
4566         }
4567
4568         public void process(MotionEvent event) {
4569             switch(event.getActionMasked()) {
4570             case MotionEvent.ACTION_CANCEL:
4571                 cancel(event);
4572                 break;
4573             case MotionEvent.ACTION_MOVE:
4574                 update(event, true);
4575                 break;
4576             default:
4577                 Log.w(TAG, "Unexpected action: " + event.getActionMasked());
4578             }
4579         }
4580
4581         private void cancel(MotionEvent event) {
4582             removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4583             removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4584             update(event, false);
4585         }
4586
4587         private void update(MotionEvent event, boolean synthesizeNewKeys) {
4588             final long time = event.getEventTime();
4589             final int metaState = event.getMetaState();
4590             final int deviceId = event.getDeviceId();
4591             final int source = event.getSource();
4592
4593             int xDirection = joystickAxisValueToDirection(
4594                     event.getAxisValue(MotionEvent.AXIS_HAT_X));
4595             if (xDirection == 0) {
4596                 xDirection = joystickAxisValueToDirection(event.getX());
4597             }
4598
4599             int yDirection = joystickAxisValueToDirection(
4600                     event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4601             if (yDirection == 0) {
4602                 yDirection = joystickAxisValueToDirection(event.getY());
4603             }
4604
4605             if (xDirection != mLastXDirection) {
4606                 if (mLastXKeyCode != 0) {
4607                     removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4608                     enqueueInputEvent(new KeyEvent(time, time,
4609                             KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState,
4610                             deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4611                     mLastXKeyCode = 0;
4612                 }
4613
4614                 mLastXDirection = xDirection;
4615
4616                 if (xDirection != 0 && synthesizeNewKeys) {
4617                     mLastXKeyCode = xDirection > 0
4618                             ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
4619                     final KeyEvent e = new KeyEvent(time, time,
4620                             KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState,
4621                             deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4622                     enqueueInputEvent(e);
4623                     Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
4624                     m.setAsynchronous(true);
4625                     sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4626                 }
4627             }
4628
4629             if (yDirection != mLastYDirection) {
4630                 if (mLastYKeyCode != 0) {
4631                     removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4632                     enqueueInputEvent(new KeyEvent(time, time,
4633                             KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState,
4634                             deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4635                     mLastYKeyCode = 0;
4636                 }
4637
4638                 mLastYDirection = yDirection;
4639
4640                 if (yDirection != 0 && synthesizeNewKeys) {
4641                     mLastYKeyCode = yDirection > 0
4642                             ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
4643                     final KeyEvent e = new KeyEvent(time, time,
4644                             KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState,
4645                             deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4646                     enqueueInputEvent(e);
4647                     Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e);
4648                     m.setAsynchronous(true);
4649                     sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4650                 }
4651             }
4652         }
4653
4654         private int joystickAxisValueToDirection(float value) {
4655             if (value >= 0.5f) {
4656                 return 1;
4657             } else if (value <= -0.5f) {
4658                 return -1;
4659             } else {
4660                 return 0;
4661             }
4662         }
4663     }
4664
4665     /**
4666      * Creates dpad events from unhandled touch navigation movements.
4667      */
4668     final class SyntheticTouchNavigationHandler extends Handler {
4669         private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4670         private static final boolean LOCAL_DEBUG = false;
4671
4672         // Assumed nominal width and height in millimeters of a touch navigation pad,
4673         // if no resolution information is available from the input system.
4674         private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
4675         private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
4676
4677         /* TODO: These constants should eventually be moved to ViewConfiguration. */
4678
4679         // The nominal distance traveled to move by one unit.
4680         private static final int TICK_DISTANCE_MILLIMETERS = 12;
4681
4682         // Minimum and maximum fling velocity in ticks per second.
4683         // The minimum velocity should be set such that we perform enough ticks per
4684         // second that the fling appears to be fluid.  For example, if we set the minimum
4685         // to 2 ticks per second, then there may be up to half a second delay between the next
4686         // to last and last ticks which is noticeably discrete and jerky.  This value should
4687         // probably not be set to anything less than about 4.
4688         // If fling accuracy is a problem then consider tuning the tick distance instead.
4689         private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
4690         private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
4691
4692         // Fling velocity decay factor applied after each new key is emitted.
4693         // This parameter controls the deceleration and overall duration of the fling.
4694         // The fling stops automatically when its velocity drops below the minimum
4695         // fling velocity defined above.
4696         private static final float FLING_TICK_DECAY = 0.8f;
4697
4698         /* The input device that we are tracking. */
4699
4700         private int mCurrentDeviceId = -1;
4701         private int mCurrentSource;
4702         private boolean mCurrentDeviceSupported;
4703
4704         /* Configuration for the current input device. */
4705
4706         // The scaled tick distance.  A movement of this amount should generally translate
4707         // into a single dpad event in a given direction.
4708         private float mConfigTickDistance;
4709
4710         // The minimum and maximum scaled fling velocity.
4711         private float mConfigMinFlingVelocity;
4712         private float mConfigMaxFlingVelocity;
4713
4714         /* Tracking state. */
4715
4716         // The velocity tracker for detecting flings.
4717         private VelocityTracker mVelocityTracker;
4718
4719         // The active pointer id, or -1 if none.
4720         private int mActivePointerId = -1;
4721
4722         // Location where tracking started.
4723         private float mStartX;
4724         private float mStartY;
4725
4726         // Most recently observed position.
4727         private float mLastX;
4728         private float mLastY;
4729
4730         // Accumulated movement delta since the last direction key was sent.
4731         private float mAccumulatedX;
4732         private float mAccumulatedY;
4733
4734         // Set to true if any movement was delivered to the app.
4735         // Implies that tap slop was exceeded.
4736         private boolean mConsumedMovement;
4737
4738         // The most recently sent key down event.
4739         // The keycode remains set until the direction changes or a fling ends
4740         // so that repeated key events may be generated as required.
4741         private long mPendingKeyDownTime;
4742         private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4743         private int mPendingKeyRepeatCount;
4744         private int mPendingKeyMetaState;
4745
4746         // The current fling velocity while a fling is in progress.
4747         private boolean mFlinging;
4748         private float mFlingVelocity;
4749
4750         public SyntheticTouchNavigationHandler() {
4751             super(true);
4752         }
4753
4754         public void process(MotionEvent event) {
4755             // Update the current device information.
4756             final long time = event.getEventTime();
4757             final int deviceId = event.getDeviceId();
4758             final int source = event.getSource();
4759             if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
4760                 finishKeys(time);
4761                 finishTracking(time);
4762                 mCurrentDeviceId = deviceId;
4763                 mCurrentSource = source;
4764                 mCurrentDeviceSupported = false;
4765                 InputDevice device = event.getDevice();
4766                 if (device != null) {
4767                     // In order to support an input device, we must know certain
4768                     // characteristics about it, such as its size and resolution.
4769                     InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
4770                     InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
4771                     if (xRange != null && yRange != null) {
4772                         mCurrentDeviceSupported = true;
4773
4774                         // Infer the resolution if it not actually known.
4775                         float xRes = xRange.getResolution();
4776                         if (xRes <= 0) {
4777                             xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
4778                         }
4779                         float yRes = yRange.getResolution();
4780                         if (yRes <= 0) {
4781                             yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
4782                         }
4783                         float nominalRes = (xRes + yRes) * 0.5f;
4784
4785                         // Precompute all of the configuration thresholds we will need.
4786                         mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
4787                         mConfigMinFlingVelocity =
4788                                 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4789                         mConfigMaxFlingVelocity =
4790                                 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
4791
4792                         if (LOCAL_DEBUG) {
4793                             Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
4794                                     + " (" + Integer.toHexString(mCurrentSource) + "): "
4795                                     + ", mConfigTickDistance=" + mConfigTickDistance
4796                                     + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
4797                                     + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
4798                         }
4799                     }
4800                 }
4801             }
4802             if (!mCurrentDeviceSupported) {
4803                 return;
4804             }
4805
4806             // Handle the event.
4807             final int action = event.getActionMasked();
4808             switch (action) {
4809                 case MotionEvent.ACTION_DOWN: {
4810                     boolean caughtFling = mFlinging;
4811                     finishKeys(time);
4812                     finishTracking(time);
4813                     mActivePointerId = event.getPointerId(0);
4814                     mVelocityTracker = VelocityTracker.obtain();
4815                     mVelocityTracker.addMovement(event);
4816                     mStartX = event.getX();
4817                     mStartY = event.getY();
4818                     mLastX = mStartX;
4819                     mLastY = mStartY;
4820                     mAccumulatedX = 0;
4821                     mAccumulatedY = 0;
4822
4823                     // If we caught a fling, then pretend that the tap slop has already
4824                     // been exceeded to suppress taps whose only purpose is to stop the fling.
4825                     mConsumedMovement = caughtFling;
4826                     break;
4827                 }
4828
4829                 case MotionEvent.ACTION_MOVE:
4830                 case MotionEvent.ACTION_UP: {
4831                     if (mActivePointerId < 0) {
4832                         break;
4833                     }
4834                     final int index = event.findPointerIndex(mActivePointerId);
4835                     if (index < 0) {
4836                         finishKeys(time);
4837                         finishTracking(time);
4838                         break;
4839                     }
4840
4841                     mVelocityTracker.addMovement(event);
4842                     final float x = event.getX(index);
4843                     final float y = event.getY(index);
4844                     mAccumulatedX += x - mLastX;
4845                     mAccumulatedY += y - mLastY;
4846                     mLastX = x;
4847                     mLastY = y;
4848
4849                     // Consume any accumulated movement so far.
4850                     final int metaState = event.getMetaState();
4851                     consumeAccumulatedMovement(time, metaState);
4852
4853                     // Detect taps and flings.
4854                     if (action == MotionEvent.ACTION_UP) {
4855                         if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4856                             // It might be a fling.
4857                             mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
4858                             final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
4859                             final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
4860                             if (!startFling(time, vx, vy)) {
4861                                 finishKeys(time);
4862                             }
4863                         }
4864                         finishTracking(time);
4865                     }
4866                     break;
4867                 }
4868
4869                 case MotionEvent.ACTION_CANCEL: {
4870                     finishKeys(time);
4871                     finishTracking(time);
4872                     break;
4873                 }
4874             }
4875         }
4876
4877         public void cancel(MotionEvent event) {
4878             if (mCurrentDeviceId == event.getDeviceId()
4879                     && mCurrentSource == event.getSource()) {
4880                 final long time = event.getEventTime();
4881                 finishKeys(time);
4882                 finishTracking(time);
4883             }
4884         }
4885
4886         private void finishKeys(long time) {
4887             cancelFling();
4888             sendKeyUp(time);
4889         }
4890
4891         private void finishTracking(long time) {
4892             if (mActivePointerId >= 0) {
4893                 mActivePointerId = -1;
4894                 mVelocityTracker.recycle();
4895                 mVelocityTracker = null;
4896             }
4897         }
4898
4899         private void consumeAccumulatedMovement(long time, int metaState) {
4900             final float absX = Math.abs(mAccumulatedX);
4901             final float absY = Math.abs(mAccumulatedY);
4902             if (absX >= absY) {
4903                 if (absX >= mConfigTickDistance) {
4904                     mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
4905                             KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
4906                     mAccumulatedY = 0;
4907                     mConsumedMovement = true;
4908                 }
4909             } else {
4910                 if (absY >= mConfigTickDistance) {
4911                     mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
4912                             KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
4913                     mAccumulatedX = 0;
4914                     mConsumedMovement = true;
4915                 }
4916             }
4917         }
4918
4919         private float consumeAccumulatedMovement(long time, int metaState,
4920                 float accumulator, int negativeKeyCode, int positiveKeyCode) {
4921             while (accumulator <= -mConfigTickDistance) {
4922                 sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
4923                 accumulator += mConfigTickDistance;
4924             }
4925             while (accumulator >= mConfigTickDistance) {
4926                 sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
4927                 accumulator -= mConfigTickDistance;
4928             }
4929             return accumulator;
4930         }
4931
4932         private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
4933             if (mPendingKeyCode != keyCode) {
4934                 sendKeyUp(time);
4935                 mPendingKeyDownTime = time;
4936                 mPendingKeyCode = keyCode;
4937                 mPendingKeyRepeatCount = 0;
4938             } else {
4939                 mPendingKeyRepeatCount += 1;
4940             }
4941             mPendingKeyMetaState = metaState;
4942
4943             // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
4944             // but it doesn't quite make sense when simulating the events in this way.
4945             if (LOCAL_DEBUG) {
4946                 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
4947                         + ", repeatCount=" + mPendingKeyRepeatCount
4948                         + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4949             }
4950             enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4951                     KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
4952                     mPendingKeyMetaState, mCurrentDeviceId,
4953                     KeyEvent.FLAG_FALLBACK, mCurrentSource));
4954         }
4955
4956         private void sendKeyUp(long time) {
4957             if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4958                 if (LOCAL_DEBUG) {
4959                     Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
4960                             + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4961                 }
4962                 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4963                         KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
4964                         mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
4965                         mCurrentSource));
4966                 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4967             }
4968         }
4969
4970         private boolean startFling(long time, float vx, float vy) {
4971             if (LOCAL_DEBUG) {
4972                 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
4973                         + ", min=" + mConfigMinFlingVelocity);
4974             }
4975
4976             // Flings must be oriented in the same direction as the preceding movements.
4977             switch (mPendingKeyCode) {
4978                 case KeyEvent.KEYCODE_DPAD_LEFT:
4979                     if (-vx >= mConfigMinFlingVelocity
4980                             && Math.abs(vy) < mConfigMinFlingVelocity) {
4981                         mFlingVelocity = -vx;
4982                         break;
4983                     }
4984                     return false;
4985
4986                 case KeyEvent.KEYCODE_DPAD_RIGHT:
4987                     if (vx >= mConfigMinFlingVelocity
4988                             && Math.abs(vy) < mConfigMinFlingVelocity) {
4989                         mFlingVelocity = vx;
4990                         break;
4991                     }
4992                     return false;
4993
4994                 case KeyEvent.KEYCODE_DPAD_UP:
4995                     if (-vy >= mConfigMinFlingVelocity
4996                             && Math.abs(vx) < mConfigMinFlingVelocity) {
4997                         mFlingVelocity = -vy;
4998                         break;
4999                     }
5000                     return false;
5001
5002                 case KeyEvent.KEYCODE_DPAD_DOWN:
5003                     if (vy >= mConfigMinFlingVelocity
5004                             && Math.abs(vx) < mConfigMinFlingVelocity) {
5005                         mFlingVelocity = vy;
5006                         break;
5007                     }
5008                     return false;
5009             }
5010
5011             // Post the first fling event.
5012             mFlinging = postFling(time);
5013             return mFlinging;
5014         }
5015
5016         private boolean postFling(long time) {
5017             // The idea here is to estimate the time when the pointer would have
5018             // traveled one tick distance unit given the current fling velocity.
5019             // This effect creates continuity of motion.
5020             if (mFlingVelocity >= mConfigMinFlingVelocity) {
5021                 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
5022                 postAtTime(mFlingRunnable, time + delay);
5023                 if (LOCAL_DEBUG) {
5024                     Log.d(LOCAL_TAG, "Posted fling: velocity="
5025                             + mFlingVelocity + ", delay=" + delay
5026                             + ", keyCode=" + mPendingKeyCode);
5027                 }
5028                 return true;
5029             }
5030             return false;
5031         }
5032
5033         private void cancelFling() {
5034             if (mFlinging) {
5035                 removeCallbacks(mFlingRunnable);
5036                 mFlinging = false;
5037             }
5038         }
5039
5040         private final Runnable mFlingRunnable = new Runnable() {
5041             @Override
5042             public void run() {
5043                 final long time = SystemClock.uptimeMillis();
5044                 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5045                 mFlingVelocity *= FLING_TICK_DECAY;
5046                 if (!postFling(time)) {
5047                     mFlinging = false;
5048                     finishKeys(time);
5049                 }
5050             }
5051         };
5052     }
5053
5054     final class SyntheticKeyboardHandler {
5055         public void process(KeyEvent event) {
5056             if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5057                 return;
5058             }
5059
5060             final KeyCharacterMap kcm = event.getKeyCharacterMap();
5061             final int keyCode = event.getKeyCode();
5062             final int metaState = event.getMetaState();
5063
5064             // Check for fallback actions specified by the key character map.
5065             KeyCharacterMap.FallbackAction fallbackAction =
5066                     kcm.getFallbackAction(keyCode, metaState);
5067             if (fallbackAction != null) {
5068                 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5069                 KeyEvent fallbackEvent = KeyEvent.obtain(
5070                         event.getDownTime(), event.getEventTime(),
5071                         event.getAction(), fallbackAction.keyCode,
5072                         event.getRepeatCount(), fallbackAction.metaState,
5073                         event.getDeviceId(), event.getScanCode(),
5074                         flags, event.getSource(), null);
5075                 fallbackAction.recycle();
5076                 enqueueInputEvent(fallbackEvent);
5077             }
5078         }
5079     }
5080
5081     /**
5082      * Returns true if the key is used for keyboard navigation.
5083      * @param keyEvent The key event.
5084      * @return True if the key is used for keyboard navigation.
5085      */
5086     private static boolean isNavigationKey(KeyEvent keyEvent) {
5087         switch (keyEvent.getKeyCode()) {
5088         case KeyEvent.KEYCODE_DPAD_LEFT:
5089         case KeyEvent.KEYCODE_DPAD_RIGHT:
5090         case KeyEvent.KEYCODE_DPAD_UP:
5091         case KeyEvent.KEYCODE_DPAD_DOWN:
5092         case KeyEvent.KEYCODE_DPAD_CENTER:
5093         case KeyEvent.KEYCODE_PAGE_UP:
5094         case KeyEvent.KEYCODE_PAGE_DOWN:
5095         case KeyEvent.KEYCODE_MOVE_HOME:
5096         case KeyEvent.KEYCODE_MOVE_END:
5097         case KeyEvent.KEYCODE_TAB:
5098         case KeyEvent.KEYCODE_SPACE:
5099         case KeyEvent.KEYCODE_ENTER:
5100             return true;
5101         }
5102         return false;
5103     }
5104
5105     /**
5106      * Returns true if the key is used for typing.
5107      * @param keyEvent The key event.
5108      * @return True if the key is used for typing.
5109      */
5110     private static boolean isTypingKey(KeyEvent keyEvent) {
5111         return keyEvent.getUnicodeChar() > 0;
5112     }
5113
5114     /**
5115      * See if the key event means we should leave touch mode (and leave touch mode if so).
5116      * @param event The key event.
5117      * @return Whether this key event should be consumed (meaning the act of
5118      *   leaving touch mode alone is considered the event).
5119      */
5120     private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
5121         // Only relevant in touch mode.
5122         if (!mAttachInfo.mInTouchMode) {
5123             return false;
5124         }
5125
5126         // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
5127         final int action = event.getAction();
5128         if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
5129             return false;
5130         }
5131
5132         // Don't leave touch mode if the IME told us not to.
5133         if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
5134             return false;
5135         }
5136
5137         // If the key can be used for keyboard navigation then leave touch mode
5138         // and select a focused view if needed (in ensureTouchMode).
5139         // When a new focused view is selected, we consume the navigation key because
5140         // navigation doesn't make much sense unless a view already has focus so
5141         // the key's purpose is to set focus.
5142         if (isNavigationKey(event)) {
5143             return ensureTouchMode(false);
5144         }
5145
5146         // If the key can be used for typing then leave touch mode
5147         // and select a focused view if needed (in ensureTouchMode).
5148         // Always allow the view to process the typing key.
5149         if (isTypingKey(event)) {
5150             ensureTouchMode(false);
5151             return false;
5152         }
5153
5154         return false;
5155     }
5156
5157     /* drag/drop */
5158     void setLocalDragState(Object obj) {
5159         mLocalDragState = obj;
5160     }
5161
5162     private void handleDragEvent(DragEvent event) {
5163         // From the root, only drag start/end/location are dispatched.  entered/exited
5164         // are determined and dispatched by the viewgroup hierarchy, who then report
5165         // that back here for ultimate reporting back to the framework.
5166         if (mView != null && mAdded) {
5167             final int what = event.mAction;
5168
5169             if (what == DragEvent.ACTION_DRAG_EXITED) {
5170                 // A direct EXITED event means that the window manager knows we've just crossed
5171                 // a window boundary, so the current drag target within this one must have
5172                 // just been exited.  Send it the usual notifications and then we're done
5173                 // for now.
5174                 mView.dispatchDragEvent(event);
5175             } else {
5176                 // Cache the drag description when the operation starts, then fill it in
5177                 // on subsequent calls as a convenience
5178                 if (what == DragEvent.ACTION_DRAG_STARTED) {
5179                     mCurrentDragView = null;    // Start the current-recipient tracking
5180                     mDragDescription = event.mClipDescription;
5181                 } else {
5182                     event.mClipDescription = mDragDescription;
5183                 }
5184
5185                 // For events with a [screen] location, translate into window coordinates
5186                 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
5187                     mDragPoint.set(event.mX, event.mY);
5188                     if (mTranslator != null) {
5189                         mTranslator.translatePointInScreenToAppWindow(mDragPoint);
5190                     }
5191
5192                     if (mCurScrollY != 0) {
5193                         mDragPoint.offset(0, mCurScrollY);
5194                     }
5195
5196                     event.mX = mDragPoint.x;
5197                     event.mY = mDragPoint.y;
5198                 }
5199
5200                 // Remember who the current drag target is pre-dispatch
5201                 final View prevDragView = mCurrentDragView;
5202
5203                 // Now dispatch the drag/drop event
5204                 boolean result = mView.dispatchDragEvent(event);
5205
5206                 // If we changed apparent drag target, tell the OS about it
5207                 if (prevDragView != mCurrentDragView) {
5208                     try {
5209                         if (prevDragView != null) {
5210                             mWindowSession.dragRecipientExited(mWindow);
5211                         }
5212                         if (mCurrentDragView != null) {
5213                             mWindowSession.dragRecipientEntered(mWindow);
5214                         }
5215                     } catch (RemoteException e) {
5216                         Slog.e(TAG, "Unable to note drag target change");
5217                     }
5218                 }
5219
5220                 // Report the drop result when we're done
5221                 if (what == DragEvent.ACTION_DROP) {
5222                     mDragDescription = null;
5223                     try {
5224                         Log.i(TAG, "Reporting drop result: " + result);
5225                         mWindowSession.reportDropResult(mWindow, result);
5226                     } catch (RemoteException e) {
5227                         Log.e(TAG, "Unable to report drop result");
5228                     }
5229                 }
5230
5231                 // When the drag operation ends, release any local state object
5232                 // that may have been in use
5233                 if (what == DragEvent.ACTION_DRAG_ENDED) {
5234                     setLocalDragState(null);
5235                 }
5236             }
5237         }
5238         event.recycle();
5239     }
5240
5241     public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
5242         if (mSeq != args.seq) {
5243             // The sequence has changed, so we need to update our value and make
5244             // sure to do a traversal afterward so the window manager is given our
5245             // most recent data.
5246             mSeq = args.seq;
5247             mAttachInfo.mForceReportNewAttributes = true;
5248             scheduleTraversals();
5249         }
5250         if (mView == null) return;
5251         if (args.localChanges != 0) {
5252             mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
5253         }
5254
5255         int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5256         if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5257             mAttachInfo.mGlobalSystemUiVisibility = visibility;
5258             mView.dispatchSystemUiVisibilityChanged(visibility);
5259         }
5260     }
5261
5262     public void handleDispatchDoneAnimating() {
5263         if (mWindowsAnimating) {
5264             mWindowsAnimating = false;
5265             if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded)  {
5266                 scheduleTraversals();
5267             }
5268         }
5269     }
5270
5271     public void handleDispatchWindowShown() {
5272         mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5273     }
5274
5275     public void getLastTouchPoint(Point outLocation) {
5276         outLocation.x = (int) mLastTouchPoint.x;
5277         outLocation.y = (int) mLastTouchPoint.y;
5278     }
5279
5280     public void setDragFocus(View newDragTarget) {
5281         if (mCurrentDragView != newDragTarget) {
5282             mCurrentDragView = newDragTarget;
5283         }
5284     }
5285
5286     private AudioManager getAudioManager() {
5287         if (mView == null) {
5288             throw new IllegalStateException("getAudioManager called when there is no mView");
5289         }
5290         if (mAudioManager == null) {
5291             mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5292         }
5293         return mAudioManager;
5294     }
5295
5296     public AccessibilityInteractionController getAccessibilityInteractionController() {
5297         if (mView == null) {
5298             throw new IllegalStateException("getAccessibilityInteractionController"
5299                     + " called when there is no mView");
5300         }
5301         if (mAccessibilityInteractionController == null) {
5302             mAccessibilityInteractionController = new AccessibilityInteractionController(this);
5303         }
5304         return mAccessibilityInteractionController;
5305     }
5306
5307     private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5308             boolean insetsPending) throws RemoteException {
5309
5310         float appScale = mAttachInfo.mApplicationScale;
5311         boolean restore = false;
5312         if (params != null && mTranslator != null) {
5313             restore = true;
5314             params.backup();
5315             mTranslator.translateWindowLayout(params);
5316         }
5317         if (params != null) {
5318             if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
5319         }
5320         mPendingConfiguration.seq = 0;
5321         //Log.d(TAG, ">>>>>> CALLING relayout");
5322         if (params != null && mOrigWindowType != params.type) {
5323             // For compatibility with old apps, don't crash here.
5324             if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5325                 Slog.w(TAG, "Window type can not be changed after "
5326                         + "the window is added; ignoring change of " + mView);
5327                 params.type = mOrigWindowType;
5328             }
5329         }
5330         int relayoutResult = mWindowSession.relayout(
5331                 mWindow, mSeq, params,
5332                 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
5333                 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
5334                 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
5335                 mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
5336                 mPendingStableInsets, mPendingConfiguration, mSurface);
5337         //Log.d(TAG, "<<<<<< BACK FROM relayout");
5338         if (restore) {
5339             params.restore();
5340         }
5341
5342         if (mTranslator != null) {
5343             mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
5344             mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
5345             mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5346             mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
5347             mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
5348         }
5349         return relayoutResult;
5350     }
5351
5352     /**
5353      * {@inheritDoc}
5354      */
5355     @Override
5356     public void playSoundEffect(int effectId) {
5357         checkThread();
5358
5359         try {
5360             final AudioManager audioManager = getAudioManager();
5361
5362             switch (effectId) {
5363                 case SoundEffectConstants.CLICK:
5364                     audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5365                     return;
5366                 case SoundEffectConstants.NAVIGATION_DOWN:
5367                     audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5368                     return;
5369                 case SoundEffectConstants.NAVIGATION_LEFT:
5370                     audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5371                     return;
5372                 case SoundEffectConstants.NAVIGATION_RIGHT:
5373                     audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5374                     return;
5375                 case SoundEffectConstants.NAVIGATION_UP:
5376                     audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5377                     return;
5378                 default:
5379                     throw new IllegalArgumentException("unknown effect id " + effectId +
5380                             " not defined in " + SoundEffectConstants.class.getCanonicalName());
5381             }
5382         } catch (IllegalStateException e) {
5383             // Exception thrown by getAudioManager() when mView is null
5384             Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
5385             e.printStackTrace();
5386         }
5387     }
5388
5389     /**
5390      * {@inheritDoc}
5391      */
5392     @Override
5393     public boolean performHapticFeedback(int effectId, boolean always) {
5394         try {
5395             return mWindowSession.performHapticFeedback(mWindow, effectId, always);
5396         } catch (RemoteException e) {
5397             return false;
5398         }
5399     }
5400
5401     /**
5402      * {@inheritDoc}
5403      */
5404     @Override
5405     public View focusSearch(View focused, int direction) {
5406         checkThread();
5407         if (!(mView instanceof ViewGroup)) {
5408             return null;
5409         }
5410         return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5411     }
5412
5413     public void debug() {
5414         mView.debug();
5415     }
5416
5417     public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5418         String innerPrefix = prefix + "  ";
5419         writer.print(prefix); writer.println("ViewRoot:");
5420         writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded);
5421                 writer.print(" mRemoved="); writer.println(mRemoved);
5422         writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled=");
5423                 writer.println(mConsumeBatchedInputScheduled);
5424         writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled=");
5425                 writer.println(mConsumeBatchedInputImmediatelyScheduled);
5426         writer.print(innerPrefix); writer.print("mPendingInputEventCount=");
5427                 writer.println(mPendingInputEventCount);
5428         writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled=");
5429                 writer.println(mProcessInputEventsScheduled);
5430         writer.print(innerPrefix); writer.print("mTraversalScheduled=");
5431                 writer.print(mTraversalScheduled);
5432         if (mTraversalScheduled) {
5433             writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")");
5434         } else {
5435             writer.println();
5436         }
5437         mFirstInputStage.dump(innerPrefix, writer);
5438
5439         mChoreographer.dump(prefix, writer);
5440
5441         writer.print(prefix); writer.println("View Hierarchy:");
5442         dumpViewHierarchy(innerPrefix, writer, mView);
5443     }
5444
5445     private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5446         writer.print(prefix);
5447         if (view == null) {
5448             writer.println("null");
5449             return;
5450         }
5451         writer.println(view.toString());
5452         if (!(view instanceof ViewGroup)) {
5453             return;
5454         }
5455         ViewGroup grp = (ViewGroup)view;
5456         final int N = grp.getChildCount();
5457         if (N <= 0) {
5458             return;
5459         }
5460         prefix = prefix + "  ";
5461         for (int i=0; i<N; i++) {
5462             dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5463         }
5464     }
5465
5466     public void dumpGfxInfo(int[] info) {
5467         info[0] = info[1] = 0;
5468         if (mView != null) {
5469             getGfxInfo(mView, info);
5470         }
5471     }
5472
5473     private static void getGfxInfo(View view, int[] info) {
5474         RenderNode renderNode = view.mRenderNode;
5475         info[0]++;
5476         if (renderNode != null) {
5477             info[1] += renderNode.getDebugSize();
5478         }
5479
5480         if (view instanceof ViewGroup) {
5481             ViewGroup group = (ViewGroup) view;
5482
5483             int count = group.getChildCount();
5484             for (int i = 0; i < count; i++) {
5485                 getGfxInfo(group.getChildAt(i), info);
5486             }
5487         }
5488     }
5489
5490     /**
5491      * @param immediate True, do now if not in traversal. False, put on queue and do later.
5492      * @return True, request has been queued. False, request has been completed.
5493      */
5494     boolean die(boolean immediate) {
5495         // Make sure we do execute immediately if we are in the middle of a traversal or the damage
5496         // done by dispatchDetachedFromWindow will cause havoc on return.
5497         if (immediate && !mIsInTraversal) {
5498             doDie();
5499             return false;
5500         }
5501
5502         if (!mIsDrawing) {
5503             destroyHardwareRenderer();
5504         } else {
5505             Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
5506                     "  window=" + this + ", title=" + mWindowAttributes.getTitle());
5507         }
5508         mHandler.sendEmptyMessage(MSG_DIE);
5509         return true;
5510     }
5511
5512     void doDie() {
5513         checkThread();
5514         if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
5515         synchronized (this) {
5516             if (mRemoved) {
5517                 return;
5518             }
5519             mRemoved = true;
5520             if (mAdded) {
5521                 dispatchDetachedFromWindow();
5522             }
5523
5524             if (mAdded && !mFirst) {
5525                 destroyHardwareRenderer();
5526
5527                 if (mView != null) {
5528                     int viewVisibility = mView.getVisibility();
5529                     boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
5530                     if (mWindowAttributesChanged || viewVisibilityChanged) {
5531                         // If layout params have been changed, first give them
5532                         // to the window manager to make sure it has the correct
5533                         // animation info.
5534                         try {
5535                             if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5536                                     & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5537                                 mWindowSession.finishDrawing(mWindow);
5538                             }
5539                         } catch (RemoteException e) {
5540                         }
5541                     }
5542
5543                     mSurface.release();
5544                 }
5545             }
5546
5547             mAdded = false;
5548         }
5549         WindowManagerGlobal.getInstance().doRemoveView(this);
5550     }
5551
5552     public void requestUpdateConfiguration(Configuration config) {
5553         Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5554         mHandler.sendMessage(msg);
5555     }
5556
5557     public void loadSystemProperties() {
5558         mHandler.post(new Runnable() {
5559             @Override
5560             public void run() {
5561                 // Profiling
5562                 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5563                 profileRendering(mAttachInfo.mHasWindowFocus);
5564
5565                 // Hardware rendering
5566                 if (mAttachInfo.mHardwareRenderer != null) {
5567                     if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
5568                         invalidate();
5569                     }
5570                 }
5571
5572                 // Layout debugging
5573                 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5574                 if (layout != mAttachInfo.mDebugLayout) {
5575                     mAttachInfo.mDebugLayout = layout;
5576                     if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5577                         mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5578                     }
5579                 }
5580             }
5581         });
5582     }
5583
5584     private void destroyHardwareRenderer() {
5585         HardwareRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
5586
5587         if (hardwareRenderer != null) {
5588             if (mView != null) {
5589                 hardwareRenderer.destroyHardwareResources(mView);
5590             }
5591             hardwareRenderer.destroy();
5592             hardwareRenderer.setRequested(false);
5593
5594             mAttachInfo.mHardwareRenderer = null;
5595             mAttachInfo.mHardwareAccelerated = false;
5596         }
5597     }
5598
5599     public void dispatchFinishInputConnection(InputConnection connection) {
5600         Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
5601         mHandler.sendMessage(msg);
5602     }
5603
5604     public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
5605             Rect visibleInsets, Rect stableInsets, boolean reportDraw, Configuration newConfig) {
5606         if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
5607                 + " contentInsets=" + contentInsets.toShortString()
5608                 + " visibleInsets=" + visibleInsets.toShortString()
5609                 + " reportDraw=" + reportDraw);
5610         Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
5611         if (mTranslator != null) {
5612             mTranslator.translateRectInScreenToAppWindow(frame);
5613             mTranslator.translateRectInScreenToAppWindow(overscanInsets);
5614             mTranslator.translateRectInScreenToAppWindow(contentInsets);
5615             mTranslator.translateRectInScreenToAppWindow(visibleInsets);
5616         }
5617         SomeArgs args = SomeArgs.obtain();
5618         final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5619         args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5620         args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5621         args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5622         args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
5623         args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
5624         args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets;
5625         msg.obj = args;
5626         mHandler.sendMessage(msg);
5627     }
5628
5629     public void dispatchMoved(int newX, int newY) {
5630         if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
5631         if (mTranslator != null) {
5632             PointF point = new PointF(newX, newY);
5633             mTranslator.translatePointInScreenToAppWindow(point);
5634             newX = (int) (point.x + 0.5);
5635             newY = (int) (point.y + 0.5);
5636         }
5637         Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5638         mHandler.sendMessage(msg);
5639     }
5640
5641     /**
5642      * Represents a pending input event that is waiting in a queue.
5643      *
5644      * Input events are processed in serial order by the timestamp specified by
5645      * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
5646      * one input event to the application at a time and waits for the application
5647      * to finish handling it before delivering the next one.
5648      *
5649      * However, because the application or IME can synthesize and inject multiple
5650      * key events at a time without going through the input dispatcher, we end up
5651      * needing a queue on the application's side.
5652      */
5653     private static final class QueuedInputEvent {
5654         public static final int FLAG_DELIVER_POST_IME = 1 << 0;
5655         public static final int FLAG_DEFERRED = 1 << 1;
5656         public static final int FLAG_FINISHED = 1 << 2;
5657         public static final int FLAG_FINISHED_HANDLED = 1 << 3;
5658         public static final int FLAG_RESYNTHESIZED = 1 << 4;
5659         public static final int FLAG_UNHANDLED = 1 << 5;
5660
5661         public QueuedInputEvent mNext;
5662
5663         public InputEvent mEvent;
5664         public InputEventReceiver mReceiver;
5665         public int mFlags;
5666
5667         public boolean shouldSkipIme() {
5668             if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5669                 return true;
5670             }
5671             return mEvent instanceof MotionEvent
5672                     && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5673         }
5674
5675         public boolean shouldSendToSynthesizer() {
5676             if ((mFlags & FLAG_UNHANDLED) != 0) {
5677                 return true;
5678             }
5679
5680             return false;
5681         }
5682
5683         @Override
5684         public String toString() {
5685             StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
5686             boolean hasPrevious = false;
5687             hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
5688             hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
5689             hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
5690             hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
5691             hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
5692             hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
5693             if (!hasPrevious) {
5694                 sb.append("0");
5695             }
5696             sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
5697             sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
5698             sb.append(", mEvent=" + mEvent + "}");
5699             return sb.toString();
5700         }
5701
5702         private boolean flagToString(String name, int flag,
5703                 boolean hasPrevious, StringBuilder sb) {
5704             if ((mFlags & flag) != 0) {
5705                 if (hasPrevious) {
5706                     sb.append("|");
5707                 }
5708                 sb.append(name);
5709                 return true;
5710             }
5711             return hasPrevious;
5712         }
5713     }
5714
5715     private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
5716             InputEventReceiver receiver, int flags) {
5717         QueuedInputEvent q = mQueuedInputEventPool;
5718         if (q != null) {
5719             mQueuedInputEventPoolSize -= 1;
5720             mQueuedInputEventPool = q.mNext;
5721             q.mNext = null;
5722         } else {
5723             q = new QueuedInputEvent();
5724         }
5725
5726         q.mEvent = event;
5727         q.mReceiver = receiver;
5728         q.mFlags = flags;
5729         return q;
5730     }
5731
5732     private void recycleQueuedInputEvent(QueuedInputEvent q) {
5733         q.mEvent = null;
5734         q.mReceiver = null;
5735
5736         if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
5737             mQueuedInputEventPoolSize += 1;
5738             q.mNext = mQueuedInputEventPool;
5739             mQueuedInputEventPool = q;
5740         }
5741     }
5742
5743     void enqueueInputEvent(InputEvent event) {
5744         enqueueInputEvent(event, null, 0, false);
5745     }
5746
5747     void enqueueInputEvent(InputEvent event,
5748             InputEventReceiver receiver, int flags, boolean processImmediately) {
5749         adjustInputEventForCompatibility(event);
5750         QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
5751
5752         // Always enqueue the input event in order, regardless of its time stamp.
5753         // We do this because the application or the IME may inject key events
5754         // in response to touch events and we want to ensure that the injected keys
5755         // are processed in the order they were received and we cannot trust that
5756         // the time stamp of injected events are monotonic.
5757         QueuedInputEvent last = mPendingInputEventTail;
5758         if (last == null) {
5759             mPendingInputEventHead = q;
5760             mPendingInputEventTail = q;
5761         } else {
5762             last.mNext = q;
5763             mPendingInputEventTail = q;
5764         }
5765         mPendingInputEventCount += 1;
5766         Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5767                 mPendingInputEventCount);
5768
5769         if (processImmediately) {
5770             doProcessInputEvents();
5771         } else {
5772             scheduleProcessInputEvents();
5773         }
5774     }
5775
5776     private void scheduleProcessInputEvents() {
5777         if (!mProcessInputEventsScheduled) {
5778             mProcessInputEventsScheduled = true;
5779             Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
5780             msg.setAsynchronous(true);
5781             mHandler.sendMessage(msg);
5782         }
5783     }
5784
5785     void doProcessInputEvents() {
5786         // Deliver all pending input events in the queue.
5787         while (mPendingInputEventHead != null) {
5788             QueuedInputEvent q = mPendingInputEventHead;
5789             mPendingInputEventHead = q.mNext;
5790             if (mPendingInputEventHead == null) {
5791                 mPendingInputEventTail = null;
5792             }
5793             q.mNext = null;
5794
5795             mPendingInputEventCount -= 1;
5796             Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5797                     mPendingInputEventCount);
5798
5799             long eventTime = q.mEvent.getEventTimeNano();
5800             long oldestEventTime = eventTime;
5801             if (q.mEvent instanceof MotionEvent) {
5802                 MotionEvent me = (MotionEvent)q.mEvent;
5803                 if (me.getHistorySize() > 0) {
5804                     oldestEventTime = me.getHistoricalEventTimeNano(0);
5805                 }
5806             }
5807             mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);
5808
5809             deliverInputEvent(q);
5810         }
5811
5812         // We are done processing all input events that we can process right now
5813         // so we can clear the pending flag immediately.
5814         if (mProcessInputEventsScheduled) {
5815             mProcessInputEventsScheduled = false;
5816             mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
5817         }
5818     }
5819
5820     private void deliverInputEvent(QueuedInputEvent q) {
5821         Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5822                 q.mEvent.getSequenceNumber());
5823         if (mInputEventConsistencyVerifier != null) {
5824             mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
5825         }
5826
5827         InputStage stage;
5828         if (q.shouldSendToSynthesizer()) {
5829             stage = mSyntheticInputStage;
5830         } else {
5831             stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
5832         }
5833
5834         if (stage != null) {
5835             stage.deliver(q);
5836         } else {
5837             finishInputEvent(q);
5838         }
5839     }
5840
5841     private void finishInputEvent(QueuedInputEvent q) {
5842         Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5843                 q.mEvent.getSequenceNumber());
5844
5845         if (q.mReceiver != null) {
5846             boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
5847             q.mReceiver.finishInputEvent(q.mEvent, handled);
5848         } else {
5849             q.mEvent.recycleIfNeededAfterDispatch();
5850         }
5851
5852         recycleQueuedInputEvent(q);
5853     }
5854
5855     private void adjustInputEventForCompatibility(InputEvent e) {
5856         if (mTargetSdkVersion < Build.VERSION_CODES.MNC && e instanceof MotionEvent) {
5857             MotionEvent motion = (MotionEvent) e;
5858             final int mask =
5859                 MotionEvent.BUTTON_STYLUS_PRIMARY | MotionEvent.BUTTON_STYLUS_SECONDARY;
5860             final int buttonState = motion.getButtonState();
5861             final int compatButtonState = (buttonState & mask) >> 4;
5862             if (compatButtonState != 0) {
5863                 motion.setButtonState(buttonState | compatButtonState);
5864             }
5865         }
5866     }
5867
5868     static boolean isTerminalInputEvent(InputEvent event) {
5869         if (event instanceof KeyEvent) {
5870             final KeyEvent keyEvent = (KeyEvent)event;
5871             return keyEvent.getAction() == KeyEvent.ACTION_UP;
5872         } else {
5873             final MotionEvent motionEvent = (MotionEvent)event;
5874             final int action = motionEvent.getAction();
5875             return action == MotionEvent.ACTION_UP
5876                     || action == MotionEvent.ACTION_CANCEL
5877                     || action == MotionEvent.ACTION_HOVER_EXIT;
5878         }
5879     }
5880
5881     void scheduleConsumeBatchedInput() {
5882         if (!mConsumeBatchedInputScheduled) {
5883             mConsumeBatchedInputScheduled = true;
5884             mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
5885                     mConsumedBatchedInputRunnable, null);
5886         }
5887     }
5888
5889     void unscheduleConsumeBatchedInput() {
5890         if (mConsumeBatchedInputScheduled) {
5891             mConsumeBatchedInputScheduled = false;
5892             mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
5893                     mConsumedBatchedInputRunnable, null);
5894         }
5895     }
5896
5897     void scheduleConsumeBatchedInputImmediately() {
5898         if (!mConsumeBatchedInputImmediatelyScheduled) {
5899             unscheduleConsumeBatchedInput();
5900             mConsumeBatchedInputImmediatelyScheduled = true;
5901             mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
5902         }
5903     }
5904
5905     void doConsumeBatchedInput(long frameTimeNanos) {
5906         if (mConsumeBatchedInputScheduled) {
5907             mConsumeBatchedInputScheduled = false;
5908             if (mInputEventReceiver != null) {
5909                 if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
5910                         && frameTimeNanos != -1) {
5911                     // If we consumed a batch here, we want to go ahead and schedule the
5912                     // consumption of batched input events on the next frame. Otherwise, we would
5913                     // wait until we have more input events pending and might get starved by other
5914                     // things occurring in the process. If the frame time is -1, however, then
5915                     // we're in a non-batching mode, so there's no need to schedule this.
5916                     scheduleConsumeBatchedInput();
5917                 }
5918             }
5919             doProcessInputEvents();
5920         }
5921     }
5922
5923     final class TraversalRunnable implements Runnable {
5924         @Override
5925         public void run() {
5926             doTraversal();
5927         }
5928     }
5929     final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
5930
5931     final class WindowInputEventReceiver extends InputEventReceiver {
5932         public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
5933             super(inputChannel, looper);
5934         }
5935
5936         @Override
5937         public void onInputEvent(InputEvent event) {
5938             enqueueInputEvent(event, this, 0, true);
5939         }
5940
5941         @Override
5942         public void onBatchedInputEventPending() {
5943             if (mUnbufferedInputDispatch) {
5944                 super.onBatchedInputEventPending();
5945             } else {
5946                 scheduleConsumeBatchedInput();
5947             }
5948         }
5949
5950         @Override
5951         public void dispose() {
5952             unscheduleConsumeBatchedInput();
5953             super.dispose();
5954         }
5955     }
5956     WindowInputEventReceiver mInputEventReceiver;
5957
5958     final class ConsumeBatchedInputRunnable implements Runnable {
5959         @Override
5960         public void run() {
5961             doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
5962         }
5963     }
5964     final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
5965             new ConsumeBatchedInputRunnable();
5966     boolean mConsumeBatchedInputScheduled;
5967
5968     final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
5969         @Override
5970         public void run() {
5971             doConsumeBatchedInput(-1);
5972         }
5973     }
5974     final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
5975             new ConsumeBatchedInputImmediatelyRunnable();
5976     boolean mConsumeBatchedInputImmediatelyScheduled;
5977
5978     final class InvalidateOnAnimationRunnable implements Runnable {
5979         private boolean mPosted;
5980         private final ArrayList<View> mViews = new ArrayList<View>();
5981         private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
5982                 new ArrayList<AttachInfo.InvalidateInfo>();
5983         private View[] mTempViews;
5984         private AttachInfo.InvalidateInfo[] mTempViewRects;
5985
5986         public void addView(View view) {
5987             synchronized (this) {
5988                 mViews.add(view);
5989                 postIfNeededLocked();
5990             }
5991         }
5992
5993         public void addViewRect(AttachInfo.InvalidateInfo info) {
5994             synchronized (this) {
5995                 mViewRects.add(info);
5996                 postIfNeededLocked();
5997             }
5998         }
5999
6000         public void removeView(View view) {
6001             synchronized (this) {
6002                 mViews.remove(view);
6003
6004                 for (int i = mViewRects.size(); i-- > 0; ) {
6005                     AttachInfo.InvalidateInfo info = mViewRects.get(i);
6006                     if (info.target == view) {
6007                         mViewRects.remove(i);
6008                         info.recycle();
6009                     }
6010                 }
6011
6012                 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
6013                     mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
6014                     mPosted = false;
6015                 }
6016             }
6017         }
6018
6019         @Override
6020         public void run() {
6021             final int viewCount;
6022             final int viewRectCount;
6023             synchronized (this) {
6024                 mPosted = false;
6025
6026                 viewCount = mViews.size();
6027                 if (viewCount != 0) {
6028                     mTempViews = mViews.toArray(mTempViews != null
6029                             ? mTempViews : new View[viewCount]);
6030                     mViews.clear();
6031                 }
6032
6033                 viewRectCount = mViewRects.size();
6034                 if (viewRectCount != 0) {
6035                     mTempViewRects = mViewRects.toArray(mTempViewRects != null
6036                             ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6037                     mViewRects.clear();
6038                 }
6039             }
6040
6041             for (int i = 0; i < viewCount; i++) {
6042                 mTempViews[i].invalidate();
6043                 mTempViews[i] = null;
6044             }
6045
6046             for (int i = 0; i < viewRectCount; i++) {
6047                 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
6048                 info.target.invalidate(info.left, info.top, info.right, info.bottom);
6049                 info.recycle();
6050             }
6051         }
6052
6053         private void postIfNeededLocked() {
6054             if (!mPosted) {
6055                 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
6056                 mPosted = true;
6057             }
6058         }
6059     }
6060     final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6061             new InvalidateOnAnimationRunnable();
6062
6063     public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6064         Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6065         mHandler.sendMessageDelayed(msg, delayMilliseconds);
6066     }
6067
6068     public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
6069             long delayMilliseconds) {
6070         final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
6071         mHandler.sendMessageDelayed(msg, delayMilliseconds);
6072     }
6073
6074     public void dispatchInvalidateOnAnimation(View view) {
6075         mInvalidateOnAnimationRunnable.addView(view);
6076     }
6077
6078     public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6079         mInvalidateOnAnimationRunnable.addViewRect(info);
6080     }
6081
6082     public void cancelInvalidate(View view) {
6083         mHandler.removeMessages(MSG_INVALIDATE, view);
6084         // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6085         // them to the pool
6086         mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6087         mInvalidateOnAnimationRunnable.removeView(view);
6088     }
6089
6090     public void dispatchInputEvent(InputEvent event) {
6091         dispatchInputEvent(event, null);
6092     }
6093
6094     public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6095         SomeArgs args = SomeArgs.obtain();
6096         args.arg1 = event;
6097         args.arg2 = receiver;
6098         Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
6099         msg.setAsynchronous(true);
6100         mHandler.sendMessage(msg);
6101     }
6102
6103     public void synthesizeInputEvent(InputEvent event) {
6104         Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6105         msg.setAsynchronous(true);
6106         mHandler.sendMessage(msg);
6107     }
6108
6109     public void dispatchKeyFromIme(KeyEvent event) {
6110         Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
6111         msg.setAsynchronous(true);
6112         mHandler.sendMessage(msg);
6113     }
6114
6115     /**
6116      * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6117      *
6118      * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6119      * passes in.
6120      */
6121     public void dispatchUnhandledInputEvent(InputEvent event) {
6122         if (event instanceof MotionEvent) {
6123             event = MotionEvent.obtain((MotionEvent) event);
6124         }
6125         synthesizeInputEvent(event);
6126     }
6127
6128     public void dispatchAppVisibility(boolean visible) {
6129         Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
6130         msg.arg1 = visible ? 1 : 0;
6131         mHandler.sendMessage(msg);
6132     }
6133
6134     public void dispatchGetNewSurface() {
6135         Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6136         mHandler.sendMessage(msg);
6137     }
6138
6139     public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6140         Message msg = Message.obtain();
6141         msg.what = MSG_WINDOW_FOCUS_CHANGED;
6142         msg.arg1 = hasFocus ? 1 : 0;
6143         msg.arg2 = inTouchMode ? 1 : 0;
6144         mHandler.sendMessage(msg);
6145     }
6146
6147     public void dispatchWindowShown() {
6148         mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6149     }
6150
6151     public void dispatchCloseSystemDialogs(String reason) {
6152         Message msg = Message.obtain();
6153         msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
6154         msg.obj = reason;
6155         mHandler.sendMessage(msg);
6156     }
6157
6158     public void dispatchDragEvent(DragEvent event) {
6159         final int what;
6160         if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
6161             what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6162             mHandler.removeMessages(what);
6163         } else {
6164             what = MSG_DISPATCH_DRAG_EVENT;
6165         }
6166         Message msg = mHandler.obtainMessage(what, event);
6167         mHandler.sendMessage(msg);
6168     }
6169
6170     public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6171             int localValue, int localChanges) {
6172         SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6173         args.seq = seq;
6174         args.globalVisibility = globalVisibility;
6175         args.localValue = localValue;
6176         args.localChanges = localChanges;
6177         mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6178     }
6179
6180     public void dispatchDoneAnimating() {
6181         mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
6182     }
6183
6184     public void dispatchCheckFocus() {
6185         if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
6186             // This will result in a call to checkFocus() below.
6187             mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
6188         }
6189     }
6190
6191     /**
6192      * Post a callback to send a
6193      * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6194      * This event is send at most once every
6195      * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
6196      */
6197     private void postSendWindowContentChangedCallback(View source, int changeType) {
6198         if (mSendWindowContentChangedAccessibilityEvent == null) {
6199             mSendWindowContentChangedAccessibilityEvent =
6200                 new SendWindowContentChangedAccessibilityEvent();
6201         }
6202         mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
6203     }
6204
6205     /**
6206      * Remove a posted callback to send a
6207      * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6208      */
6209     private void removeSendWindowContentChangedCallback() {
6210         if (mSendWindowContentChangedAccessibilityEvent != null) {
6211             mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
6212         }
6213     }
6214
6215     @Override
6216     public boolean showContextMenuForChild(View originalView) {
6217         return false;
6218     }
6219
6220     @Override
6221     public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6222         return null;
6223     }
6224
6225     @Override
6226     public ActionMode startActionModeForChild(
6227             View originalView, ActionMode.Callback callback, int type) {
6228         return null;
6229     }
6230
6231     @Override
6232     public void createContextMenu(ContextMenu menu) {
6233     }
6234
6235     @Override
6236     public void childDrawableStateChanged(View child) {
6237     }
6238
6239     @Override
6240     public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
6241         if (mView == null) {
6242             return false;
6243         }
6244         // Intercept accessibility focus events fired by virtual nodes to keep
6245         // track of accessibility focus position in such nodes.
6246         final int eventType = event.getEventType();
6247         switch (eventType) {
6248             case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
6249                 final long sourceNodeId = event.getSourceNodeId();
6250                 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6251                         sourceNodeId);
6252                 View source = mView.findViewByAccessibilityId(accessibilityViewId);
6253                 if (source != null) {
6254                     AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6255                     if (provider != null) {
6256                         final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
6257                                 sourceNodeId);
6258                         final AccessibilityNodeInfo node;
6259                         if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6260                             node = provider.createAccessibilityNodeInfo(
6261                                     AccessibilityNodeProvider.HOST_VIEW_ID);
6262                         } else {
6263                             node = provider.createAccessibilityNodeInfo(virtualNodeId);
6264                         }
6265                         setAccessibilityFocus(source, node);
6266                     }
6267                 }
6268             } break;
6269             case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
6270                 final long sourceNodeId = event.getSourceNodeId();
6271                 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6272                         sourceNodeId);
6273                 View source = mView.findViewByAccessibilityId(accessibilityViewId);
6274                 if (source != null) {
6275                     AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6276                     if (provider != null) {
6277                         setAccessibilityFocus(null, null);
6278                     }
6279                 }
6280             } break;
6281
6282
6283             case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
6284                 handleWindowContentChangedEvent(event);
6285             } break;
6286         }
6287         mAccessibilityManager.sendAccessibilityEvent(event);
6288         return true;
6289     }
6290
6291     /**
6292      * Updates the focused virtual view, when necessary, in response to a
6293      * content changed event.
6294      * <p>
6295      * This is necessary to get updated bounds after a position change.
6296      *
6297      * @param event an accessibility event of type
6298      *              {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
6299      */
6300     private void handleWindowContentChangedEvent(AccessibilityEvent event) {
6301         // No virtual view focused, nothing to do here.
6302         if (mAccessibilityFocusedHost == null || mAccessibilityFocusedVirtualView == null) {
6303             return;
6304         }
6305
6306         // If we have a node but no provider, abort.
6307         final AccessibilityNodeProvider provider =
6308                 mAccessibilityFocusedHost.getAccessibilityNodeProvider();
6309         if (provider == null) {
6310             // TODO: Should we clear the focused virtual view?
6311             return;
6312         }
6313
6314         // We only care about change types that may affect the bounds of the
6315         // focused virtual view.
6316         final int changes = event.getContentChangeTypes();
6317         if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) == 0
6318                 && changes != AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
6319             return;
6320         }
6321
6322         final long eventSourceNodeId = event.getSourceNodeId();
6323         final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId);
6324
6325         // Search up the tree for subtree containment.
6326         boolean hostInSubtree = false;
6327         View root = mAccessibilityFocusedHost;
6328         while (root != null && !hostInSubtree) {
6329             if (changedViewId == root.getAccessibilityViewId()) {
6330                 hostInSubtree = true;
6331             } else {
6332                 final ViewParent parent = root.getParent();
6333                 if (parent instanceof View) {
6334                     root = (View) parent;
6335                 } else {
6336                     root = null;
6337                 }
6338             }
6339         }
6340
6341         // We care only about changes in subtrees containing the host view.
6342         if (!hostInSubtree) {
6343             return;
6344         }
6345
6346         final long focusedSourceNodeId = mAccessibilityFocusedVirtualView.getSourceNodeId();
6347         int focusedChildId = AccessibilityNodeInfo.getVirtualDescendantId(focusedSourceNodeId);
6348         if (focusedChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6349             // TODO: Should we clear the focused virtual view?
6350             focusedChildId = AccessibilityNodeProvider.HOST_VIEW_ID;
6351         }
6352
6353         // Refresh the node for the focused virtual view.
6354         mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId);
6355     }
6356
6357     @Override
6358     public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6359         postSendWindowContentChangedCallback(source, changeType);
6360     }
6361
6362     @Override
6363     public boolean canResolveLayoutDirection() {
6364         return true;
6365     }
6366
6367     @Override
6368     public boolean isLayoutDirectionResolved() {
6369         return true;
6370     }
6371
6372     @Override
6373     public int getLayoutDirection() {
6374         return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6375     }
6376
6377     @Override
6378     public boolean canResolveTextDirection() {
6379         return true;
6380     }
6381
6382     @Override
6383     public boolean isTextDirectionResolved() {
6384         return true;
6385     }
6386
6387     @Override
6388     public int getTextDirection() {
6389         return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6390     }
6391
6392     @Override
6393     public boolean canResolveTextAlignment() {
6394         return true;
6395     }
6396
6397     @Override
6398     public boolean isTextAlignmentResolved() {
6399         return true;
6400     }
6401
6402     @Override
6403     public int getTextAlignment() {
6404         return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6405     }
6406
6407     private View getCommonPredecessor(View first, View second) {
6408         if (mTempHashSet == null) {
6409             mTempHashSet = new HashSet<View>();
6410         }
6411         HashSet<View> seen = mTempHashSet;
6412         seen.clear();
6413         View firstCurrent = first;
6414         while (firstCurrent != null) {
6415             seen.add(firstCurrent);
6416             ViewParent firstCurrentParent = firstCurrent.mParent;
6417             if (firstCurrentParent instanceof View) {
6418                 firstCurrent = (View) firstCurrentParent;
6419             } else {
6420                 firstCurrent = null;
6421             }
6422         }
6423         View secondCurrent = second;
6424         while (secondCurrent != null) {
6425             if (seen.contains(secondCurrent)) {
6426                 seen.clear();
6427                 return secondCurrent;
6428             }
6429             ViewParent secondCurrentParent = secondCurrent.mParent;
6430             if (secondCurrentParent instanceof View) {
6431                 secondCurrent = (View) secondCurrentParent;
6432             } else {
6433                 secondCurrent = null;
6434             }
6435         }
6436         seen.clear();
6437         return null;
6438     }
6439
6440     void checkThread() {
6441         if (mThread != Thread.currentThread()) {
6442             throw new CalledFromWrongThreadException(
6443                     "Only the original thread that created a view hierarchy can touch its views.");
6444         }
6445     }
6446
6447     @Override
6448     public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
6449         // ViewAncestor never intercepts touch event, so this can be a no-op
6450     }
6451
6452     @Override
6453     public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
6454         final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
6455         if (rectangle != null) {
6456             mTempRect.set(rectangle);
6457             mTempRect.offset(0, -mCurScrollY);
6458             mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6459             try {
6460                 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6461             } catch (RemoteException re) {
6462                 /* ignore */
6463             }
6464         }
6465         return scrolled;
6466     }
6467
6468     @Override
6469     public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6470         // Do nothing.
6471     }
6472
6473     @Override
6474     public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6475         return false;
6476     }
6477
6478     @Override
6479     public void onStopNestedScroll(View target) {
6480     }
6481
6482     @Override
6483     public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6484     }
6485
6486     @Override
6487     public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6488             int dxUnconsumed, int dyUnconsumed) {
6489     }
6490
6491     @Override
6492     public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6493     }
6494
6495     @Override
6496     public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6497         return false;
6498     }
6499
6500     @Override
6501     public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6502         return false;
6503     }
6504
6505     @Override
6506     public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6507         return false;
6508     }
6509
6510     void changeCanvasOpacity(boolean opaque) {
6511         Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque);
6512         if (mAttachInfo.mHardwareRenderer != null) {
6513             mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6514         }
6515     }
6516
6517     class TakenSurfaceHolder extends BaseSurfaceHolder {
6518         @Override
6519         public boolean onAllowLockCanvas() {
6520             return mDrawingAllowed;
6521         }
6522
6523         @Override
6524         public void onRelayoutContainer() {
6525             // Not currently interesting -- from changing between fixed and layout size.
6526         }
6527
6528         @Override
6529         public void setFormat(int format) {
6530             ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6531         }
6532
6533         @Override
6534         public void setType(int type) {
6535             ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6536         }
6537
6538         @Override
6539         public void onUpdateSurface() {
6540             // We take care of format and type changes on our own.
6541             throw new IllegalStateException("Shouldn't be here");
6542         }
6543
6544         @Override
6545         public boolean isCreating() {
6546             return mIsCreating;
6547         }
6548
6549         @Override
6550         public void setFixedSize(int width, int height) {
6551             throw new UnsupportedOperationException(
6552                     "Currently only support sizing from layout");
6553         }
6554
6555         @Override
6556         public void setKeepScreenOn(boolean screenOn) {
6557             ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6558         }
6559     }
6560
6561     static class W extends IWindow.Stub {
6562         private final WeakReference<ViewRootImpl> mViewAncestor;
6563         private final IWindowSession mWindowSession;
6564
6565         W(ViewRootImpl viewAncestor) {
6566             mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
6567             mWindowSession = viewAncestor.mWindowSession;
6568         }
6569
6570         @Override
6571         public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
6572                 Rect visibleInsets, Rect stableInsets, boolean reportDraw,
6573                 Configuration newConfig) {
6574             final ViewRootImpl viewAncestor = mViewAncestor.get();
6575             if (viewAncestor != null) {
6576                 viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
6577                         visibleInsets, stableInsets, reportDraw, newConfig);
6578             }
6579         }
6580
6581         @Override
6582         public void moved(int newX, int newY) {
6583             final ViewRootImpl viewAncestor = mViewAncestor.get();
6584             if (viewAncestor != null) {
6585                 viewAncestor.dispatchMoved(newX, newY);
6586             }
6587         }
6588
6589         @Override
6590         public void dispatchAppVisibility(boolean visible) {
6591             final ViewRootImpl viewAncestor = mViewAncestor.get();
6592             if (viewAncestor != null) {
6593                 viewAncestor.dispatchAppVisibility(visible);
6594             }
6595         }
6596
6597         @Override
6598         public void dispatchGetNewSurface() {
6599             final ViewRootImpl viewAncestor = mViewAncestor.get();
6600             if (viewAncestor != null) {
6601                 viewAncestor.dispatchGetNewSurface();
6602             }
6603         }
6604
6605         @Override
6606         public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6607             final ViewRootImpl viewAncestor = mViewAncestor.get();
6608             if (viewAncestor != null) {
6609                 viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
6610             }
6611         }
6612
6613         private static int checkCallingPermission(String permission) {
6614             try {
6615                 return ActivityManagerNative.getDefault().checkPermission(
6616                         permission, Binder.getCallingPid(), Binder.getCallingUid());
6617             } catch (RemoteException e) {
6618                 return PackageManager.PERMISSION_DENIED;
6619             }
6620         }
6621
6622         @Override
6623         public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
6624             final ViewRootImpl viewAncestor = mViewAncestor.get();
6625             if (viewAncestor != null) {
6626                 final View view = viewAncestor.mView;
6627                 if (view != null) {
6628                     if (checkCallingPermission(Manifest.permission.DUMP) !=
6629                             PackageManager.PERMISSION_GRANTED) {
6630                         throw new SecurityException("Insufficient permissions to invoke"
6631                                 + " executeCommand() from pid=" + Binder.getCallingPid()
6632                                 + ", uid=" + Binder.getCallingUid());
6633                     }
6634
6635                     OutputStream clientStream = null;
6636                     try {
6637                         clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
6638                         ViewDebug.dispatchCommand(view, command, parameters, clientStream);
6639                     } catch (IOException e) {
6640                         e.printStackTrace();
6641                     } finally {
6642                         if (clientStream != null) {
6643                             try {
6644                                 clientStream.close();
6645                             } catch (IOException e) {
6646                                 e.printStackTrace();
6647                             }
6648                         }
6649                     }
6650                 }
6651             }
6652         }
6653
6654         @Override
6655         public void closeSystemDialogs(String reason) {
6656             final ViewRootImpl viewAncestor = mViewAncestor.get();
6657             if (viewAncestor != null) {
6658                 viewAncestor.dispatchCloseSystemDialogs(reason);
6659             }
6660         }
6661
6662         @Override
6663         public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
6664                 boolean sync) {
6665             if (sync) {
6666                 try {
6667                     mWindowSession.wallpaperOffsetsComplete(asBinder());
6668                 } catch (RemoteException e) {
6669                 }
6670             }
6671         }
6672
6673         @Override
6674         public void dispatchWallpaperCommand(String action, int x, int y,
6675                 int z, Bundle extras, boolean sync) {
6676             if (sync) {
6677                 try {
6678                     mWindowSession.wallpaperCommandComplete(asBinder(), null);
6679                 } catch (RemoteException e) {
6680                 }
6681             }
6682         }
6683
6684         /* Drag/drop */
6685         @Override
6686         public void dispatchDragEvent(DragEvent event) {
6687             final ViewRootImpl viewAncestor = mViewAncestor.get();
6688             if (viewAncestor != null) {
6689                 viewAncestor.dispatchDragEvent(event);
6690             }
6691         }
6692
6693         @Override
6694         public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6695                 int localValue, int localChanges) {
6696             final ViewRootImpl viewAncestor = mViewAncestor.get();
6697             if (viewAncestor != null) {
6698                 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
6699                         localValue, localChanges);
6700             }
6701         }
6702
6703         @Override
6704         public void doneAnimating() {
6705             final ViewRootImpl viewAncestor = mViewAncestor.get();
6706             if (viewAncestor != null) {
6707                 viewAncestor.dispatchDoneAnimating();
6708             }
6709         }
6710
6711         @Override
6712         public void dispatchWindowShown() {
6713             final ViewRootImpl viewAncestor = mViewAncestor.get();
6714             if (viewAncestor != null) {
6715                 viewAncestor.dispatchWindowShown();
6716             }
6717         }
6718     }
6719
6720     public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
6721         public CalledFromWrongThreadException(String msg) {
6722             super(msg);
6723         }
6724     }
6725
6726     static RunQueue getRunQueue() {
6727         RunQueue rq = sRunQueues.get();
6728         if (rq != null) {
6729             return rq;
6730         }
6731         rq = new RunQueue();
6732         sRunQueues.set(rq);
6733         return rq;
6734     }
6735
6736     /**
6737      * The run queue is used to enqueue pending work from Views when no Handler is
6738      * attached.  The work is executed during the next call to performTraversals on
6739      * the thread.
6740      * @hide
6741      */
6742     static final class RunQueue {
6743         private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
6744
6745         void post(Runnable action) {
6746             postDelayed(action, 0);
6747         }
6748
6749         void postDelayed(Runnable action, long delayMillis) {
6750             HandlerAction handlerAction = new HandlerAction();
6751             handlerAction.action = action;
6752             handlerAction.delay = delayMillis;
6753
6754             synchronized (mActions) {
6755                 mActions.add(handlerAction);
6756             }
6757         }
6758
6759         void removeCallbacks(Runnable action) {
6760             final HandlerAction handlerAction = new HandlerAction();
6761             handlerAction.action = action;
6762
6763             synchronized (mActions) {
6764                 final ArrayList<HandlerAction> actions = mActions;
6765
6766                 while (actions.remove(handlerAction)) {
6767                     // Keep going
6768                 }
6769             }
6770         }
6771
6772         void executeActions(Handler handler) {
6773             synchronized (mActions) {
6774                 final ArrayList<HandlerAction> actions = mActions;
6775                 final int count = actions.size();
6776
6777                 for (int i = 0; i < count; i++) {
6778                     final HandlerAction handlerAction = actions.get(i);
6779                     handler.postDelayed(handlerAction.action, handlerAction.delay);
6780                 }
6781
6782                 actions.clear();
6783             }
6784         }
6785
6786         private static class HandlerAction {
6787             Runnable action;
6788             long delay;
6789
6790             @Override
6791             public boolean equals(Object o) {
6792                 if (this == o) return true;
6793                 if (o == null || getClass() != o.getClass()) return false;
6794
6795                 HandlerAction that = (HandlerAction) o;
6796                 return !(action != null ? !action.equals(that.action) : that.action != null);
6797
6798             }
6799
6800             @Override
6801             public int hashCode() {
6802                 int result = action != null ? action.hashCode() : 0;
6803                 result = 31 * result + (int) (delay ^ (delay >>> 32));
6804                 return result;
6805             }
6806         }
6807     }
6808
6809     /**
6810      * Class for managing the accessibility interaction connection
6811      * based on the global accessibility state.
6812      */
6813     final class AccessibilityInteractionConnectionManager
6814             implements AccessibilityStateChangeListener {
6815         @Override
6816         public void onAccessibilityStateChanged(boolean enabled) {
6817             if (enabled) {
6818                 ensureConnection();
6819                 if (mAttachInfo.mHasWindowFocus) {
6820                     mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
6821                     View focusedView = mView.findFocus();
6822                     if (focusedView != null && focusedView != mView) {
6823                         focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6824                     }
6825                 }
6826             } else {
6827                 ensureNoConnection();
6828                 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
6829             }
6830         }
6831
6832         public void ensureConnection() {
6833             final boolean registered =
6834                     mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6835             if (!registered) {
6836                 mAttachInfo.mAccessibilityWindowId =
6837                         mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
6838                                 new AccessibilityInteractionConnection(ViewRootImpl.this));
6839             }
6840         }
6841
6842         public void ensureNoConnection() {
6843             final boolean registered =
6844                 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6845             if (registered) {
6846                 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6847                 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
6848             }
6849         }
6850     }
6851
6852     final class HighContrastTextManager implements HighTextContrastChangeListener {
6853         HighContrastTextManager() {
6854             mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
6855         }
6856         @Override
6857         public void onHighTextContrastStateChanged(boolean enabled) {
6858             mAttachInfo.mHighContrastText = enabled;
6859
6860             // Destroy Displaylists so they can be recreated with high contrast recordings
6861             destroyHardwareResources();
6862
6863             // Schedule redraw, which will rerecord + redraw all text
6864             invalidate();
6865         }
6866     }
6867
6868     /**
6869      * This class is an interface this ViewAncestor provides to the
6870      * AccessibilityManagerService to the latter can interact with
6871      * the view hierarchy in this ViewAncestor.
6872      */
6873     static final class AccessibilityInteractionConnection
6874             extends IAccessibilityInteractionConnection.Stub {
6875         private final WeakReference<ViewRootImpl> mViewRootImpl;
6876
6877         AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
6878             mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
6879         }
6880
6881         @Override
6882         public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
6883                 Region interactiveRegion, int interactionId,
6884                 IAccessibilityInteractionConnectionCallback callback, int flags,
6885                 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6886             ViewRootImpl viewRootImpl = mViewRootImpl.get();
6887             if (viewRootImpl != null && viewRootImpl.mView != null) {
6888                 viewRootImpl.getAccessibilityInteractionController()
6889                     .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
6890                             interactiveRegion, interactionId, callback, flags, interrogatingPid,
6891                             interrogatingTid, spec);
6892             } else {
6893                 // We cannot make the call and notify the caller so it does not wait.
6894                 try {
6895                     callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6896                 } catch (RemoteException re) {
6897                     /* best effort - ignore */
6898                 }
6899             }
6900         }
6901
6902         @Override
6903         public void performAccessibilityAction(long accessibilityNodeId, int action,
6904                 Bundle arguments, int interactionId,
6905                 IAccessibilityInteractionConnectionCallback callback, int flags,
6906                 int interrogatingPid, long interrogatingTid) {
6907             ViewRootImpl viewRootImpl = mViewRootImpl.get();
6908             if (viewRootImpl != null && viewRootImpl.mView != null) {
6909                 viewRootImpl.getAccessibilityInteractionController()
6910                     .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
6911                             interactionId, callback, flags, interrogatingPid, interrogatingTid);
6912             } else {
6913                 // We cannot make the call and notify the caller so it does not wait.
6914                 try {
6915                     callback.setPerformAccessibilityActionResult(false, interactionId);
6916                 } catch (RemoteException re) {
6917                     /* best effort - ignore */
6918                 }
6919             }
6920         }
6921
6922         @Override
6923         public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
6924                 String viewId, Region interactiveRegion, int interactionId,
6925                 IAccessibilityInteractionConnectionCallback callback, int flags,
6926                 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6927             ViewRootImpl viewRootImpl = mViewRootImpl.get();
6928             if (viewRootImpl != null && viewRootImpl.mView != null) {
6929                 viewRootImpl.getAccessibilityInteractionController()
6930                     .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
6931                             viewId, interactiveRegion, interactionId, callback, flags,
6932                             interrogatingPid, interrogatingTid, spec);
6933             } else {
6934                 // We cannot make the call and notify the caller so it does not wait.
6935                 try {
6936                     callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6937                 } catch (RemoteException re) {
6938                     /* best effort - ignore */
6939                 }
6940             }
6941         }
6942
6943         @Override
6944         public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
6945                 Region interactiveRegion, int interactionId,
6946                 IAccessibilityInteractionConnectionCallback callback, int flags,
6947                 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6948             ViewRootImpl viewRootImpl = mViewRootImpl.get();
6949             if (viewRootImpl != null && viewRootImpl.mView != null) {
6950                 viewRootImpl.getAccessibilityInteractionController()
6951                     .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
6952                             interactiveRegion, interactionId, callback, flags, interrogatingPid,
6953                             interrogatingTid, spec);
6954             } else {
6955                 // We cannot make the call and notify the caller so it does not wait.
6956                 try {
6957                     callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6958                 } catch (RemoteException re) {
6959                     /* best effort - ignore */
6960                 }
6961             }
6962         }
6963
6964         @Override
6965         public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
6966                 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6967                 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6968             ViewRootImpl viewRootImpl = mViewRootImpl.get();
6969             if (viewRootImpl != null && viewRootImpl.mView != null) {
6970                 viewRootImpl.getAccessibilityInteractionController()
6971                     .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
6972                             interactionId, callback, flags, interrogatingPid, interrogatingTid,
6973                             spec);
6974             } else {
6975                 // We cannot make the call and notify the caller so it does not wait.
6976                 try {
6977                     callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6978                 } catch (RemoteException re) {
6979                     /* best effort - ignore */
6980                 }
6981             }
6982         }
6983
6984         @Override
6985         public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
6986                 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
6987                 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
6988             ViewRootImpl viewRootImpl = mViewRootImpl.get();
6989             if (viewRootImpl != null && viewRootImpl.mView != null) {
6990                 viewRootImpl.getAccessibilityInteractionController()
6991                     .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
6992                             interactionId, callback, flags, interrogatingPid, interrogatingTid,
6993                             spec);
6994             } else {
6995                 // We cannot make the call and notify the caller so it does not wait.
6996                 try {
6997                     callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6998                 } catch (RemoteException re) {
6999                     /* best effort - ignore */
7000                 }
7001             }
7002         }
7003     }
7004
7005     private class SendWindowContentChangedAccessibilityEvent implements Runnable {
7006         private int mChangeTypes = 0;
7007
7008         public View mSource;
7009         public long mLastEventTimeMillis;
7010
7011         @Override
7012         public void run() {
7013             // The accessibility may be turned off while we were waiting so check again.
7014             if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7015                 mLastEventTimeMillis = SystemClock.uptimeMillis();
7016                 AccessibilityEvent event = AccessibilityEvent.obtain();
7017                 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
7018                 event.setContentChangeTypes(mChangeTypes);
7019                 mSource.sendAccessibilityEventUnchecked(event);
7020             } else {
7021                 mLastEventTimeMillis = 0;
7022             }
7023             // In any case reset to initial state.
7024             mSource.resetSubtreeAccessibilityStateChanged();
7025             mSource = null;
7026             mChangeTypes = 0;
7027         }
7028
7029         public void runOrPost(View source, int changeType) {
7030             if (mSource != null) {
7031                 // If there is no common predecessor, then mSource points to
7032                 // a removed view, hence in this case always prefer the source.
7033                 View predecessor = getCommonPredecessor(mSource, source);
7034                 mSource = (predecessor != null) ? predecessor : source;
7035                 mChangeTypes |= changeType;
7036                 return;
7037             }
7038             mSource = source;
7039             mChangeTypes = changeType;
7040             final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
7041             final long minEventIntevalMillis =
7042                     ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
7043             if (timeSinceLastMillis >= minEventIntevalMillis) {
7044                 mSource.removeCallbacks(this);
7045                 run();
7046             } else {
7047                 mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
7048             }
7049         }
7050     }
7051 }