2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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;
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;
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;
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}.
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;
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.
121 private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering";
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";
129 * Maximum time we allow the user to roll the trackball enough to generate
130 * a key event, before resetting the counters.
132 static final int MAX_TRACKBALL_DELAY = 250;
134 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
136 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
137 static boolean sFirstDrawComplete = false;
139 static final ArrayList<ComponentCallbacks> sConfigCallbacks
140 = new ArrayList<ComponentCallbacks>();
142 final Context mContext;
143 final IWindowSession mWindowSession;
144 final Display mDisplay;
145 final DisplayManager mDisplayManager;
146 final String mBasePackageName;
148 final int[] mTmpLocation = new int[2];
150 final TypedValue mTmpValue = new TypedValue();
152 final Thread mThread;
154 final WindowLeaked mLocation;
156 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
160 final int mTargetSdkVersion;
166 View mAccessibilityFocusedHost;
167 AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
170 boolean mAppVisible = true;
171 int mOrigWindowType = -1;
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;
177 boolean mLastInCompatMode = false;
179 SurfaceHolder.Callback2 mSurfaceHolderCallback;
180 BaseSurfaceHolder mSurfaceHolder;
182 boolean mDrawingAllowed;
184 final Region mTransparentRegion;
185 final Region mPreviousTransparentRegion;
190 boolean mIsAnimating;
192 CompatibilityInfo.Translator mTranslator;
194 final View.AttachInfo mAttachInfo;
195 InputChannel mInputChannel;
196 InputQueue.Callback mInputQueueCallback;
197 InputQueue mInputQueue;
198 FallbackEventHandler mFallbackEventHandler;
199 Choreographer mChoreographer;
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.
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;
213 boolean mReportNextDraw;
214 boolean mFullRedrawNeeded;
215 boolean mNewSurfaceNeeded;
216 boolean mHasHadWindowFocus;
217 boolean mLastWasImTarget;
218 boolean mWindowsAnimating;
219 boolean mDrawDuringWindowsAnimating;
221 int mLastSystemUiVisibility;
222 int mClientWindowLayoutFlags;
223 boolean mLastOverscanRequested;
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;
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.
234 QueuedInputEvent mPendingInputEventHead;
235 QueuedInputEvent mPendingInputEventTail;
236 int mPendingInputEventCount;
237 boolean mProcessInputEventsScheduled;
238 boolean mUnbufferedInputDispatch;
239 String mPendingInputEventQueueLengthCounterName = "pq";
241 InputStage mFirstInputStage;
242 InputStage mFirstPostImeInputStage;
243 InputStage mSyntheticInputStage;
245 boolean mWindowAttributesChanged = false;
246 int mWindowAttributesChangesFlag = 0;
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();
253 boolean mAddedTouchMode;
255 final DisplayAdjustments mDisplayAdjustments;
257 // These are accessed by multiple threads.
258 final Rect mWinFrame; // frame given by window manager.
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();
267 final Rect mDispatchContentInsets = new Rect();
268 final Rect mDispatchStableInsets = new Rect();
270 private WindowInsets mLastWindowInsets;
272 final Configuration mLastConfiguration = new Configuration();
273 final Configuration mPendingConfiguration = new Configuration();
275 boolean mScrollMayChange;
277 WeakReference<View> mLastScrolledFocus;
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;
291 final ViewConfiguration mViewConfiguration;
294 ClipDescription mDragDescription;
295 View mCurrentDragView;
296 volatile Object mLocalDragState;
297 final PointF mDragPoint = new PointF();
298 final PointF mLastTouchPoint = new PointF();
300 private boolean mProfileRendering;
301 private Choreographer.FrameCallback mRenderProfiler;
302 private boolean mRenderProfilingEnabled;
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;
310 * see {@link #playSoundEffect(int)}
312 AudioManager mAudioManager;
314 final AccessibilityManager mAccessibilityManager;
316 AccessibilityInteractionController mAccessibilityInteractionController;
318 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
319 HighContrastTextManager mHighContrastTextManager;
321 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
323 HashSet<View> mTempHashSet;
325 private final int mDensity;
326 private final int mNoncompatDensity;
328 private boolean mInLayout = false;
329 ArrayList<View> mLayoutRequesters = new ArrayList<View>();
330 boolean mHandlingLayoutInLayoutRequest = false;
332 private int mViewLayoutDirectionInitial;
334 /** Set to true once doDie() has been called. */
335 private boolean mRemoved;
337 private final boolean mWindowIsRound;
340 * Consistency verifier for debugging purposes.
342 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
343 InputEventConsistencyVerifier.isInstrumentationEnabled() ?
344 new InputEventConsistencyVerifier(this, 0) : null;
346 static final class SystemUiVisibilityInfo {
348 int globalVisibility;
353 public ViewRootImpl(Context context, Display display) {
355 mWindowSession = WindowManagerGlobal.getWindowSession();
357 mBasePackageName = context.getBasePackageName();
359 mDisplayAdjustments = display.getDisplayAdjustments();
361 mThread = Thread.currentThread();
362 mLocation = new WindowLeaked(null);
363 mLocation.fillInStackTrace();
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
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());
396 public static void addFirstDrawHandler(Runnable callback) {
397 synchronized (sFirstDrawHandlers) {
398 if (!sFirstDrawComplete) {
399 sFirstDrawHandlers.add(callback);
404 public static void addConfigCallback(ComponentCallbacks callback) {
405 synchronized (sConfigCallbacks) {
406 sConfigCallbacks.add(callback);
410 // FIXME for perf testing only
411 private boolean mProfile = false;
414 * Call this to profile the next traversal call.
415 * FIXME for perf testing only. Remove eventually
417 public void profile() {
422 * Indicates whether we are in touch mode. Calling this method triggers an IPC
423 * call and should be avoided whenever possible.
425 * @return True, if the device is in touch mode, false otherwise.
429 static boolean isInTouchMode() {
430 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
431 if (windowSession != null) {
433 return windowSession.getInTouchMode();
434 } catch (RemoteException e) {
443 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
444 synchronized (this) {
448 mAttachInfo.mDisplayState = mDisplay.getState();
449 mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);
451 mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
452 mFallbackEventHandler.setView(view);
453 mWindowAttributes.copyFrom(attrs);
454 if (mWindowAttributes.packageName == null) {
455 mWindowAttributes.packageName = mBasePackageName;
457 attrs = mWindowAttributes;
458 // Keep track of the actual window flags supplied by the client.
459 mClientWindowLayoutFlags = attrs.flags;
461 setAccessibilityFocus(null, null);
463 if (view instanceof RootViewSurfaceTaker) {
464 mSurfaceHolderCallback =
465 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
466 if (mSurfaceHolderCallback != null) {
467 mSurfaceHolder = new TakenSurfaceHolder();
468 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
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);
479 CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
480 mTranslator = compatibilityInfo.getTranslator();
482 // If the application owns the surface, don't enable hardware acceleration
483 if (mSurfaceHolder == null) {
484 enableHardwareAcceleration(attrs);
487 boolean restore = false;
488 if (mTranslator != null) {
489 mSurface.setCompatibilityTranslator(mTranslator);
492 mTranslator.translateWindowLayout(attrs);
494 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
496 if (!compatibilityInfo.supportsScreen()) {
497 attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
498 mLastInCompatMode = true;
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();
513 int res; /* = WindowManagerImpl.ADD_OKAY; */
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.
519 if ((mWindowAttributes.inputFeatures
520 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
521 mInputChannel = new InputChannel();
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) {
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);
545 if (mTranslator != null) {
546 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
548 mPendingOverscanInsets.set(0, 0, 0, 0);
549 mPendingContentInsets.set(mAttachInfo.mContentInsets);
550 mPendingStableInsets.set(mAttachInfo.mStableInsets);
551 mPendingVisibleInsets.set(0, 0, 0, 0);
553 relayoutWindow(attrs, getHostVisibility(), false);
554 } catch (RemoteException e) {
555 if (DEBUG_LAYOUT) Log.e(TAG, "failed to relayoutWindow", e);
557 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
558 if (res < WindowManagerGlobal.ADD_OKAY) {
559 mAttachInfo.mRootView = null;
561 mFallbackEventHandler.setView(null);
562 unscheduleTraversals();
563 setAccessibilityFocus(null, null);
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
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.
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");
603 throw new RuntimeException(
604 "Unable to add window -- unknown error code " + res);
607 if (view instanceof RootViewSurfaceTaker) {
608 mInputQueueCallback =
609 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
611 if (mInputChannel != null) {
612 if (mInputQueueCallback != null) {
613 mInputQueue = new InputQueue();
614 mInputQueueCallback.onInputQueueCreated(mInputQueue);
616 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
620 view.assignParent(this);
621 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
622 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
624 if (mAccessibilityManager.isEnabled()) {
625 mAccessibilityInteractionConnectionManager.ensureConnection();
628 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
629 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
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);
645 mFirstInputStage = nativePreImeStage;
646 mFirstPostImeInputStage = earlyPostImeStage;
647 mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
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;
657 public CharSequence getTitle() {
658 return mWindowAttributes.getTitle();
661 void destroyHardwareResources() {
662 if (mAttachInfo.mHardwareRenderer != null) {
663 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
664 mAttachInfo.mHardwareRenderer.destroy();
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();
679 * Schedules the functor for execution in either kModeProcess or
680 * kModeProcessNoContext, depending on whether or not there is an EGLContext.
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
687 public void invokeFunctor(long functor, boolean waitForCompletion) {
688 ThreadedRenderer.invokeFunctor(functor, waitForCompletion);
691 public void registerAnimatingRenderNode(RenderNode animator) {
692 if (mAttachInfo.mHardwareRenderer != null) {
693 mAttachInfo.mHardwareRenderer.registerAnimatingRenderNode(animator);
695 if (mAttachInfo.mPendingAnimatingRenderNodes == null) {
696 mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>();
698 mAttachInfo.mPendingAnimatingRenderNodes.add(animator);
702 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
703 mAttachInfo.mHardwareAccelerated = false;
704 mAttachInfo.mHardwareAccelerationRequested = false;
706 // Don't enable hardware acceleration when the application is in compatibility mode
707 if (mTranslator != null) return;
709 // Try to enable hardware acceleration if requested
710 final boolean hardwareAccelerated =
711 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
713 if (hardwareAccelerated) {
714 if (!HardwareRenderer.isAvailable()) {
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.)
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;
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();
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;
757 public View getView() {
761 final WindowLeaked getLocation() {
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;
774 // Keep track of the actual window flags supplied by the client.
775 mClientWindowLayoutFlags = attrs.flags;
777 // Preserve compatible window flag if exists.
778 final int compatibleWindowFlag = mWindowAttributes.privateFlags
779 & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
781 // Transfer over system UI visibility values as they carry current state.
782 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
783 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
785 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
786 if ((mWindowAttributesChangesFlag
787 & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) {
788 // Recompute system ui visibility.
789 mAttachInfo.mRecomputeGlobalAttributes = true;
791 if (mWindowAttributes.packageName == null) {
792 mWindowAttributes.packageName = mBasePackageName;
794 mWindowAttributes.privateFlags |= compatibleWindowFlag;
796 // Restore old surface insets.
797 mWindowAttributes.surfaceInsets.set(
798 oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
799 mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
801 applyKeepScreenOnFlag(mWindowAttributes);
804 mSoftInputMode = attrs.softInputMode;
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);
816 mWindowAttributesChanged = true;
817 scheduleTraversals();
821 void handleAppVisibility(boolean visible) {
822 if (mAppVisible != visible) {
823 mAppVisible = visible;
824 scheduleTraversals();
826 WindowManagerGlobal.trimForeground();
831 void handleGetNewSurface() {
832 mNewSurfaceNeeded = true;
833 mFullRedrawNeeded = true;
834 scheduleTraversals();
837 private final DisplayListener mDisplayListener = new DisplayListener() {
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);
852 if (oldDisplayState == Display.STATE_OFF) {
853 // Draw was suppressed so we need to for it to happen here.
854 mFullRedrawNeeded = true;
855 scheduleTraversals();
863 public void onDisplayRemoved(int displayId) {
867 public void onDisplayAdded(int displayId) {
870 private int toViewScreenState(int displayState) {
871 return displayState == Display.STATE_OFF ?
872 View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON;
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)) {
882 mWindowSession.pokeDrawLock(mWindow);
883 } catch (RemoteException ex) {
884 // System server died, oh well.
890 public void requestFitSystemWindows() {
892 mApplyInsetsRequested = true;
893 scheduleTraversals();
897 public void requestLayout() {
898 if (!mHandlingLayoutInLayoutRequest) {
900 mLayoutRequested = true;
901 scheduleTraversals();
906 public boolean isLayoutRequested() {
907 return mLayoutRequested;
911 mDirty.set(0, 0, mWidth, mHeight);
912 if (!mWillDrawSoon) {
913 scheduleTraversals();
917 void invalidateWorld(View view) {
919 if (view instanceof ViewGroup) {
920 ViewGroup parent = (ViewGroup) view;
921 for (int i = 0; i < parent.getChildCount(); i++) {
922 invalidateWorld(parent.getChildAt(i));
928 public void invalidateChild(View child, Rect dirty) {
929 invalidateChildInParent(null, dirty);
933 public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
935 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
940 } else if (dirty.isEmpty() && !mIsAnimating) {
944 if (mCurScrollY != 0 || mTranslator != null) {
945 mTempRect.set(dirty);
947 if (mCurScrollY != 0) {
948 dirty.offset(0, -mCurScrollY);
950 if (mTranslator != null) {
951 mTranslator.translateRectInAppWindowToScreen(dirty);
953 if (mAttachInfo.mScalingRequired) {
958 final Rect localDirty = mDirty;
959 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
960 mAttachInfo.mSetIgnoreDirtyState = true;
961 mAttachInfo.mIgnoreDirtyState = true;
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));
972 localDirty.setEmpty();
974 if (!mWillDrawSoon && (intersected || mIsAnimating)) {
975 scheduleTraversals();
981 void setStopped(boolean stopped) {
982 if (mStopped != stopped) {
985 scheduleTraversals();
991 public ViewParent getParent() {
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!");
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);
1006 public void bringChildToFront(View child) {
1009 int getHostVisibility() {
1010 return mAppVisible ? mView.getVisibility() : View.GONE;
1013 void disposeResizeBuffer() {
1014 if (mResizeBuffer != null) {
1015 mResizeBuffer.destroy();
1016 mResizeBuffer = null;
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.
1029 * @param transition The LayoutTransition to be started on the next traversal.
1033 public void requestTransitionStart(LayoutTransition transition) {
1034 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
1035 if (mPendingTransitions == null) {
1036 mPendingTransitions = new ArrayList<LayoutTransition>();
1038 mPendingTransitions.add(transition);
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
1047 void notifyRendererOfFramePending() {
1048 if (mAttachInfo.mHardwareRenderer != null) {
1049 mAttachInfo.mHardwareRenderer.notifyFramePending();
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();
1062 notifyRendererOfFramePending();
1063 pokeDrawLockIfNeeded();
1067 void unscheduleTraversals() {
1068 if (mTraversalScheduled) {
1069 mTraversalScheduled = false;
1070 mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1071 mChoreographer.removeCallbacks(
1072 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1076 void doTraversal() {
1077 if (mTraversalScheduled) {
1078 mTraversalScheduled = false;
1079 mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1082 Debug.startMethodTracing("ViewAncestor");
1085 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
1087 performTraversals();
1089 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1093 Debug.stopMethodTracing();
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;
1106 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1107 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
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);
1136 private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
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;
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;
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;
1154 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
1155 "Measuring " + host + " in display " + desiredWindowWidth
1156 + "x" + desiredWindowHeight + "...");
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);
1167 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1168 baseSize = (int)mTmpValue.getDimension(packageMetrics);
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) {
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="
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!");
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;
1206 System.out.println("======================================");
1207 System.out.println("performTraversals -- after measure");
1211 return windowSizeMayChange;
1215 * Modifies the input matrix such that it maps view-local coordinates to
1216 * on-screen coordinates.
1218 * @param m input matrix to modify
1220 void transformMatrixToGlobal(Matrix m) {
1221 m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
1225 * Modifies the input matrix such that it maps on-screen coordinates to
1226 * view-local coordinates.
1228 * @param m input matrix to modify
1230 void transformMatrixToLocal(Matrix m) {
1231 m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
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.
1243 && (!mPendingContentInsets.equals(contentInsets) ||
1244 !mPendingStableInsets.equals(stableInsets))) {
1245 contentInsets = mPendingContentInsets;
1246 stableInsets = mPendingStableInsets;
1248 mLastWindowInsets = new WindowInsets(contentInsets,
1249 null /* windowDecorInsets */, stableInsets, mWindowIsRound);
1251 return mLastWindowInsets;
1254 void dispatchApplyInsets(View host) {
1255 host.dispatchApplyWindowInsets(getWindowInsets(true /* forceConstruct */));
1258 private void performTraversals() {
1259 // cache mView since it is used so much below...
1260 final View host = mView;
1263 System.out.println("======================================");
1264 System.out.println("performTraversals");
1268 if (host == null || !mAdded)
1271 mIsInTraversal = true;
1272 mWillDrawSoon = true;
1273 boolean windowSizeMayChange = false;
1274 boolean newSurface = false;
1275 boolean surfaceChanged = false;
1276 WindowManager.LayoutParams lp = mWindowAttributes;
1278 int desiredWindowWidth;
1279 int desiredWindowHeight;
1281 final int viewVisibility = getHostVisibility();
1282 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
1283 || mNewSurfaceNeeded;
1285 WindowManager.LayoutParams params = null;
1286 if (mWindowAttributesChanged) {
1287 mWindowAttributesChanged = false;
1288 surfaceChanged = true;
1291 CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
1292 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1294 mFullRedrawNeeded = true;
1295 mLayoutRequested = true;
1296 if (mLastInCompatMode) {
1297 params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1298 mLastInCompatMode = false;
1300 params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1301 mLastInCompatMode = true;
1305 mWindowAttributesChangesFlag = 0;
1307 Rect frame = mWinFrame;
1309 mFullRedrawNeeded = true;
1310 mLayoutRequested = true;
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;
1320 DisplayMetrics packageMetrics =
1321 mView.getContext().getResources().getDisplayMetrics();
1322 desiredWindowWidth = packageMetrics.widthPixels;
1323 desiredWindowHeight = packageMetrics.heightPixels;
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());
1340 host.dispatchAttachedToWindow(mAttachInfo, 0);
1341 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
1342 dispatchApplyInsets(host);
1343 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
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;
1357 if (viewVisibilityChanged) {
1358 mAttachInfo.mWindowVisibility = viewVisibility;
1359 host.dispatchWindowVisibilityChanged(viewVisibility);
1360 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1361 destroyHardwareResources();
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;
1370 // Non-visible windows can't hold accessibility focus.
1371 if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
1372 host.clearAccessibilityFocus();
1375 // Execute enqueued actions on every traversal in case a detached view enqueued an action
1376 getRunQueue().executeActions(mAttachInfo.mHandler);
1378 boolean insetsChanged = false;
1380 boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
1381 if (layoutRequested) {
1383 final Resources res = mView.getContext().getResources();
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);
1391 if (!mPendingOverscanInsets.equals(mAttachInfo.mOverscanInsets)) {
1392 insetsChanged = true;
1394 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
1395 insetsChanged = true;
1397 if (!mPendingStableInsets.equals(mAttachInfo.mStableInsets)) {
1398 insetsChanged = true;
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);
1405 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1406 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
1407 windowSizeMayChange = true;
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;
1417 DisplayMetrics packageMetrics = res.getDisplayMetrics();
1418 desiredWindowWidth = packageMetrics.widthPixels;
1419 desiredWindowHeight = packageMetrics.heightPixels;
1424 // Ask host how big it wants to be
1425 windowSizeMayChange |= measureHierarchy(host, lp, res,
1426 desiredWindowWidth, desiredWindowHeight);
1429 if (collectViewAttributes()) {
1432 if (mAttachInfo.mForceReportNewAttributes) {
1433 mAttachInfo.mForceReportNewAttributes = false;
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;
1450 if (resizeMode == 0) {
1451 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1453 if ((lp.softInputMode &
1454 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1455 lp.softInputMode = (lp.softInputMode &
1456 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
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;
1469 mAttachInfo.mOverscanRequested = (params.flags
1470 & WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN) != 0;
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);
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
1491 mLayoutRequested = false;
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));
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;
1508 boolean insetsPending = false;
1509 int relayoutResult = 0;
1511 if (mFirst || windowShouldResize || insetsChanged ||
1512 viewVisibilityChanged || params != null) {
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
1524 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1527 if (mSurfaceHolder != null) {
1528 mSurfaceHolder.mSurfaceLock.lock();
1529 mDrawingAllowed = true;
1532 boolean hwInitialized = false;
1533 boolean contentInsetsChanged = false;
1534 boolean hadSurface = mSurface.isValid();
1538 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1539 host.getMeasuredHeight() + ", params=" + params);
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
1549 mDirty.set(0, 0, mWidth, mHeight);
1551 mChoreographer.mFrameInfo.addFlags(FrameInfo.FLAG_WINDOW_LAYOUT_CHANGED);
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;
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);
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;
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) {
1593 disposeResizeBuffer();
1596 // if (mResizeBuffer == null) {
1597 // mResizeBuffer = mAttachInfo.mHardwareRenderer.createDisplayListLayer(
1598 // mWidth, mHeight);
1600 // mResizeBuffer.prepare(mWidth, mHeight, false);
1601 // RenderNode layerRenderNode = mResizeBuffer.startRecording();
1602 // HardwareCanvas layerCanvas = layerRenderNode.start(mWidth, mHeight);
1604 // final int restoreCount = layerCanvas.save();
1607 // final boolean scrolling = mScroller != null
1608 // && mScroller.computeScrollOffset();
1610 // yoff = mScroller.getCurrY();
1611 // mScroller.abortAnimation();
1616 // layerCanvas.translate(0, -yoff);
1617 // if (mTranslator != null) {
1618 // mTranslator.translateCanvas(layerCanvas);
1621 // RenderNode renderNode = mView.mRenderNode;
1622 // if (renderNode != null && renderNode.isValid()) {
1623 // layerCanvas.drawDisplayList(renderNode, null,
1624 // RenderNode.FLAG_CLIP_CHILDREN);
1626 // mView.draw(layerCanvas);
1629 // drawAccessibilityFocusedDrawableIfNeeded(layerCanvas);
1631 // mResizeBufferStartTime = SystemClock.uptimeMillis();
1632 // mResizeBufferDuration = mView.getResources().getInteger(
1633 // com.android.internal.R.integer.config_mediumAnimTime);
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);
1641 // mResizeBuffer.endRecording(mTempRect);
1643 // mAttachInfo.mHardwareRenderer.flushLayerUpdates();
1645 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1646 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1647 + mAttachInfo.mContentInsets);
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;
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;
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);
1671 if (visibleInsetsChanged) {
1672 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1673 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1674 + mAttachInfo.mVisibleInsets);
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
1687 mFullRedrawNeeded = true;
1688 mPreviousTransparentRegion.setEmpty();
1690 if (mAttachInfo.mHardwareRenderer != null) {
1692 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
1694 } catch (OutOfResourcesException e) {
1695 handleOutOfResourcesException(e);
1700 } else if (!mSurface.isValid()) {
1701 // If the surface has been removed, then reset the scroll
1703 if (mLastScrolledFocus != null) {
1704 mLastScrolledFocus.clear();
1706 mScrollY = mCurScrollY = 0;
1707 if (mView instanceof RootViewSurfaceTaker) {
1708 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
1710 if (mScroller != null) {
1711 mScroller.abortAnimation();
1713 disposeResizeBuffer();
1714 // Our surface is gone
1715 if (mAttachInfo.mHardwareRenderer != null &&
1716 mAttachInfo.mHardwareRenderer.isEnabled()) {
1717 mAttachInfo.mHardwareRenderer.destroy();
1719 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1720 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1721 mFullRedrawNeeded = true;
1723 mAttachInfo.mHardwareRenderer.updateSurface(mSurface);
1724 } catch (OutOfResourcesException e) {
1725 handleOutOfResourcesException(e);
1729 } catch (RemoteException e) {
1732 if (DEBUG_ORIENTATION) Log.v(
1733 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1735 mAttachInfo.mWindowLeft = frame.left;
1736 mAttachInfo.mWindowTop = frame.top;
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();
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;
1753 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1754 mSurfaceHolder.mSurfaceLock.unlock();
1755 if (mSurface.isValid()) {
1757 mSurfaceHolder.ungetCallbacks();
1760 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1761 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1762 if (callbacks != null) {
1763 for (SurfaceHolder.Callback c : callbacks) {
1764 c.surfaceCreated(mSurfaceHolder);
1767 surfaceChanged = true;
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,
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);
1790 mSurfaceHolder.mSurfaceLock.lock();
1792 mSurfaceHolder.mSurface = new Surface();
1794 mSurfaceHolder.mSurfaceLock.unlock();
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;
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);
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);
1827 // Ask host how big it wants to be
1828 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1830 // Implementation of weights from WindowManager.LayoutParams
1831 // We just grow the dimensions as needed and re-measure if
1833 int width = host.getMeasuredWidth();
1834 int height = host.getMeasuredHeight();
1835 boolean measureAgain = false;
1837 if (lp.horizontalWeight > 0.0f) {
1838 width += (int) ((mWidth - width) * lp.horizontalWeight);
1839 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1840 MeasureSpec.EXACTLY);
1841 measureAgain = true;
1843 if (lp.verticalWeight > 0.0f) {
1844 height += (int) ((mHeight - height) * lp.verticalWeight);
1845 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1846 MeasureSpec.EXACTLY);
1847 measureAgain = true;
1851 if (DEBUG_LAYOUT) Log.v(TAG,
1852 "And hey let's measure once more: width=" + width
1853 + " height=" + height);
1854 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1857 layoutRequested = true;
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.
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.
1875 final boolean windowMoved = (mAttachInfo.mWindowLeft != frame.left
1876 || mAttachInfo.mWindowTop != frame.top);
1878 if (mTranslator != null) {
1879 mTranslator.translateRectInScreenToAppWinFrame(frame);
1881 mAttachInfo.mWindowLeft = frame.left;
1882 mAttachInfo.mWindowTop = frame.top;
1886 final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
1887 boolean triggerGlobalLayoutListener = didLayout
1888 || mAttachInfo.mRecomputeGlobalAttributes;
1890 performLayout(lp, desiredWindowWidth, desiredWindowHeight);
1892 // By this point all views have been sized and positioned
1893 // We can compute the transparent area
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);
1903 host.gatherTransparentRegion(mTransparentRegion);
1904 if (mTranslator != null) {
1905 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1908 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1909 mPreviousTransparentRegion.set(mTransparentRegion);
1910 mFullRedrawNeeded = true;
1911 // reconfigure window manager
1913 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1914 } catch (RemoteException e) {
1920 System.out.println("======================================");
1921 System.out.println("performTraversals -- after setFrame");
1926 if (triggerGlobalLayoutListener) {
1927 mAttachInfo.mRecomputeGlobalAttributes = false;
1928 mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
1931 if (computesInternalInsets) {
1932 // Clear the original insets.
1933 final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
1936 // Compute new insets in place.
1937 mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
1938 mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
1940 // Tell the window manager.
1941 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1942 mLastGivenInsets.set(insets);
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);
1953 contentInsets = insets.contentInsets;
1954 visibleInsets = insets.visibleInsets;
1955 touchableRegion = insets.touchableRegion;
1959 mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
1960 contentInsets, visibleInsets, touchableRegion);
1961 } catch (RemoteException e) {
1966 boolean skipDraw = false;
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());
1978 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1979 + mView.findFocus());
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;
1988 } else if (mWindowsAnimating) {
1993 mWillDrawSoon = false;
1994 mNewSurfaceNeeded = false;
1995 mViewVisibility = viewVisibility;
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);
2012 // Remember if we must report the next draw.
2013 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
2014 mReportNextDraw = true;
2017 boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() ||
2018 viewVisibility != View.VISIBLE;
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();
2026 mPendingTransitions.clear();
2032 if (viewVisibility == View.VISIBLE) {
2034 scheduleTraversals();
2035 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2036 for (int i = 0; i < mPendingTransitions.size(); ++i) {
2037 mPendingTransitions.get(i).endChangingAnimations();
2039 mPendingTransitions.clear();
2043 mIsInTraversal = false;
2046 private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
2047 Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
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());
2054 } catch (RemoteException ex) {
2056 mLayoutRequested = true; // ask wm for a new surface next time.
2059 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
2060 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2062 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2064 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2069 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
2070 * is currently undergoing a layout pass.
2072 * @return whether the view hierarchy is currently undergoing a layout pass
2074 boolean isInLayout() {
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.
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>
2096 * @param view the view that requested the layout.
2098 * @return true if request should proceed, false otherwise.
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
2105 if (!mLayoutRequesters.contains(view)) {
2106 mLayoutRequesters.add(view);
2108 if (!mHandlingLayoutInLayoutRequest) {
2109 // Let the request proceed normally; it will be processed in a second layout pass
2113 // Don't let the request proceed during the second layout pass.
2114 // It will post to the next frame instead.
2119 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
2120 int desiredWindowHeight) {
2121 mLayoutRequested = false;
2122 mScrollMayChange = true;
2125 final View host = mView;
2126 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
2127 Log.v(TAG, "Laying out " + host + " to (" +
2128 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
2131 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
2133 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
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,
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
2148 mHandlingLayoutInLayoutRequest = true;
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();
2158 measureHierarchy(host, lp, mView.getContext().getResources(),
2159 desiredWindowWidth, desiredWindowHeight);
2161 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2163 mHandlingLayoutInLayoutRequest = false;
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() {
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();
2188 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
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).
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.
2204 private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters,
2205 boolean secondLayoutRequests) {
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;
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) {
2222 if (parent.mParent instanceof View) {
2223 parent = (View) parent.mParent;
2229 if (validLayoutRequesters == null) {
2230 validLayoutRequesters = new ArrayList<View>();
2232 validLayoutRequesters.add(view);
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;
2251 layoutRequesters.clear();
2252 return validLayoutRequesters;
2256 public void requestTransparentRegion(View child) {
2257 // the test below should not fail unless someone is messing with us
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;
2270 * Figures out the measure spec for the root view in a window based on it's
2274 * The available width or height of the window
2276 * @param rootDimension
2277 * The layout params for one dimension (width or height) of the
2280 * @return The measure spec to use to measure the root view.
2282 private static int getRootMeasureSpec(int windowSize, int rootDimension) {
2284 switch (rootDimension) {
2286 case ViewGroup.LayoutParams.MATCH_PARENT:
2287 // Window can't resize. Force root view to be windowSize.
2288 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2290 case ViewGroup.LayoutParams.WRAP_CONTENT:
2291 // Window can resize. Set max size for root view.
2292 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2295 // Window wants to be an exact size. Force root view to be that size.
2296 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2302 int mHardwareXOffset;
2303 int mHardwareYOffset;
2305 final Paint mResizePaint = new Paint();
2308 public void onHardwarePreDraw(DisplayListCanvas canvas) {
2309 canvas.translate(-mHardwareXOffset, -mHardwareYOffset);
2313 public void onHardwarePostDraw(DisplayListCanvas canvas) {
2314 if (mResizeBuffer != null) {
2315 mResizePaint.setAlpha(mResizeAlpha);
2316 canvas.drawHardwareLayer(mResizeBuffer, mHardwareXOffset, mHardwareYOffset,
2319 drawAccessibilityFocusedDrawableIfNeeded(canvas);
2325 void outputDisplayList(View view) {
2326 RenderNode renderNode = view.updateDisplayListIfDirty();
2327 renderNode.output();
2331 * @see #PROPERTY_PROFILE_RENDERING
2333 private void profileRendering(boolean enabled) {
2334 if (mProfileRendering) {
2335 mRenderProfilingEnabled = enabled;
2337 if (mRenderProfiler != null) {
2338 mChoreographer.removeFrameCallback(mRenderProfiler);
2340 if (mRenderProfilingEnabled) {
2341 if (mRenderProfiler == null) {
2342 mRenderProfiler = new Choreographer.FrameCallback() {
2344 public void doFrame(long frameTimeNanos) {
2345 mDirty.set(0, 0, mWidth, mHeight);
2346 scheduleTraversals();
2347 if (mRenderProfilingEnabled) {
2348 mChoreographer.postFrameCallback(mRenderProfiler);
2353 mChoreographer.postFrameCallback(mRenderProfiler);
2355 mRenderProfiler = null;
2361 * Called from draw() when DEBUG_FPS is enabled
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;
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;
2386 private void performDraw() {
2387 if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
2391 final boolean fullRedrawNeeded = mFullRedrawNeeded;
2392 mFullRedrawNeeded = false;
2395 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2397 draw(fullRedrawNeeded);
2400 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
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();
2410 mAttachInfo.mPendingAnimatingRenderNodes.clear();
2413 if (mReportNextDraw) {
2414 mReportNextDraw = false;
2415 if (mAttachInfo.mHardwareRenderer != null) {
2416 mAttachInfo.mHardwareRenderer.fence();
2420 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
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(
2435 mWindowSession.finishDrawing(mWindow);
2436 } catch (RemoteException e) {
2441 private void draw(boolean fullRedrawNeeded) {
2442 Surface surface = mSurface;
2443 if (!surface.isValid()) {
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));
2461 scrollToRectOrFocus(null, false);
2463 if (mAttachInfo.mViewScrollChanged) {
2464 mAttachInfo.mViewScrollChanged = false;
2465 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
2468 boolean animating = mScroller != null && mScroller.computeScrollOffset();
2469 final int curScrollY;
2471 curScrollY = mScroller.getCurrY();
2473 curScrollY = mScrollY;
2475 if (mCurScrollY != curScrollY) {
2476 mCurScrollY = curScrollY;
2477 fullRedrawNeeded = true;
2478 if (mView instanceof RootViewSurfaceTaker) {
2479 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
2483 final float appScale = mAttachInfo.mApplicationScale;
2484 final boolean scalingRequired = mAttachInfo.mScalingRequired;
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);
2493 resizeAlpha = 255 - (int)(amt*255);
2495 disposeResizeBuffer();
2499 final Rect dirty = mDirty;
2500 if (mSurfaceHolder != null) {
2501 // The app owns the surface, we won't draw.
2504 if (mScroller != null) {
2505 mScroller.abortAnimation();
2507 disposeResizeBuffer();
2512 if (fullRedrawNeeded) {
2513 mAttachInfo.mIgnoreDirtyState = true;
2514 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
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);
2526 mAttachInfo.mTreeObserver.dispatchOnDraw();
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;
2536 // Offset dirty rect for surface insets.
2537 dirty.offset(surfaceInsets.left, surfaceInsets.right);
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);
2548 if (!bounds.equals(drawable.getBounds())) {
2549 accessibilityFocusDirty = true;
2553 mAttachInfo.mDrawingTime =
2554 mChoreographer.getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
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;
2561 // Draw with hardware renderer.
2562 mIsAnimating = false;
2564 if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
2565 mHardwareYOffset = yOffset;
2566 mHardwareXOffset = xOffset;
2567 invalidateRoot = true;
2569 mResizeAlpha = resizeAlpha;
2571 if (invalidateRoot) {
2572 mAttachInfo.mHardwareRenderer.invalidateRoot();
2577 mBlockResizeBuffer = false;
2578 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
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()) {
2593 mAttachInfo.mHardwareRenderer.initializeIfNeeded(
2594 mWidth, mHeight, mSurface, surfaceInsets);
2595 } catch (OutOfResourcesException e) {
2596 handleOutOfResourcesException(e);
2600 mFullRedrawNeeded = true;
2601 scheduleTraversals();
2605 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
2612 mFullRedrawNeeded = true;
2613 scheduleTraversals();
2618 * @return true if drawing was successful, false if an error occurred
2620 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
2621 boolean scalingRequired, Rect dirty) {
2623 // Draw with software renderer.
2624 final Canvas canvas;
2626 final int left = dirty.left;
2627 final int top = dirty.top;
2628 final int right = dirty.right;
2629 final int bottom = dirty.bottom;
2631 canvas = mSurface.lockCanvas(dirty);
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;
2640 // TODO: Do this in native
2641 canvas.setDensity(mDensity);
2642 } catch (Surface.OutOfResourcesException e) {
2643 handleOutOfResourcesException(e);
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.
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);
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
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);
2674 mIsAnimating = false;
2675 mView.mPrivateFlags |= View.PFLAG_DRAWN;
2678 Context cxt = mView.getContext();
2679 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
2680 ", metrics=" + cxt.getResources().getDisplayMetrics() +
2681 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2684 canvas.translate(-xoff, -yoff);
2685 if (mTranslator != null) {
2686 mTranslator.translateCanvas(canvas);
2688 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2689 attachInfo.mSetIgnoreDirtyState = false;
2693 drawAccessibilityFocusedDrawableIfNeeded(canvas);
2695 if (!attachInfo.mSetIgnoreDirtyState) {
2696 // Only clear the flag if it was not set during the mView.draw() call
2697 attachInfo.mIgnoreDirtyState = false;
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
2711 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
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.
2722 * Note: We are doing this here to be able to draw the highlight for
2723 * virtual views in addition to real ones.
2725 * @param canvas The canvas on which to draw.
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);
2735 } else if (mAttachInfo.mAccessibilityFocusDrawable != null) {
2736 mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0);
2740 private boolean getAccessibilityFocusedRect(Rect bounds) {
2741 final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2742 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2746 final View host = mAccessibilityFocusedHost;
2747 if (host == null || host.mAttachInfo == null) {
2751 final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider();
2752 if (provider == null) {
2753 host.getBoundsOnScreen(bounds, true);
2754 } else if (mAccessibilityFocusedVirtualView != null) {
2755 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
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();
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);
2773 mAttachInfo.mAccessibilityFocusDrawable =
2774 mView.mContext.getDrawable(value.resourceId);
2777 return mAttachInfo.mAccessibilityFocusDrawable;
2783 public void setDrawDuringWindowsAnimating(boolean value) {
2784 mDrawDuringWindowsAnimating = value;
2786 handleDispatchDoneAnimating();
2790 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2791 final Rect ci = mAttachInfo.mContentInsets;
2792 final Rect vi = mAttachInfo.mVisibleInsets;
2794 boolean handled = false;
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.
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
2809 final View focus = mView.findFocus();
2810 if (focus == null) {
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
2820 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2821 + " rectangle=" + rectangle + " ci=" + ci
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
2827 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2828 + mScrollY + " vi=" + vi.toShortString());
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(
2850 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2851 "Focus in window: focusRect="
2852 + mTempRect.toShortString()
2853 + " visRect=" + mVisRect.toShortString());
2855 mTempRect.set(rectangle);
2856 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2857 "Request scroll to rect: "
2858 + mTempRect.toShortString()
2859 + " visRect=" + mVisRect.toShortString());
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);
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());
2895 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2896 } else if (mScroller != null) {
2897 mScroller.abortAnimation();
2908 public View getAccessibilityFocusedHost() {
2909 return mAccessibilityFocusedHost;
2915 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
2916 return mAccessibilityFocusedVirtualView;
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) {
2924 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
2925 View focusHost = mAccessibilityFocusedHost;
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;
2935 // Clear accessibility focus on the host after clearing state since
2936 // this method may be reentrant.
2937 focusHost.clearAccessibilityFocusNoCallbacks();
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);
2950 focusNode.recycle();
2952 if (mAccessibilityFocusedHost != null) {
2953 // Clear accessibility focus in the view.
2954 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2957 // Set the new focus host and node.
2958 mAccessibilityFocusedHost = view;
2959 mAccessibilityFocusedVirtualView = node;
2961 if (mAttachInfo.mHardwareRenderer != null) {
2962 mAttachInfo.mHardwareRenderer.invalidateRoot();
2967 public void requestChildFocus(View child, View focused) {
2968 if (DEBUG_INPUT_RESIZE) {
2969 Log.v(TAG, "Request child focus: focus now " + focused);
2972 scheduleTraversals();
2976 public void clearChildFocus(View child) {
2977 if (DEBUG_INPUT_RESIZE) {
2978 Log.v(TAG, "Clearing child focus");
2981 scheduleTraversals();
2985 public ViewParent getParentForAccessibility() {
2990 public void focusableViewAvailable(View v) {
2992 if (mView != null) {
2993 if (!mView.hasFocus()) {
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)) {
3012 public void recomputeViewAttributes(View child) {
3014 if (mView == child) {
3015 mAttachInfo.mRecomputeGlobalAttributes = true;
3016 if (!mWillDrawSoon) {
3017 scheduleTraversals();
3022 void dispatchDetachedFromWindow() {
3023 if (mView != null && mView.mAttachInfo != null) {
3024 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
3025 mView.dispatchDetachedFromWindow();
3028 mAccessibilityInteractionConnectionManager.ensureNoConnection();
3029 mAccessibilityManager.removeAccessibilityStateChangeListener(
3030 mAccessibilityInteractionConnectionManager);
3031 mAccessibilityManager.removeHighTextContrastStateChangeListener(
3032 mHighContrastTextManager);
3033 removeSendWindowContentChangedCallback();
3035 destroyHardwareRenderer();
3037 setAccessibilityFocus(null, null);
3039 mView.assignParent(null);
3041 mAttachInfo.mRootView = null;
3045 if (mInputQueueCallback != null && mInputQueue != null) {
3046 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
3047 mInputQueue.dispose();
3048 mInputQueueCallback = null;
3051 if (mInputEventReceiver != null) {
3052 mInputEventReceiver.dispose();
3053 mInputEventReceiver = null;
3056 mWindowSession.remove(mWindow);
3057 } catch (RemoteException e) {
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;
3067 mDisplayManager.unregisterDisplayListener(mDisplayListener);
3069 unscheduleTraversals();
3072 void updateConfiguration(Configuration config, boolean force) {
3073 if (DEBUG_CONFIGURATION) Log.v(TAG,
3074 "Applying new config to window "
3075 + mWindowAttributes.getTitle()
3078 CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo();
3079 if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
3080 config = new Configuration(config);
3081 ci.applyToConfiguration(mNoncompatDensity, config);
3084 synchronized (sConfigCallbacks) {
3085 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
3086 sConfigCallbacks.get(i).onConfigurationChanged(config);
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);
3102 mView.dispatchConfigurationChanged(config);
3108 * Return true if child is an ancestor of parent, (or equal to the parent).
3110 public static boolean isViewDescendantOf(View child, View parent) {
3111 if (child == parent) {
3115 final ViewParent theParent = child.getParent();
3116 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
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;
3144 final class ViewRootHandler extends Handler {
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";
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";
3195 return super.getMessageName(message);
3199 public void handleMessage(Message msg) {
3201 case MSG_INVALIDATE:
3202 ((View) msg.obj).invalidate();
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);
3209 case MSG_PROCESS_INPUT_EVENTS:
3210 mProcessInputEventsScheduled = false;
3211 doProcessInputEvents();
3213 case MSG_DISPATCH_APP_VISIBILITY:
3214 handleAppVisibility(msg.arg1 != 0);
3216 case MSG_DISPATCH_GET_NEW_SURFACE:
3217 handleGetNewSurface();
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) {
3230 } // fall through...
3231 case MSG_RESIZED_REPORT:
3233 SomeArgs args = (SomeArgs) msg.obj;
3235 Configuration config = (Configuration) args.arg4;
3236 if (config != null) {
3237 updateConfiguration(config, false);
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);
3248 if (msg.what == MSG_RESIZED_REPORT) {
3249 mReportNextDraw = true;
3255 case MSG_WINDOW_MOVED:
3257 final int w = mWinFrame.width();
3258 final int h = mWinFrame.height();
3259 final int l = msg.arg1;
3260 final int t = msg.arg2;
3262 mWinFrame.right = l + w;
3264 mWinFrame.bottom = t + h;
3269 case MSG_WINDOW_FOCUS_CHANGED: {
3271 boolean hasWindowFocus = msg.arg1 != 0;
3272 mAttachInfo.mHasWindowFocus = hasWindowFocus;
3274 profileRendering(hasWindowFocus);
3276 if (hasWindowFocus) {
3277 boolean inTouchMode = msg.arg2 != 0;
3278 ensureTouchModeLocally(inTouchMode);
3280 if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){
3281 mFullRedrawNeeded = true;
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);
3290 if (!mWindowSession.outOfMemory(mWindow)) {
3291 Slog.w(TAG, "No processes killed for memory; killing self");
3292 Process.killProcess(Process.myPid());
3294 } catch (RemoteException ex) {
3297 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3303 mLastWasImTarget = WindowManager.LayoutParams
3304 .mayUseInputMethod(mWindowAttributes.flags);
3306 InputMethodManager imm = InputMethodManager.peekInstance();
3307 if (mView != null) {
3308 if (hasWindowFocus && imm != null && mLastWasImTarget &&
3309 !isInLocalFocusMode()) {
3310 imm.startGettingWindowFocus(mView);
3312 mAttachInfo.mKeyDispatchState.reset();
3313 mView.dispatchWindowFocusChanged(hasWindowFocus);
3314 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
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);
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())
3331 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3332 mHasHadWindowFocus = true;
3335 if (mView != null && mAccessibilityManager.isEnabled()) {
3336 if (hasWindowFocus) {
3337 mView.sendAccessibilityEvent(
3338 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
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);
3353 case MSG_SYNTHESIZE_INPUT_EVENT: {
3354 InputEvent event = (InputEvent)msg.obj;
3355 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true);
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);
3369 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3371 case MSG_FINISH_INPUT_CONNECTION: {
3372 InputMethodManager imm = InputMethodManager.peekInstance();
3374 imm.reportFinishInputConnection((InputConnection)msg.obj);
3377 case MSG_CHECK_FOCUS: {
3378 InputMethodManager imm = InputMethodManager.peekInstance();
3383 case MSG_CLOSE_SYSTEM_DIALOGS: {
3384 if (mView != null) {
3385 mView.onCloseSystemDialogs((String)msg.obj);
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);
3394 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3395 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3397 case MSG_UPDATE_CONFIGURATION: {
3398 Configuration config = (Configuration)msg.obj;
3399 if (config.isOtherSeqNewer(mLastConfiguration)) {
3400 config = mLastConfiguration;
3402 updateConfiguration(config, false);
3404 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3405 setAccessibilityFocus(null, null);
3407 case MSG_DISPATCH_DONE_ANIMATING: {
3408 handleDispatchDoneAnimating();
3410 case MSG_INVALIDATE_WORLD: {
3411 if (mView != null) {
3412 invalidateWorld(mView);
3415 case MSG_DISPATCH_WINDOW_SHOWN: {
3416 handleDispatchWindowShown();
3422 final ViewRootHandler mHandler = new ViewRootHandler();
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.
3428 * If the touch mode has changed, tell the window manager, and handle it locally.
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
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;
3438 // tell the window manager
3440 if (!isInLocalFocusMode()) {
3441 mWindowSession.setInTouchMode(inTouchMode);
3443 } catch (RemoteException e) {
3444 throw new RuntimeException(e);
3447 // handle the change
3448 return ensureTouchModeLocally(inTouchMode);
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
3457 private boolean ensureTouchModeLocally(boolean inTouchMode) {
3458 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3459 + "touch mode is " + mAttachInfo.mInTouchMode);
3461 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3463 mAttachInfo.mInTouchMode = inTouchMode;
3464 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3466 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
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
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
3481 return ancestorToTakeFocus.requestFocus();
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);
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.
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()) {
3507 if (vgParent.isRootNamespace()) {
3510 parent = vgParent.getParent();
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
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.
3531 // find the best view to give focus to in this brave new non-touch-mode
3533 final View focused = focusSearch(null, View.FOCUS_DOWN);
3534 if (focused != null) {
3535 return focused.requestFocus(View.FOCUS_DOWN);
3542 * Base class for implementing a stage in the chain of responsibility
3543 * for processing input events.
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.
3549 abstract class InputStage {
3550 private final InputStage mNext;
3552 protected static final int FORWARD = 0;
3553 protected static final int FINISH_HANDLED = 1;
3554 protected static final int FINISH_NOT_HANDLED = 2;
3557 * Creates an input stage.
3558 * @param next The next stage to which events should be forwarded.
3560 public InputStage(InputStage next) {
3565 * Delivers an event to be processed.
3567 public final void deliver(QueuedInputEvent q) {
3568 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
3570 } else if (shouldDropInputEvent(q)) {
3573 apply(q, onProcess(q));
3578 * Marks the the input event as finished then forwards it to the next stage.
3580 protected void finish(QueuedInputEvent q, boolean handled) {
3581 q.mFlags |= QueuedInputEvent.FLAG_FINISHED;
3583 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;
3589 * Forwards the event to the next stage.
3591 protected void forward(QueuedInputEvent q) {
3596 * Applies a result code from {@link #onProcess} to the specified event.
3598 protected void apply(QueuedInputEvent q, int result) {
3599 if (result == FORWARD) {
3601 } else if (result == FINISH_HANDLED) {
3603 } else if (result == FINISH_NOT_HANDLED) {
3606 throw new IllegalArgumentException("Invalid result: " + result);
3611 * Called when an event is ready to be processed.
3612 * @return A result code indicating how the event was handled.
3614 protected int onProcess(QueuedInputEvent q) {
3619 * Called when an event is being delivered to the next stage.
3621 protected void onDeliverToNext(QueuedInputEvent q) {
3622 if (DEBUG_INPUT_STAGES) {
3623 Log.v(TAG, "Done with " + getClass().getSimpleName() + ". " + q);
3625 if (mNext != null) {
3628 finishInputEvent(q);
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);
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.
3644 Slog.w(TAG, "Cancelling event due to no window focus: " + q.mEvent);
3648 // Drop non-terminal input events.
3649 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent);
3655 void dump(String prefix, PrintWriter writer) {
3656 if (mNext != null) {
3657 mNext.dump(prefix, writer);
3663 * Base class for implementing an input pipeline stage that supports
3664 * asynchronous and out-of-order processing of input events.
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.
3671 abstract class AsyncInputStage extends InputStage {
3672 private final String mTraceCounter;
3674 private QueuedInputEvent mQueueHead;
3675 private QueuedInputEvent mQueueTail;
3676 private int mQueueLength;
3678 protected static final int DEFER = 3;
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.
3686 public AsyncInputStage(InputStage next, String traceCounter) {
3688 mTraceCounter = traceCounter;
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.
3696 protected void defer(QueuedInputEvent q) {
3697 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED;
3702 protected void forward(QueuedInputEvent q) {
3703 // Clear the deferred flag.
3704 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
3706 // Fast path if the queue is empty.
3707 QueuedInputEvent curr = mQueueHead;
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()) {
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.
3737 // The event is not blocked. Deliver it immediately.
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) {
3750 QueuedInputEvent next = curr.mNext;
3751 dequeue(curr, prev);
3752 super.forward(curr);
3762 protected void apply(QueuedInputEvent q, int result) {
3763 if (result == DEFER) {
3766 super.apply(q, result);
3770 private void enqueue(QueuedInputEvent q) {
3771 if (mQueueTail == null) {
3775 mQueueTail.mNext = q;
3780 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3783 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) {
3785 mQueueHead = q.mNext;
3787 prev.mNext = q.mNext;
3789 if (mQueueTail == q) {
3795 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3799 void dump(String prefix, PrintWriter writer) {
3800 writer.print(prefix);
3801 writer.print(getClass().getName());
3802 writer.print(": mQueueLength=");
3803 writer.println(mQueueLength);
3805 super.dump(prefix, writer);
3810 * Delivers pre-ime input events to a native activity.
3811 * Does not support pointer events.
3813 final class NativePreImeInputStage extends AsyncInputStage
3814 implements InputQueue.FinishedInputEventCallback {
3815 public NativePreImeInputStage(InputStage next, String traceCounter) {
3816 super(next, traceCounter);
3820 protected int onProcess(QueuedInputEvent q) {
3821 if (mInputQueue != null && q.mEvent instanceof KeyEvent) {
3822 mInputQueue.sendInputEvent(q.mEvent, q, true, this);
3829 public void onFinishedInputEvent(Object token, boolean handled) {
3830 QueuedInputEvent q = (QueuedInputEvent)token;
3840 * Delivers pre-ime input events to the view hierarchy.
3841 * Does not support pointer events.
3843 final class ViewPreImeInputStage extends InputStage {
3844 public ViewPreImeInputStage(InputStage next) {
3849 protected int onProcess(QueuedInputEvent q) {
3850 if (q.mEvent instanceof KeyEvent) {
3851 return processKeyEvent(q);
3856 private int processKeyEvent(QueuedInputEvent q) {
3857 final KeyEvent event = (KeyEvent)q.mEvent;
3858 if (mView.dispatchKeyEventPreIme(event)) {
3859 return FINISH_HANDLED;
3866 * Delivers input events to the ime.
3867 * Does not support pointer events.
3869 final class ImeInputStage extends AsyncInputStage
3870 implements InputMethodManager.FinishedInputEventCallback {
3871 public ImeInputStage(InputStage next, String traceCounter) {
3872 super(next, traceCounter);
3876 protected int onProcess(QueuedInputEvent q) {
3877 if (mLastWasImTarget && !isInLocalFocusMode()) {
3878 InputMethodManager imm = InputMethodManager.peekInstance();
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
3889 return DEFER; // callback will be invoked later
3897 public void onFinishedInputEvent(Object token, boolean handled) {
3898 QueuedInputEvent q = (QueuedInputEvent)token;
3908 * Performs early processing of post-ime input events.
3910 final class EarlyPostImeInputStage extends InputStage {
3911 public EarlyPostImeInputStage(InputStage next) {
3916 protected int onProcess(QueuedInputEvent q) {
3917 if (q.mEvent instanceof KeyEvent) {
3918 return processKeyEvent(q);
3920 final int source = q.mEvent.getSource();
3921 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3922 return processPointerEvent(q);
3928 private int processKeyEvent(QueuedInputEvent q) {
3929 final KeyEvent event = (KeyEvent)q.mEvent;
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;
3937 // Make sure the fallback event policy sees all keys that will be
3938 // delivered to the view hierarchy.
3939 mFallbackEventHandler.preDispatchKeyEvent(event);
3943 private int processPointerEvent(QueuedInputEvent q) {
3944 final MotionEvent event = (MotionEvent)q.mEvent;
3946 // Translate the pointer event for compatibility, if needed.
3947 if (mTranslator != null) {
3948 mTranslator.translateEventInScreenToAppWindow(event);
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);
3957 // Offset the scroll position.
3958 if (mCurScrollY != 0) {
3959 event.offsetLocation(0, mCurScrollY);
3962 // Remember the touch position for possible drag-initiation.
3963 if (event.isTouchEvent()) {
3964 mLastTouchPoint.x = event.getRawX();
3965 mLastTouchPoint.y = event.getRawY();
3972 * Delivers post-ime input events to a native activity.
3974 final class NativePostImeInputStage extends AsyncInputStage
3975 implements InputQueue.FinishedInputEventCallback {
3976 public NativePostImeInputStage(InputStage next, String traceCounter) {
3977 super(next, traceCounter);
3981 protected int onProcess(QueuedInputEvent q) {
3982 if (mInputQueue != null) {
3983 mInputQueue.sendInputEvent(q.mEvent, q, false, this);
3990 public void onFinishedInputEvent(Object token, boolean handled) {
3991 QueuedInputEvent q = (QueuedInputEvent)token;
4001 * Delivers post-ime input events to the view hierarchy.
4003 final class ViewPostImeInputStage extends InputStage {
4004 public ViewPostImeInputStage(InputStage next) {
4009 protected int onProcess(QueuedInputEvent q) {
4010 if (q.mEvent instanceof KeyEvent) {
4011 return processKeyEvent(q);
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);
4022 return processGenericMotionEvent(q);
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();
4036 super.onDeliverToNext(q);
4039 private int processKeyEvent(QueuedInputEvent q) {
4040 final KeyEvent event = (KeyEvent)q.mEvent;
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();
4048 // Deliver the key to the view hierarchy.
4049 if (mView.dispatchKeyEvent(event)) {
4050 return FINISH_HANDLED;
4053 if (shouldDropInputEvent(q)) {
4054 return FINISH_NOT_HANDLED;
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;
4065 if (shouldDropInputEvent(q)) {
4066 return FINISH_NOT_HANDLED;
4070 // Apply the fallback event policy.
4071 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
4072 return FINISH_HANDLED;
4074 if (shouldDropInputEvent(q)) {
4075 return FINISH_NOT_HANDLED;
4078 // Handle automatic focus changes.
4079 if (event.getAction() == KeyEvent.ACTION_DOWN) {
4081 switch (event.getKeyCode()) {
4082 case KeyEvent.KEYCODE_DPAD_LEFT:
4083 if (event.hasNoModifiers()) {
4084 direction = View.FOCUS_LEFT;
4087 case KeyEvent.KEYCODE_DPAD_RIGHT:
4088 if (event.hasNoModifiers()) {
4089 direction = View.FOCUS_RIGHT;
4092 case KeyEvent.KEYCODE_DPAD_UP:
4093 if (event.hasNoModifiers()) {
4094 direction = View.FOCUS_UP;
4097 case KeyEvent.KEYCODE_DPAD_DOWN:
4098 if (event.hasNoModifiers()) {
4099 direction = View.FOCUS_DOWN;
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;
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(
4125 if (v.requestFocus(direction, mTempRect)) {
4126 playSoundEffect(SoundEffectConstants
4127 .getContantForFocusDirection(direction));
4128 return FINISH_HANDLED;
4132 // Give the focused view a last chance to handle the dpad key.
4133 if (mView.dispatchUnhandledMove(focused, direction)) {
4134 return FINISH_HANDLED;
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;
4148 private int processPointerEvent(QueuedInputEvent q) {
4149 final MotionEvent event = (MotionEvent)q.mEvent;
4151 mAttachInfo.mUnbufferedDispatchRequested = false;
4152 boolean handled = mView.dispatchPointerEvent(event);
4153 if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4154 mUnbufferedInputDispatch = true;
4155 if (mConsumeBatchedInputScheduled) {
4156 scheduleConsumeBatchedInputImmediately();
4159 return handled ? FINISH_HANDLED : FORWARD;
4162 private int processTrackballEvent(QueuedInputEvent q) {
4163 final MotionEvent event = (MotionEvent)q.mEvent;
4165 if (mView.dispatchTrackballEvent(event)) {
4166 return FINISH_HANDLED;
4171 private int processGenericMotionEvent(QueuedInputEvent q) {
4172 final MotionEvent event = (MotionEvent)q.mEvent;
4174 // Deliver the event to the view.
4175 if (mView.dispatchGenericMotionEvent(event)) {
4176 return FINISH_HANDLED;
4183 * Performs synthesis of new input events from unhandled input events.
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();
4192 public SyntheticInputStage() {
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;
4213 } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4214 mKeyboard.process((KeyEvent)q.mEvent);
4215 return FINISH_HANDLED;
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);
4238 super.onDeliverToNext(q);
4243 * Creates dpad events from unhandled trackball movements.
4245 final class SyntheticTrackballHandler {
4246 private final TrackballAxis mX = new TrackballAxis();
4247 private final TrackballAxis mY = new TrackballAxis();
4248 private long mLastTime;
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.
4258 mLastTime = curTime;
4261 final int action = event.getAction();
4262 final int metaState = event.getMetaState();
4264 case MotionEvent.ACTION_DOWN:
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));
4272 case MotionEvent.ACTION_UP:
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));
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");
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.
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;
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;
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: "
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));
4334 while (movement > 0) {
4335 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: "
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));
4348 mLastTime = curTime;
4352 public void cancel(MotionEvent event) {
4353 mLastTime = Integer.MIN_VALUE;
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);
4365 * Maintains state information for a single trackball axis, generating
4366 * discrete (DPAD) movements based on raw trackball motion.
4368 static final class TrackballAxis {
4370 * The maximum amount of acceleration we will apply.
4372 static final float MAX_ACCELERATION = 20;
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.
4379 static final long FAST_MOVE_TIME = 150;
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.
4387 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
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;
4394 float acceleration = 1;
4395 long lastMoveTime = 0;
4398 int nonAccelMovement;
4400 void reset(int _step) {
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
4415 * @return Returns the absolute value of the amount of movement
4418 float collect(float off, long time, String axis) {
4421 normTime = (long)(off * FAST_MOVE_TIME);
4423 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4430 } else if (off < 0) {
4431 normTime = (long)((-off) * FAST_MOVE_TIME);
4433 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
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.
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;
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;
4470 return Math.abs(position);
4474 * Generate the number of discrete movement events appropriate for
4475 * the currently collected trackball movement.
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.
4483 nonAccelMovement = 0;
4485 final int dir = position >= 0 ? 1 : -1;
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.
4491 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4495 nonAccelMovement += dir;
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.
4502 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4506 nonAccelMovement += dir;
4507 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
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.
4518 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4522 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4523 float acc = acceleration;
4525 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4533 * Creates dpad events from unhandled joystick movements.
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;
4540 private int mLastXDirection;
4541 private int mLastYDirection;
4542 private int mLastXKeyCode;
4543 private int mLastYKeyCode;
4545 public SyntheticJoystickHandler() {
4550 public void handleMessage(Message msg) {
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());
4568 public void process(MotionEvent event) {
4569 switch(event.getActionMasked()) {
4570 case MotionEvent.ACTION_CANCEL:
4573 case MotionEvent.ACTION_MOVE:
4574 update(event, true);
4577 Log.w(TAG, "Unexpected action: " + event.getActionMasked());
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);
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();
4593 int xDirection = joystickAxisValueToDirection(
4594 event.getAxisValue(MotionEvent.AXIS_HAT_X));
4595 if (xDirection == 0) {
4596 xDirection = joystickAxisValueToDirection(event.getX());
4599 int yDirection = joystickAxisValueToDirection(
4600 event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4601 if (yDirection == 0) {
4602 yDirection = joystickAxisValueToDirection(event.getY());
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));
4614 mLastXDirection = xDirection;
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());
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));
4638 mLastYDirection = yDirection;
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());
4654 private int joystickAxisValueToDirection(float value) {
4655 if (value >= 0.5f) {
4657 } else if (value <= -0.5f) {
4666 * Creates dpad events from unhandled touch navigation movements.
4668 final class SyntheticTouchNavigationHandler extends Handler {
4669 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4670 private static final boolean LOCAL_DEBUG = false;
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;
4677 /* TODO: These constants should eventually be moved to ViewConfiguration. */
4679 // The nominal distance traveled to move by one unit.
4680 private static final int TICK_DISTANCE_MILLIMETERS = 12;
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;
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;
4698 /* The input device that we are tracking. */
4700 private int mCurrentDeviceId = -1;
4701 private int mCurrentSource;
4702 private boolean mCurrentDeviceSupported;
4704 /* Configuration for the current input device. */
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;
4710 // The minimum and maximum scaled fling velocity.
4711 private float mConfigMinFlingVelocity;
4712 private float mConfigMaxFlingVelocity;
4714 /* Tracking state. */
4716 // The velocity tracker for detecting flings.
4717 private VelocityTracker mVelocityTracker;
4719 // The active pointer id, or -1 if none.
4720 private int mActivePointerId = -1;
4722 // Location where tracking started.
4723 private float mStartX;
4724 private float mStartY;
4726 // Most recently observed position.
4727 private float mLastX;
4728 private float mLastY;
4730 // Accumulated movement delta since the last direction key was sent.
4731 private float mAccumulatedX;
4732 private float mAccumulatedY;
4734 // Set to true if any movement was delivered to the app.
4735 // Implies that tap slop was exceeded.
4736 private boolean mConsumedMovement;
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;
4746 // The current fling velocity while a fling is in progress.
4747 private boolean mFlinging;
4748 private float mFlingVelocity;
4750 public SyntheticTouchNavigationHandler() {
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) {
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;
4774 // Infer the resolution if it not actually known.
4775 float xRes = xRange.getResolution();
4777 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
4779 float yRes = yRange.getResolution();
4781 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
4783 float nominalRes = (xRes + yRes) * 0.5f;
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;
4793 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
4794 + " (" + Integer.toHexString(mCurrentSource) + "): "
4795 + ", mConfigTickDistance=" + mConfigTickDistance
4796 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
4797 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
4802 if (!mCurrentDeviceSupported) {
4806 // Handle the event.
4807 final int action = event.getActionMasked();
4809 case MotionEvent.ACTION_DOWN: {
4810 boolean caughtFling = mFlinging;
4812 finishTracking(time);
4813 mActivePointerId = event.getPointerId(0);
4814 mVelocityTracker = VelocityTracker.obtain();
4815 mVelocityTracker.addMovement(event);
4816 mStartX = event.getX();
4817 mStartY = event.getY();
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;
4829 case MotionEvent.ACTION_MOVE:
4830 case MotionEvent.ACTION_UP: {
4831 if (mActivePointerId < 0) {
4834 final int index = event.findPointerIndex(mActivePointerId);
4837 finishTracking(time);
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;
4849 // Consume any accumulated movement so far.
4850 final int metaState = event.getMetaState();
4851 consumeAccumulatedMovement(time, metaState);
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)) {
4864 finishTracking(time);
4869 case MotionEvent.ACTION_CANCEL: {
4871 finishTracking(time);
4877 public void cancel(MotionEvent event) {
4878 if (mCurrentDeviceId == event.getDeviceId()
4879 && mCurrentSource == event.getSource()) {
4880 final long time = event.getEventTime();
4882 finishTracking(time);
4886 private void finishKeys(long time) {
4891 private void finishTracking(long time) {
4892 if (mActivePointerId >= 0) {
4893 mActivePointerId = -1;
4894 mVelocityTracker.recycle();
4895 mVelocityTracker = null;
4899 private void consumeAccumulatedMovement(long time, int metaState) {
4900 final float absX = Math.abs(mAccumulatedX);
4901 final float absY = Math.abs(mAccumulatedY);
4903 if (absX >= mConfigTickDistance) {
4904 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
4905 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
4907 mConsumedMovement = true;
4910 if (absY >= mConfigTickDistance) {
4911 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
4912 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
4914 mConsumedMovement = true;
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;
4925 while (accumulator >= mConfigTickDistance) {
4926 sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
4927 accumulator -= mConfigTickDistance;
4932 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
4933 if (mPendingKeyCode != keyCode) {
4935 mPendingKeyDownTime = time;
4936 mPendingKeyCode = keyCode;
4937 mPendingKeyRepeatCount = 0;
4939 mPendingKeyRepeatCount += 1;
4941 mPendingKeyMetaState = metaState;
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.
4946 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
4947 + ", repeatCount=" + mPendingKeyRepeatCount
4948 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4950 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4951 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
4952 mPendingKeyMetaState, mCurrentDeviceId,
4953 KeyEvent.FLAG_FALLBACK, mCurrentSource));
4956 private void sendKeyUp(long time) {
4957 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
4959 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
4960 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
4962 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
4963 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
4964 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
4966 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4970 private boolean startFling(long time, float vx, float vy) {
4972 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
4973 + ", min=" + mConfigMinFlingVelocity);
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;
4986 case KeyEvent.KEYCODE_DPAD_RIGHT:
4987 if (vx >= mConfigMinFlingVelocity
4988 && Math.abs(vy) < mConfigMinFlingVelocity) {
4989 mFlingVelocity = vx;
4994 case KeyEvent.KEYCODE_DPAD_UP:
4995 if (-vy >= mConfigMinFlingVelocity
4996 && Math.abs(vx) < mConfigMinFlingVelocity) {
4997 mFlingVelocity = -vy;
5002 case KeyEvent.KEYCODE_DPAD_DOWN:
5003 if (vy >= mConfigMinFlingVelocity
5004 && Math.abs(vx) < mConfigMinFlingVelocity) {
5005 mFlingVelocity = vy;
5011 // Post the first fling event.
5012 mFlinging = postFling(time);
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);
5024 Log.d(LOCAL_TAG, "Posted fling: velocity="
5025 + mFlingVelocity + ", delay=" + delay
5026 + ", keyCode=" + mPendingKeyCode);
5033 private void cancelFling() {
5035 removeCallbacks(mFlingRunnable);
5040 private final Runnable mFlingRunnable = new Runnable() {
5043 final long time = SystemClock.uptimeMillis();
5044 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5045 mFlingVelocity *= FLING_TICK_DECAY;
5046 if (!postFling(time)) {
5054 final class SyntheticKeyboardHandler {
5055 public void process(KeyEvent event) {
5056 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5060 final KeyCharacterMap kcm = event.getKeyCharacterMap();
5061 final int keyCode = event.getKeyCode();
5062 final int metaState = event.getMetaState();
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);
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.
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:
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.
5110 private static boolean isTypingKey(KeyEvent keyEvent) {
5111 return keyEvent.getUnicodeChar() > 0;
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).
5120 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
5121 // Only relevant in touch mode.
5122 if (!mAttachInfo.mInTouchMode) {
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) {
5132 // Don't leave touch mode if the IME told us not to.
5133 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
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);
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);
5158 void setLocalDragState(Object obj) {
5159 mLocalDragState = obj;
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;
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
5174 mView.dispatchDragEvent(event);
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;
5182 event.mClipDescription = mDragDescription;
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);
5192 if (mCurScrollY != 0) {
5193 mDragPoint.offset(0, mCurScrollY);
5196 event.mX = mDragPoint.x;
5197 event.mY = mDragPoint.y;
5200 // Remember who the current drag target is pre-dispatch
5201 final View prevDragView = mCurrentDragView;
5203 // Now dispatch the drag/drop event
5204 boolean result = mView.dispatchDragEvent(event);
5206 // If we changed apparent drag target, tell the OS about it
5207 if (prevDragView != mCurrentDragView) {
5209 if (prevDragView != null) {
5210 mWindowSession.dragRecipientExited(mWindow);
5212 if (mCurrentDragView != null) {
5213 mWindowSession.dragRecipientEntered(mWindow);
5215 } catch (RemoteException e) {
5216 Slog.e(TAG, "Unable to note drag target change");
5220 // Report the drop result when we're done
5221 if (what == DragEvent.ACTION_DROP) {
5222 mDragDescription = null;
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");
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);
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.
5247 mAttachInfo.mForceReportNewAttributes = true;
5248 scheduleTraversals();
5250 if (mView == null) return;
5251 if (args.localChanges != 0) {
5252 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
5255 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5256 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5257 mAttachInfo.mGlobalSystemUiVisibility = visibility;
5258 mView.dispatchSystemUiVisibilityChanged(visibility);
5262 public void handleDispatchDoneAnimating() {
5263 if (mWindowsAnimating) {
5264 mWindowsAnimating = false;
5265 if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded) {
5266 scheduleTraversals();
5271 public void handleDispatchWindowShown() {
5272 mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5275 public void getLastTouchPoint(Point outLocation) {
5276 outLocation.x = (int) mLastTouchPoint.x;
5277 outLocation.y = (int) mLastTouchPoint.y;
5280 public void setDragFocus(View newDragTarget) {
5281 if (mCurrentDragView != newDragTarget) {
5282 mCurrentDragView = newDragTarget;
5286 private AudioManager getAudioManager() {
5287 if (mView == null) {
5288 throw new IllegalStateException("getAudioManager called when there is no mView");
5290 if (mAudioManager == null) {
5291 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5293 return mAudioManager;
5296 public AccessibilityInteractionController getAccessibilityInteractionController() {
5297 if (mView == null) {
5298 throw new IllegalStateException("getAccessibilityInteractionController"
5299 + " called when there is no mView");
5301 if (mAccessibilityInteractionController == null) {
5302 mAccessibilityInteractionController = new AccessibilityInteractionController(this);
5304 return mAccessibilityInteractionController;
5307 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5308 boolean insetsPending) throws RemoteException {
5310 float appScale = mAttachInfo.mApplicationScale;
5311 boolean restore = false;
5312 if (params != null && mTranslator != null) {
5315 mTranslator.translateWindowLayout(params);
5317 if (params != null) {
5318 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
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;
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");
5342 if (mTranslator != null) {
5343 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
5344 mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
5345 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5346 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
5347 mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
5349 return relayoutResult;
5356 public void playSoundEffect(int effectId) {
5360 final AudioManager audioManager = getAudioManager();
5363 case SoundEffectConstants.CLICK:
5364 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5366 case SoundEffectConstants.NAVIGATION_DOWN:
5367 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5369 case SoundEffectConstants.NAVIGATION_LEFT:
5370 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5372 case SoundEffectConstants.NAVIGATION_RIGHT:
5373 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5375 case SoundEffectConstants.NAVIGATION_UP:
5376 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5379 throw new IllegalArgumentException("unknown effect id " + effectId +
5380 " not defined in " + SoundEffectConstants.class.getCanonicalName());
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();
5393 public boolean performHapticFeedback(int effectId, boolean always) {
5395 return mWindowSession.performHapticFeedback(mWindow, effectId, always);
5396 } catch (RemoteException e) {
5405 public View focusSearch(View focused, int direction) {
5407 if (!(mView instanceof ViewGroup)) {
5410 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5413 public void debug() {
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(")");
5437 mFirstInputStage.dump(innerPrefix, writer);
5439 mChoreographer.dump(prefix, writer);
5441 writer.print(prefix); writer.println("View Hierarchy:");
5442 dumpViewHierarchy(innerPrefix, writer, mView);
5445 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5446 writer.print(prefix);
5448 writer.println("null");
5451 writer.println(view.toString());
5452 if (!(view instanceof ViewGroup)) {
5455 ViewGroup grp = (ViewGroup)view;
5456 final int N = grp.getChildCount();
5460 prefix = prefix + " ";
5461 for (int i=0; i<N; i++) {
5462 dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5466 public void dumpGfxInfo(int[] info) {
5467 info[0] = info[1] = 0;
5468 if (mView != null) {
5469 getGfxInfo(mView, info);
5473 private static void getGfxInfo(View view, int[] info) {
5474 RenderNode renderNode = view.mRenderNode;
5476 if (renderNode != null) {
5477 info[1] += renderNode.getDebugSize();
5480 if (view instanceof ViewGroup) {
5481 ViewGroup group = (ViewGroup) view;
5483 int count = group.getChildCount();
5484 for (int i = 0; i < count; i++) {
5485 getGfxInfo(group.getChildAt(i), info);
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.
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) {
5503 destroyHardwareRenderer();
5505 Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
5506 " window=" + this + ", title=" + mWindowAttributes.getTitle());
5508 mHandler.sendEmptyMessage(MSG_DIE);
5514 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
5515 synchronized (this) {
5521 dispatchDetachedFromWindow();
5524 if (mAdded && !mFirst) {
5525 destroyHardwareRenderer();
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
5535 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5536 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5537 mWindowSession.finishDrawing(mWindow);
5539 } catch (RemoteException e) {
5549 WindowManagerGlobal.getInstance().doRemoveView(this);
5552 public void requestUpdateConfiguration(Configuration config) {
5553 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5554 mHandler.sendMessage(msg);
5557 public void loadSystemProperties() {
5558 mHandler.post(new Runnable() {
5562 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5563 profileRendering(mAttachInfo.mHasWindowFocus);
5565 // Hardware rendering
5566 if (mAttachInfo.mHardwareRenderer != null) {
5567 if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
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);
5584 private void destroyHardwareRenderer() {
5585 HardwareRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
5587 if (hardwareRenderer != null) {
5588 if (mView != null) {
5589 hardwareRenderer.destroyHardwareResources(mView);
5591 hardwareRenderer.destroy();
5592 hardwareRenderer.setRequested(false);
5594 mAttachInfo.mHardwareRenderer = null;
5595 mAttachInfo.mHardwareAccelerated = false;
5599 public void dispatchFinishInputConnection(InputConnection connection) {
5600 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
5601 mHandler.sendMessage(msg);
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);
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;
5626 mHandler.sendMessage(msg);
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);
5637 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5638 mHandler.sendMessage(msg);
5642 * Represents a pending input event that is waiting in a queue.
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.
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.
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;
5661 public QueuedInputEvent mNext;
5663 public InputEvent mEvent;
5664 public InputEventReceiver mReceiver;
5667 public boolean shouldSkipIme() {
5668 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5671 return mEvent instanceof MotionEvent
5672 && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5675 public boolean shouldSendToSynthesizer() {
5676 if ((mFlags & FLAG_UNHANDLED) != 0) {
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);
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();
5702 private boolean flagToString(String name, int flag,
5703 boolean hasPrevious, StringBuilder sb) {
5704 if ((mFlags & flag) != 0) {
5715 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
5716 InputEventReceiver receiver, int flags) {
5717 QueuedInputEvent q = mQueuedInputEventPool;
5719 mQueuedInputEventPoolSize -= 1;
5720 mQueuedInputEventPool = q.mNext;
5723 q = new QueuedInputEvent();
5727 q.mReceiver = receiver;
5732 private void recycleQueuedInputEvent(QueuedInputEvent q) {
5736 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
5737 mQueuedInputEventPoolSize += 1;
5738 q.mNext = mQueuedInputEventPool;
5739 mQueuedInputEventPool = q;
5743 void enqueueInputEvent(InputEvent event) {
5744 enqueueInputEvent(event, null, 0, false);
5747 void enqueueInputEvent(InputEvent event,
5748 InputEventReceiver receiver, int flags, boolean processImmediately) {
5749 adjustInputEventForCompatibility(event);
5750 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
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;
5759 mPendingInputEventHead = q;
5760 mPendingInputEventTail = q;
5763 mPendingInputEventTail = q;
5765 mPendingInputEventCount += 1;
5766 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5767 mPendingInputEventCount);
5769 if (processImmediately) {
5770 doProcessInputEvents();
5772 scheduleProcessInputEvents();
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);
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;
5795 mPendingInputEventCount -= 1;
5796 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
5797 mPendingInputEventCount);
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);
5807 mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);
5809 deliverInputEvent(q);
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);
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);
5828 if (q.shouldSendToSynthesizer()) {
5829 stage = mSyntheticInputStage;
5831 stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
5834 if (stage != null) {
5837 finishInputEvent(q);
5841 private void finishInputEvent(QueuedInputEvent q) {
5842 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
5843 q.mEvent.getSequenceNumber());
5845 if (q.mReceiver != null) {
5846 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
5847 q.mReceiver.finishInputEvent(q.mEvent, handled);
5849 q.mEvent.recycleIfNeededAfterDispatch();
5852 recycleQueuedInputEvent(q);
5855 private void adjustInputEventForCompatibility(InputEvent e) {
5856 if (mTargetSdkVersion < Build.VERSION_CODES.MNC && e instanceof MotionEvent) {
5857 MotionEvent motion = (MotionEvent) e;
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);
5868 static boolean isTerminalInputEvent(InputEvent event) {
5869 if (event instanceof KeyEvent) {
5870 final KeyEvent keyEvent = (KeyEvent)event;
5871 return keyEvent.getAction() == KeyEvent.ACTION_UP;
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;
5881 void scheduleConsumeBatchedInput() {
5882 if (!mConsumeBatchedInputScheduled) {
5883 mConsumeBatchedInputScheduled = true;
5884 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
5885 mConsumedBatchedInputRunnable, null);
5889 void unscheduleConsumeBatchedInput() {
5890 if (mConsumeBatchedInputScheduled) {
5891 mConsumeBatchedInputScheduled = false;
5892 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
5893 mConsumedBatchedInputRunnable, null);
5897 void scheduleConsumeBatchedInputImmediately() {
5898 if (!mConsumeBatchedInputImmediatelyScheduled) {
5899 unscheduleConsumeBatchedInput();
5900 mConsumeBatchedInputImmediatelyScheduled = true;
5901 mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
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();
5919 doProcessInputEvents();
5923 final class TraversalRunnable implements Runnable {
5929 final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
5931 final class WindowInputEventReceiver extends InputEventReceiver {
5932 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
5933 super(inputChannel, looper);
5937 public void onInputEvent(InputEvent event) {
5938 enqueueInputEvent(event, this, 0, true);
5942 public void onBatchedInputEventPending() {
5943 if (mUnbufferedInputDispatch) {
5944 super.onBatchedInputEventPending();
5946 scheduleConsumeBatchedInput();
5951 public void dispose() {
5952 unscheduleConsumeBatchedInput();
5956 WindowInputEventReceiver mInputEventReceiver;
5958 final class ConsumeBatchedInputRunnable implements Runnable {
5961 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
5964 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
5965 new ConsumeBatchedInputRunnable();
5966 boolean mConsumeBatchedInputScheduled;
5968 final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
5971 doConsumeBatchedInput(-1);
5974 final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
5975 new ConsumeBatchedInputImmediatelyRunnable();
5976 boolean mConsumeBatchedInputImmediatelyScheduled;
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;
5986 public void addView(View view) {
5987 synchronized (this) {
5989 postIfNeededLocked();
5993 public void addViewRect(AttachInfo.InvalidateInfo info) {
5994 synchronized (this) {
5995 mViewRects.add(info);
5996 postIfNeededLocked();
6000 public void removeView(View view) {
6001 synchronized (this) {
6002 mViews.remove(view);
6004 for (int i = mViewRects.size(); i-- > 0; ) {
6005 AttachInfo.InvalidateInfo info = mViewRects.get(i);
6006 if (info.target == view) {
6007 mViewRects.remove(i);
6012 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
6013 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
6021 final int viewCount;
6022 final int viewRectCount;
6023 synchronized (this) {
6026 viewCount = mViews.size();
6027 if (viewCount != 0) {
6028 mTempViews = mViews.toArray(mTempViews != null
6029 ? mTempViews : new View[viewCount]);
6033 viewRectCount = mViewRects.size();
6034 if (viewRectCount != 0) {
6035 mTempViewRects = mViewRects.toArray(mTempViewRects != null
6036 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6041 for (int i = 0; i < viewCount; i++) {
6042 mTempViews[i].invalidate();
6043 mTempViews[i] = null;
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);
6053 private void postIfNeededLocked() {
6055 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
6060 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6061 new InvalidateOnAnimationRunnable();
6063 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6064 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6065 mHandler.sendMessageDelayed(msg, delayMilliseconds);
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);
6074 public void dispatchInvalidateOnAnimation(View view) {
6075 mInvalidateOnAnimationRunnable.addView(view);
6078 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6079 mInvalidateOnAnimationRunnable.addViewRect(info);
6082 public void cancelInvalidate(View view) {
6083 mHandler.removeMessages(MSG_INVALIDATE, view);
6084 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6086 mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6087 mInvalidateOnAnimationRunnable.removeView(view);
6090 public void dispatchInputEvent(InputEvent event) {
6091 dispatchInputEvent(event, null);
6094 public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6095 SomeArgs args = SomeArgs.obtain();
6097 args.arg2 = receiver;
6098 Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
6099 msg.setAsynchronous(true);
6100 mHandler.sendMessage(msg);
6103 public void synthesizeInputEvent(InputEvent event) {
6104 Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6105 msg.setAsynchronous(true);
6106 mHandler.sendMessage(msg);
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);
6116 * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6118 * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6121 public void dispatchUnhandledInputEvent(InputEvent event) {
6122 if (event instanceof MotionEvent) {
6123 event = MotionEvent.obtain((MotionEvent) event);
6125 synthesizeInputEvent(event);
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);
6134 public void dispatchGetNewSurface() {
6135 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6136 mHandler.sendMessage(msg);
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);
6147 public void dispatchWindowShown() {
6148 mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6151 public void dispatchCloseSystemDialogs(String reason) {
6152 Message msg = Message.obtain();
6153 msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
6155 mHandler.sendMessage(msg);
6158 public void dispatchDragEvent(DragEvent event) {
6160 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
6161 what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6162 mHandler.removeMessages(what);
6164 what = MSG_DISPATCH_DRAG_EVENT;
6166 Message msg = mHandler.obtainMessage(what, event);
6167 mHandler.sendMessage(msg);
6170 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6171 int localValue, int localChanges) {
6172 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6174 args.globalVisibility = globalVisibility;
6175 args.localValue = localValue;
6176 args.localChanges = localChanges;
6177 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6180 public void dispatchDoneAnimating() {
6181 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
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);
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()}.
6197 private void postSendWindowContentChangedCallback(View source, int changeType) {
6198 if (mSendWindowContentChangedAccessibilityEvent == null) {
6199 mSendWindowContentChangedAccessibilityEvent =
6200 new SendWindowContentChangedAccessibilityEvent();
6202 mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
6206 * Remove a posted callback to send a
6207 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6209 private void removeSendWindowContentChangedCallback() {
6210 if (mSendWindowContentChangedAccessibilityEvent != null) {
6211 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
6216 public boolean showContextMenuForChild(View originalView) {
6221 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6226 public ActionMode startActionModeForChild(
6227 View originalView, ActionMode.Callback callback, int type) {
6232 public void createContextMenu(ContextMenu menu) {
6236 public void childDrawableStateChanged(View child) {
6240 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
6241 if (mView == null) {
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(
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(
6258 final AccessibilityNodeInfo node;
6259 if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6260 node = provider.createAccessibilityNodeInfo(
6261 AccessibilityNodeProvider.HOST_VIEW_ID);
6263 node = provider.createAccessibilityNodeInfo(virtualNodeId);
6265 setAccessibilityFocus(source, node);
6269 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
6270 final long sourceNodeId = event.getSourceNodeId();
6271 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6273 View source = mView.findViewByAccessibilityId(accessibilityViewId);
6274 if (source != null) {
6275 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6276 if (provider != null) {
6277 setAccessibilityFocus(null, null);
6283 case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
6284 handleWindowContentChangedEvent(event);
6287 mAccessibilityManager.sendAccessibilityEvent(event);
6292 * Updates the focused virtual view, when necessary, in response to a
6293 * content changed event.
6295 * This is necessary to get updated bounds after a position change.
6297 * @param event an accessibility event of type
6298 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
6300 private void handleWindowContentChangedEvent(AccessibilityEvent event) {
6301 // No virtual view focused, nothing to do here.
6302 if (mAccessibilityFocusedHost == null || mAccessibilityFocusedVirtualView == null) {
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?
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) {
6322 final long eventSourceNodeId = event.getSourceNodeId();
6323 final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId);
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;
6332 final ViewParent parent = root.getParent();
6333 if (parent instanceof View) {
6334 root = (View) parent;
6341 // We care only about changes in subtrees containing the host view.
6342 if (!hostInSubtree) {
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;
6353 // Refresh the node for the focused virtual view.
6354 mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId);
6358 public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6359 postSendWindowContentChangedCallback(source, changeType);
6363 public boolean canResolveLayoutDirection() {
6368 public boolean isLayoutDirectionResolved() {
6373 public int getLayoutDirection() {
6374 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6378 public boolean canResolveTextDirection() {
6383 public boolean isTextDirectionResolved() {
6388 public int getTextDirection() {
6389 return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6393 public boolean canResolveTextAlignment() {
6398 public boolean isTextAlignmentResolved() {
6403 public int getTextAlignment() {
6404 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6407 private View getCommonPredecessor(View first, View second) {
6408 if (mTempHashSet == null) {
6409 mTempHashSet = new HashSet<View>();
6411 HashSet<View> seen = mTempHashSet;
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;
6420 firstCurrent = null;
6423 View secondCurrent = second;
6424 while (secondCurrent != null) {
6425 if (seen.contains(secondCurrent)) {
6427 return secondCurrent;
6429 ViewParent secondCurrentParent = secondCurrent.mParent;
6430 if (secondCurrentParent instanceof View) {
6431 secondCurrent = (View) secondCurrentParent;
6433 secondCurrent = null;
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.");
6448 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
6449 // ViewAncestor never intercepts touch event, so this can be a no-op
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);
6460 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6461 } catch (RemoteException re) {
6469 public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6474 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6479 public void onStopNestedScroll(View target) {
6483 public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6487 public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6488 int dxUnconsumed, int dyUnconsumed) {
6492 public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6496 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6501 public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6506 public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6510 void changeCanvasOpacity(boolean opaque) {
6511 Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque);
6512 if (mAttachInfo.mHardwareRenderer != null) {
6513 mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6517 class TakenSurfaceHolder extends BaseSurfaceHolder {
6519 public boolean onAllowLockCanvas() {
6520 return mDrawingAllowed;
6524 public void onRelayoutContainer() {
6525 // Not currently interesting -- from changing between fixed and layout size.
6529 public void setFormat(int format) {
6530 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6534 public void setType(int type) {
6535 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6539 public void onUpdateSurface() {
6540 // We take care of format and type changes on our own.
6541 throw new IllegalStateException("Shouldn't be here");
6545 public boolean isCreating() {
6550 public void setFixedSize(int width, int height) {
6551 throw new UnsupportedOperationException(
6552 "Currently only support sizing from layout");
6556 public void setKeepScreenOn(boolean screenOn) {
6557 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6561 static class W extends IWindow.Stub {
6562 private final WeakReference<ViewRootImpl> mViewAncestor;
6563 private final IWindowSession mWindowSession;
6565 W(ViewRootImpl viewAncestor) {
6566 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
6567 mWindowSession = viewAncestor.mWindowSession;
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);
6582 public void moved(int newX, int newY) {
6583 final ViewRootImpl viewAncestor = mViewAncestor.get();
6584 if (viewAncestor != null) {
6585 viewAncestor.dispatchMoved(newX, newY);
6590 public void dispatchAppVisibility(boolean visible) {
6591 final ViewRootImpl viewAncestor = mViewAncestor.get();
6592 if (viewAncestor != null) {
6593 viewAncestor.dispatchAppVisibility(visible);
6598 public void dispatchGetNewSurface() {
6599 final ViewRootImpl viewAncestor = mViewAncestor.get();
6600 if (viewAncestor != null) {
6601 viewAncestor.dispatchGetNewSurface();
6606 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6607 final ViewRootImpl viewAncestor = mViewAncestor.get();
6608 if (viewAncestor != null) {
6609 viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
6613 private static int checkCallingPermission(String permission) {
6615 return ActivityManagerNative.getDefault().checkPermission(
6616 permission, Binder.getCallingPid(), Binder.getCallingUid());
6617 } catch (RemoteException e) {
6618 return PackageManager.PERMISSION_DENIED;
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;
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());
6635 OutputStream clientStream = null;
6637 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
6638 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
6639 } catch (IOException e) {
6640 e.printStackTrace();
6642 if (clientStream != null) {
6644 clientStream.close();
6645 } catch (IOException e) {
6646 e.printStackTrace();
6655 public void closeSystemDialogs(String reason) {
6656 final ViewRootImpl viewAncestor = mViewAncestor.get();
6657 if (viewAncestor != null) {
6658 viewAncestor.dispatchCloseSystemDialogs(reason);
6663 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
6667 mWindowSession.wallpaperOffsetsComplete(asBinder());
6668 } catch (RemoteException e) {
6674 public void dispatchWallpaperCommand(String action, int x, int y,
6675 int z, Bundle extras, boolean sync) {
6678 mWindowSession.wallpaperCommandComplete(asBinder(), null);
6679 } catch (RemoteException e) {
6686 public void dispatchDragEvent(DragEvent event) {
6687 final ViewRootImpl viewAncestor = mViewAncestor.get();
6688 if (viewAncestor != null) {
6689 viewAncestor.dispatchDragEvent(event);
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);
6704 public void doneAnimating() {
6705 final ViewRootImpl viewAncestor = mViewAncestor.get();
6706 if (viewAncestor != null) {
6707 viewAncestor.dispatchDoneAnimating();
6712 public void dispatchWindowShown() {
6713 final ViewRootImpl viewAncestor = mViewAncestor.get();
6714 if (viewAncestor != null) {
6715 viewAncestor.dispatchWindowShown();
6720 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
6721 public CalledFromWrongThreadException(String msg) {
6726 static RunQueue getRunQueue() {
6727 RunQueue rq = sRunQueues.get();
6731 rq = new RunQueue();
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
6742 static final class RunQueue {
6743 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
6745 void post(Runnable action) {
6746 postDelayed(action, 0);
6749 void postDelayed(Runnable action, long delayMillis) {
6750 HandlerAction handlerAction = new HandlerAction();
6751 handlerAction.action = action;
6752 handlerAction.delay = delayMillis;
6754 synchronized (mActions) {
6755 mActions.add(handlerAction);
6759 void removeCallbacks(Runnable action) {
6760 final HandlerAction handlerAction = new HandlerAction();
6761 handlerAction.action = action;
6763 synchronized (mActions) {
6764 final ArrayList<HandlerAction> actions = mActions;
6766 while (actions.remove(handlerAction)) {
6772 void executeActions(Handler handler) {
6773 synchronized (mActions) {
6774 final ArrayList<HandlerAction> actions = mActions;
6775 final int count = actions.size();
6777 for (int i = 0; i < count; i++) {
6778 final HandlerAction handlerAction = actions.get(i);
6779 handler.postDelayed(handlerAction.action, handlerAction.delay);
6786 private static class HandlerAction {
6791 public boolean equals(Object o) {
6792 if (this == o) return true;
6793 if (o == null || getClass() != o.getClass()) return false;
6795 HandlerAction that = (HandlerAction) o;
6796 return !(action != null ? !action.equals(that.action) : that.action != null);
6801 public int hashCode() {
6802 int result = action != null ? action.hashCode() : 0;
6803 result = 31 * result + (int) (delay ^ (delay >>> 32));
6810 * Class for managing the accessibility interaction connection
6811 * based on the global accessibility state.
6813 final class AccessibilityInteractionConnectionManager
6814 implements AccessibilityStateChangeListener {
6816 public void onAccessibilityStateChanged(boolean enabled) {
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);
6827 ensureNoConnection();
6828 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
6832 public void ensureConnection() {
6833 final boolean registered =
6834 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6836 mAttachInfo.mAccessibilityWindowId =
6837 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
6838 new AccessibilityInteractionConnection(ViewRootImpl.this));
6842 public void ensureNoConnection() {
6843 final boolean registered =
6844 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6846 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6847 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
6852 final class HighContrastTextManager implements HighTextContrastChangeListener {
6853 HighContrastTextManager() {
6854 mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
6857 public void onHighTextContrastStateChanged(boolean enabled) {
6858 mAttachInfo.mHighContrastText = enabled;
6860 // Destroy Displaylists so they can be recreated with high contrast recordings
6861 destroyHardwareResources();
6863 // Schedule redraw, which will rerecord + redraw all text
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.
6873 static final class AccessibilityInteractionConnection
6874 extends IAccessibilityInteractionConnection.Stub {
6875 private final WeakReference<ViewRootImpl> mViewRootImpl;
6877 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
6878 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
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);
6893 // We cannot make the call and notify the caller so it does not wait.
6895 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6896 } catch (RemoteException re) {
6897 /* best effort - ignore */
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);
6913 // We cannot make the call and notify the caller so it does not wait.
6915 callback.setPerformAccessibilityActionResult(false, interactionId);
6916 } catch (RemoteException re) {
6917 /* best effort - ignore */
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);
6934 // We cannot make the call and notify the caller so it does not wait.
6936 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6937 } catch (RemoteException re) {
6938 /* best effort - ignore */
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);
6955 // We cannot make the call and notify the caller so it does not wait.
6957 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
6958 } catch (RemoteException re) {
6959 /* best effort - ignore */
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,
6975 // We cannot make the call and notify the caller so it does not wait.
6977 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6978 } catch (RemoteException re) {
6979 /* best effort - ignore */
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,
6995 // We cannot make the call and notify the caller so it does not wait.
6997 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
6998 } catch (RemoteException re) {
6999 /* best effort - ignore */
7005 private class SendWindowContentChangedAccessibilityEvent implements Runnable {
7006 private int mChangeTypes = 0;
7008 public View mSource;
7009 public long mLastEventTimeMillis;
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);
7021 mLastEventTimeMillis = 0;
7023 // In any case reset to initial state.
7024 mSource.resetSubtreeAccessibilityStateChanged();
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;
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);
7047 mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);