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.ComponentCallbacks2;
25 import android.content.Context;
26 import android.content.pm.ApplicationInfo;
27 import android.content.pm.PackageManager;
28 import android.content.res.CompatibilityInfo;
29 import android.content.res.Configuration;
30 import android.content.res.Resources;
31 import android.graphics.Canvas;
32 import android.graphics.Paint;
33 import android.graphics.PixelFormat;
34 import android.graphics.Point;
35 import android.graphics.PointF;
36 import android.graphics.PorterDuff;
37 import android.graphics.Rect;
38 import android.graphics.Region;
39 import android.graphics.drawable.Drawable;
40 import android.media.AudioManager;
41 import android.os.Binder;
42 import android.os.Bundle;
43 import android.os.Debug;
44 import android.os.Handler;
45 import android.os.LatencyTimer;
46 import android.os.Looper;
47 import android.os.Message;
48 import android.os.ParcelFileDescriptor;
49 import android.os.PowerManager;
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.TypedValue;
60 import android.view.View.AttachInfo;
61 import android.view.View.MeasureSpec;
62 import android.view.accessibility.AccessibilityEvent;
63 import android.view.accessibility.AccessibilityManager;
64 import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
65 import android.view.accessibility.AccessibilityNodeInfo;
66 import android.view.accessibility.AccessibilityNodeProvider;
67 import android.view.accessibility.IAccessibilityInteractionConnection;
68 import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
69 import android.view.animation.AccelerateDecelerateInterpolator;
70 import android.view.animation.Interpolator;
71 import android.view.inputmethod.InputConnection;
72 import android.view.inputmethod.InputMethodManager;
73 import android.widget.Scroller;
75 import com.android.internal.R;
76 import com.android.internal.os.SomeArgs;
77 import com.android.internal.policy.PolicyManager;
78 import com.android.internal.view.BaseSurfaceHolder;
79 import com.android.internal.view.RootViewSurfaceTaker;
81 import java.io.IOException;
82 import java.io.OutputStream;
83 import java.lang.ref.WeakReference;
84 import java.util.ArrayList;
85 import java.util.HashSet;
88 * The top of a view hierarchy, implementing the needed protocol between View
89 * and the WindowManager. This is for the most part an internal implementation
90 * detail of {@link WindowManagerGlobal}.
94 @SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
95 public final class ViewRootImpl implements ViewParent,
96 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
97 private static final String TAG = "ViewRootImpl";
98 private static final boolean DBG = false;
99 private static final boolean LOCAL_LOGV = false;
100 /** @noinspection PointlessBooleanExpression*/
101 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
102 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
103 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
104 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
105 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
106 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
107 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
108 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
109 private static final boolean DEBUG_FPS = false;
111 private static final boolean USE_RENDER_THREAD = false;
114 * Set this system property to true to force the view hierarchy to render
115 * at 60 Hz. This can be used to measure the potential framerate.
117 private static final String PROPERTY_PROFILE_RENDERING = "viewancestor.profile_rendering";
119 private static final boolean MEASURE_LATENCY = false;
120 private static LatencyTimer lt;
123 * Maximum time we allow the user to roll the trackball enough to generate
124 * a key event, before resetting the counters.
126 static final int MAX_TRACKBALL_DELAY = 250;
128 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
130 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
131 static boolean sFirstDrawComplete = false;
133 static final ArrayList<ComponentCallbacks> sConfigCallbacks
134 = new ArrayList<ComponentCallbacks>();
136 private static boolean sUseRenderThread = false;
137 private static boolean sRenderThreadQueried = false;
138 private static final Object[] sRenderThreadQueryLock = new Object[0];
140 final IWindowSession mWindowSession;
141 final Display mDisplay;
143 long mLastTrackballTime = 0;
144 final TrackballAxis mTrackballAxisX = new TrackballAxis();
145 final TrackballAxis mTrackballAxisY = new TrackballAxis();
147 final SimulatedTrackball mSimulatedTrackball;
149 int mLastJoystickXDirection;
150 int mLastJoystickYDirection;
151 int mLastJoystickXKeyCode;
152 int mLastJoystickYKeyCode;
154 final int[] mTmpLocation = new int[2];
156 final TypedValue mTmpValue = new TypedValue();
158 final InputMethodCallback mInputMethodCallback;
159 final Thread mThread;
161 final WindowLeaked mLocation;
163 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
167 final int mTargetSdkVersion;
173 View mRealFocusedView; // this is not set to null in touch mode
174 View mOldFocusedView;
176 View mAccessibilityFocusedHost;
177 AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
180 boolean mAppVisible = true;
181 int mOrigWindowType = -1;
183 // Set to true if the owner of this window is in the stopped state,
184 // so the window should no longer be active.
185 boolean mStopped = false;
187 boolean mLastInCompatMode = false;
189 SurfaceHolder.Callback2 mSurfaceHolderCallback;
190 BaseSurfaceHolder mSurfaceHolder;
192 boolean mDrawingAllowed;
194 final Region mTransparentRegion;
195 final Region mPreviousTransparentRegion;
200 final Rect mCurrentDirty = new Rect();
201 final Rect mPreviousDirty = new Rect();
202 boolean mIsAnimating;
204 CompatibilityInfo.Translator mTranslator;
206 final View.AttachInfo mAttachInfo;
207 InputChannel mInputChannel;
208 InputQueue.Callback mInputQueueCallback;
209 InputQueue mInputQueue;
210 FallbackEventHandler mFallbackEventHandler;
211 Choreographer mChoreographer;
213 final Rect mTempRect; // used in the transaction to not thrash the heap.
214 final Rect mVisRect; // used to retrieve visible rect of focused view.
216 boolean mTraversalScheduled;
217 int mTraversalBarrier;
218 boolean mWillDrawSoon;
219 /** Set to true while in performTraversals for detecting when die(true) is called from internal
220 * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
221 boolean mIsInTraversal;
222 boolean mFitSystemWindowsRequested;
223 boolean mLayoutRequested;
225 boolean mReportNextDraw;
226 boolean mFullRedrawNeeded;
227 boolean mNewSurfaceNeeded;
228 boolean mHasHadWindowFocus;
229 boolean mLastWasImTarget;
230 boolean mWindowsAnimating;
232 int mLastSystemUiVisibility;
233 int mClientWindowLayoutFlags;
236 public static final int EVENT_NOT_HANDLED = 0;
238 public static final int EVENT_HANDLED = 1;
240 public static final int EVENT_IN_PROGRESS = 2;
242 // Pool of queued input events.
243 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
244 private QueuedInputEvent mQueuedInputEventPool;
245 private int mQueuedInputEventPoolSize;
247 // Input event queue.
248 QueuedInputEvent mFirstPendingInputEvent;
249 QueuedInputEvent mCurrentInputEvent;
250 boolean mProcessInputEventsScheduled;
252 boolean mWindowAttributesChanged = false;
253 int mWindowAttributesChangesFlag = 0;
255 // These can be accessed by any thread, must be protected with a lock.
256 // Surface can never be reassigned or cleared (use Surface.clear()).
257 private final Surface mSurface = new Surface();
260 boolean mAddedTouchMode;
262 final CompatibilityInfoHolder mCompatibilityInfo;
264 // These are accessed by multiple threads.
265 final Rect mWinFrame; // frame given by window manager.
267 final Rect mPendingVisibleInsets = new Rect();
268 final Rect mPendingContentInsets = new Rect();
269 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
270 = new ViewTreeObserver.InternalInsetsInfo();
272 final Rect mFitSystemWindowsInsets = new Rect();
274 final Configuration mLastConfiguration = new Configuration();
275 final Configuration mPendingConfiguration = new Configuration();
277 boolean mScrollMayChange;
279 View mLastScrolledFocus;
283 HardwareLayer mResizeBuffer;
284 long mResizeBufferStartTime;
285 int mResizeBufferDuration;
286 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
287 private ArrayList<LayoutTransition> mPendingTransitions;
289 final ViewConfiguration mViewConfiguration;
292 ClipDescription mDragDescription;
293 View mCurrentDragView;
294 volatile Object mLocalDragState;
295 final PointF mDragPoint = new PointF();
296 final PointF mLastTouchPoint = new PointF();
298 private boolean mProfileRendering;
299 private Choreographer.FrameCallback mRenderProfiler;
300 private boolean mRenderProfilingEnabled;
302 // Variables to track frames per second, enabled via DEBUG_FPS flag
303 private long mFpsStartTime = -1;
304 private long mFpsPrevTime = -1;
305 private int mFpsNumFrames;
307 private final ArrayList<DisplayList> mDisplayLists = new ArrayList<DisplayList>();
310 * see {@link #playSoundEffect(int)}
312 AudioManager mAudioManager;
314 final AccessibilityManager mAccessibilityManager;
316 AccessibilityInteractionController mAccessibilityInteractionController;
318 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
320 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
322 HashSet<View> mTempHashSet;
324 private final int mDensity;
325 private final int mNoncompatDensity;
327 private boolean mInLayout = false;
328 ArrayList<View> mLayoutRequesters = new ArrayList<View>();
329 boolean mHandlingLayoutInLayoutRequest = false;
331 private int mViewLayoutDirectionInitial;
334 * Consistency verifier for debugging purposes.
336 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
337 InputEventConsistencyVerifier.isInstrumentationEnabled() ?
338 new InputEventConsistencyVerifier(this, 0) : null;
340 static final class SystemUiVisibilityInfo {
342 int globalVisibility;
347 public ViewRootImpl(Context context, Display display) {
350 if (MEASURE_LATENCY) {
352 lt = new LatencyTimer(100, 1000);
356 // Initialize the statics when this class is first instantiated. This is
357 // done here instead of in the static block because Zygote does not
358 // allow the spawning of threads.
359 mWindowSession = WindowManagerGlobal.getWindowSession(context.getMainLooper());
362 CompatibilityInfoHolder cih = display.getCompatibilityInfo();
363 mCompatibilityInfo = cih != null ? cih : new CompatibilityInfoHolder();
365 mThread = Thread.currentThread();
366 mLocation = new WindowLeaked(null);
367 mLocation.fillInStackTrace();
371 mTempRect = new Rect();
372 mVisRect = new Rect();
373 mWinFrame = new Rect();
374 mWindow = new W(this);
375 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
376 mInputMethodCallback = new InputMethodCallback(this);
377 mViewVisibility = View.GONE;
378 mTransparentRegion = new Region();
379 mPreviousTransparentRegion = new Region();
380 mFirst = true; // true for the first time the view is added
382 mAccessibilityManager = AccessibilityManager.getInstance(context);
383 mAccessibilityInteractionConnectionManager =
384 new AccessibilityInteractionConnectionManager();
385 mAccessibilityManager.addAccessibilityStateChangeListener(
386 mAccessibilityInteractionConnectionManager);
387 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
388 mViewConfiguration = ViewConfiguration.get(context);
389 mDensity = context.getResources().getDisplayMetrics().densityDpi;
390 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
391 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
392 mChoreographer = Choreographer.getInstance();
394 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
395 mAttachInfo.mScreenOn = powerManager.isScreenOn();
396 loadSystemProperties();
397 mSimulatedTrackball = new SimulatedTrackball(context);
401 * @return True if the application requests the use of a separate render thread,
404 private static boolean isRenderThreadRequested(Context context) {
405 if (USE_RENDER_THREAD) {
406 synchronized (sRenderThreadQueryLock) {
407 if (!sRenderThreadQueried) {
408 final PackageManager packageManager = context.getPackageManager();
409 final String packageName = context.getApplicationInfo().packageName;
411 ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName,
412 PackageManager.GET_META_DATA);
413 if (applicationInfo.metaData != null) {
414 sUseRenderThread = applicationInfo.metaData.getBoolean(
415 "android.graphics.renderThread", false);
417 } catch (PackageManager.NameNotFoundException e) {
419 sRenderThreadQueried = true;
422 return sUseRenderThread;
429 public static void addFirstDrawHandler(Runnable callback) {
430 synchronized (sFirstDrawHandlers) {
431 if (!sFirstDrawComplete) {
432 sFirstDrawHandlers.add(callback);
437 public static void addConfigCallback(ComponentCallbacks callback) {
438 synchronized (sConfigCallbacks) {
439 sConfigCallbacks.add(callback);
443 // FIXME for perf testing only
444 private boolean mProfile = false;
447 * Call this to profile the next traversal call.
448 * FIXME for perf testing only. Remove eventually
450 public void profile() {
455 * Indicates whether we are in touch mode. Calling this method triggers an IPC
456 * call and should be avoided whenever possible.
458 * @return True, if the device is in touch mode, false otherwise.
462 static boolean isInTouchMode() {
463 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
464 if (windowSession != null) {
466 return windowSession.getInTouchMode();
467 } catch (RemoteException e) {
476 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
477 synchronized (this) {
480 mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
481 mFallbackEventHandler.setView(view);
482 mWindowAttributes.copyFrom(attrs);
483 attrs = mWindowAttributes;
484 // Keep track of the actual window flags supplied by the client.
485 mClientWindowLayoutFlags = attrs.flags;
487 setAccessibilityFocus(null, null);
489 if (view instanceof RootViewSurfaceTaker) {
490 mSurfaceHolderCallback =
491 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
492 if (mSurfaceHolderCallback != null) {
493 mSurfaceHolder = new TakenSurfaceHolder();
494 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
498 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
499 mTranslator = compatibilityInfo.getTranslator();
501 // If the application owns the surface, don't enable hardware acceleration
502 if (mSurfaceHolder == null) {
503 enableHardwareAcceleration(mView.getContext(), attrs);
506 boolean restore = false;
507 if (mTranslator != null) {
508 mSurface.setCompatibilityTranslator(mTranslator);
511 mTranslator.translateWindowLayout(attrs);
513 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
515 if (!compatibilityInfo.supportsScreen()) {
516 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
517 mLastInCompatMode = true;
520 mSoftInputMode = attrs.softInputMode;
521 mWindowAttributesChanged = true;
522 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
523 mAttachInfo.mRootView = view;
524 mAttachInfo.mScalingRequired = mTranslator != null;
525 mAttachInfo.mApplicationScale =
526 mTranslator == null ? 1.0f : mTranslator.applicationScale;
527 if (panelParentView != null) {
528 mAttachInfo.mPanelParentWindowToken
529 = panelParentView.getApplicationWindowToken();
532 int res; /* = WindowManagerImpl.ADD_OKAY; */
534 // Schedule the first layout -before- adding to the window
535 // manager, to make sure we do the relayout before receiving
536 // any other events from the system.
538 if ((mWindowAttributes.inputFeatures
539 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
540 mInputChannel = new InputChannel();
543 mOrigWindowType = mWindowAttributes.type;
544 mAttachInfo.mRecomputeGlobalAttributes = true;
545 collectViewAttributes();
546 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
547 getHostVisibility(), mDisplay.getDisplayId(),
548 mAttachInfo.mContentInsets, mInputChannel);
549 } catch (RemoteException e) {
552 mAttachInfo.mRootView = null;
553 mInputChannel = null;
554 mFallbackEventHandler.setView(null);
555 unscheduleTraversals();
556 setAccessibilityFocus(null, null);
557 throw new RuntimeException("Adding window failed", e);
564 if (mTranslator != null) {
565 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
567 mPendingContentInsets.set(mAttachInfo.mContentInsets);
568 mPendingVisibleInsets.set(0, 0, 0, 0);
569 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
570 if (res < WindowManagerGlobal.ADD_OKAY) {
571 mAttachInfo.mRootView = null;
573 mFallbackEventHandler.setView(null);
574 unscheduleTraversals();
575 setAccessibilityFocus(null, null);
577 case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
578 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
579 throw new WindowManager.BadTokenException(
580 "Unable to add window -- token " + attrs.token
581 + " is not valid; is your activity running?");
582 case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
583 throw new WindowManager.BadTokenException(
584 "Unable to add window -- token " + attrs.token
585 + " is not for an application");
586 case WindowManagerGlobal.ADD_APP_EXITING:
587 throw new WindowManager.BadTokenException(
588 "Unable to add window -- app for token " + attrs.token
590 case WindowManagerGlobal.ADD_DUPLICATE_ADD:
591 throw new WindowManager.BadTokenException(
592 "Unable to add window -- window " + mWindow
593 + " has already been added");
594 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
595 // Silently ignore -- we would have just removed it
596 // right away, anyway.
598 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
599 throw new WindowManager.BadTokenException(
600 "Unable to add window " + mWindow +
601 " -- another window of this type already exists");
602 case WindowManagerGlobal.ADD_PERMISSION_DENIED:
603 throw new WindowManager.BadTokenException(
604 "Unable to add window " + mWindow +
605 " -- permission denied for this window type");
606 case WindowManagerGlobal.ADD_INVALID_DISPLAY:
607 throw new WindowManager.InvalidDisplayException(
608 "Unable to add window " + mWindow +
609 " -- the specified display can not be found");
611 throw new RuntimeException(
612 "Unable to add window -- unknown error code " + res);
615 if (view instanceof RootViewSurfaceTaker) {
616 mInputQueueCallback =
617 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
619 if (mInputChannel != null) {
620 if (mInputQueueCallback != null) {
621 mInputQueue = new InputQueue(mInputChannel);
622 mInputQueueCallback.onInputQueueCreated(mInputQueue);
624 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
629 view.assignParent(this);
630 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
631 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
633 if (mAccessibilityManager.isEnabled()) {
634 mAccessibilityInteractionConnectionManager.ensureConnection();
637 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
638 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
644 void destroyHardwareResources() {
645 if (mAttachInfo.mHardwareRenderer != null) {
646 if (mAttachInfo.mHardwareRenderer.isEnabled()) {
647 mAttachInfo.mHardwareRenderer.destroyLayers(mView);
649 mAttachInfo.mHardwareRenderer.destroy(false);
653 void terminateHardwareResources() {
654 if (mAttachInfo.mHardwareRenderer != null) {
655 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
656 mAttachInfo.mHardwareRenderer.destroy(false);
660 void destroyHardwareLayers() {
661 if (mThread != Thread.currentThread()) {
662 if (mAttachInfo.mHardwareRenderer != null &&
663 mAttachInfo.mHardwareRenderer.isEnabled()) {
664 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE);
667 if (mAttachInfo.mHardwareRenderer != null &&
668 mAttachInfo.mHardwareRenderer.isEnabled()) {
669 mAttachInfo.mHardwareRenderer.destroyLayers(mView);
674 void pushHardwareLayerUpdate(HardwareLayer layer) {
675 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
676 mAttachInfo.mHardwareRenderer.pushLayerUpdate(layer);
680 public boolean attachFunctor(int functor) {
681 //noinspection SimplifiableIfStatement
682 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
683 return mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor);
688 public void detachFunctor(int functor) {
689 if (mAttachInfo.mHardwareRenderer != null) {
690 mAttachInfo.mHardwareRenderer.detachFunctor(functor);
694 private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) {
695 mAttachInfo.mHardwareAccelerated = false;
696 mAttachInfo.mHardwareAccelerationRequested = false;
698 // Don't enable hardware acceleration when the application is in compatibility mode
699 if (mTranslator != null) return;
701 // Try to enable hardware acceleration if requested
702 final boolean hardwareAccelerated =
703 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
705 if (hardwareAccelerated) {
706 if (!HardwareRenderer.isAvailable()) {
710 // Persistent processes (including the system) should not do
711 // accelerated rendering on low-end devices. In that case,
712 // sRendererDisabled will be set. In addition, the system process
713 // itself should never do accelerated rendering. In that case, both
714 // sRendererDisabled and sSystemRendererDisabled are set. When
715 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
716 // can be used by code on the system process to escape that and enable
717 // HW accelerated drawing. (This is basically for the lock screen.)
719 final boolean fakeHwAccelerated = (attrs.privateFlags &
720 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
721 final boolean forceHwAccelerated = (attrs.privateFlags &
722 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
724 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled
725 && forceHwAccelerated)) {
726 // Don't enable hardware acceleration when we're not on the main thread
727 if (!HardwareRenderer.sSystemRendererDisabled &&
728 Looper.getMainLooper() != Looper.myLooper()) {
729 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
730 + "acceleration outside of the main thread, aborting");
734 final boolean renderThread = isRenderThreadRequested(context);
736 Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated");
739 if (mAttachInfo.mHardwareRenderer != null) {
740 mAttachInfo.mHardwareRenderer.destroy(true);
743 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
744 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
745 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
746 = mAttachInfo.mHardwareRenderer != null;
748 } else if (fakeHwAccelerated) {
749 // The window had wanted to use hardware acceleration, but this
750 // is not allowed in its process. By setting this flag, it can
751 // still render as if it was accelerated. This is basically for
752 // the preview windows the window manager shows for launching
753 // applications, so they will look more like the app being launched.
754 mAttachInfo.mHardwareAccelerationRequested = true;
759 public View getView() {
763 final WindowLeaked getLocation() {
767 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
768 synchronized (this) {
769 int oldSoftInputMode = mWindowAttributes.softInputMode;
770 // Keep track of the actual window flags supplied by the client.
771 mClientWindowLayoutFlags = attrs.flags;
772 // preserve compatible window flag if exists.
773 int compatibleWindowFlag =
774 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
775 // transfer over system UI visibility values as they carry current state.
776 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
777 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
778 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
779 mWindowAttributes.flags |= compatibleWindowFlag;
781 applyKeepScreenOnFlag(mWindowAttributes);
784 mSoftInputMode = attrs.softInputMode;
787 // Don't lose the mode we last auto-computed.
788 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
789 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
790 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
791 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
793 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
795 mWindowAttributesChanged = true;
796 scheduleTraversals();
800 void handleAppVisibility(boolean visible) {
801 if (mAppVisible != visible) {
802 mAppVisible = visible;
803 scheduleTraversals();
807 void handleGetNewSurface() {
808 mNewSurfaceNeeded = true;
809 mFullRedrawNeeded = true;
810 scheduleTraversals();
813 void handleScreenStateChange(boolean on) {
814 if (on != mAttachInfo.mScreenOn) {
815 mAttachInfo.mScreenOn = on;
817 mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF);
820 mFullRedrawNeeded = true;
821 scheduleTraversals();
827 public void requestFitSystemWindows() {
829 mFitSystemWindowsRequested = true;
830 scheduleTraversals();
834 public void requestLayout() {
835 if (!mHandlingLayoutInLayoutRequest) {
837 mLayoutRequested = true;
838 scheduleTraversals();
843 public boolean isLayoutRequested() {
844 return mLayoutRequested;
848 mDirty.set(0, 0, mWidth, mHeight);
849 scheduleTraversals();
852 void invalidateWorld(View view) {
854 if (view instanceof ViewGroup) {
855 ViewGroup parent = (ViewGroup) view;
856 for (int i = 0; i < parent.getChildCount(); i++) {
857 invalidateWorld(parent.getChildAt(i));
863 public void invalidateChild(View child, Rect dirty) {
864 invalidateChildInParent(null, dirty);
867 public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
869 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
874 } else if (dirty.isEmpty() && !mIsAnimating) {
878 if (mCurScrollY != 0 || mTranslator != null) {
879 mTempRect.set(dirty);
881 if (mCurScrollY != 0) {
882 dirty.offset(0, -mCurScrollY);
884 if (mTranslator != null) {
885 mTranslator.translateRectInAppWindowToScreen(dirty);
887 if (mAttachInfo.mScalingRequired) {
892 final Rect localDirty = mDirty;
893 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
894 mAttachInfo.mSetIgnoreDirtyState = true;
895 mAttachInfo.mIgnoreDirtyState = true;
898 // Add the new dirty rect to the current one
899 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
900 // Intersect with the bounds of the window to skip
901 // updates that lie outside of the visible region
902 final float appScale = mAttachInfo.mApplicationScale;
903 final boolean intersected = localDirty.intersect(0, 0,
904 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
906 localDirty.setEmpty();
908 if (!mWillDrawSoon && (intersected || mIsAnimating)) {
909 scheduleTraversals();
915 void setStopped(boolean stopped) {
916 if (mStopped != stopped) {
919 scheduleTraversals();
924 public ViewParent getParent() {
928 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
929 if (child != mView) {
930 throw new RuntimeException("child is not mine, honest!");
932 // Note: don't apply scroll offset, because we want to know its
933 // visibility in the virtual canvas being given to the view hierarchy.
934 return r.intersect(0, 0, mWidth, mHeight);
937 public void bringChildToFront(View child) {
940 int getHostVisibility() {
941 return mAppVisible ? mView.getVisibility() : View.GONE;
944 void disposeResizeBuffer() {
945 if (mResizeBuffer != null) {
946 mResizeBuffer.destroy();
947 mResizeBuffer = null;
952 * Add LayoutTransition to the list of transitions to be started in the next traversal.
953 * This list will be cleared after the transitions on the list are start()'ed. These
954 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
955 * happens during the layout phase of traversal, which we want to complete before any of the
956 * animations are started (because those animations may side-effect properties that layout
957 * depends upon, like the bounding rectangles of the affected views). So we add the transition
958 * to the list and it is started just prior to starting the drawing phase of traversal.
960 * @param transition The LayoutTransition to be started on the next traversal.
964 public void requestTransitionStart(LayoutTransition transition) {
965 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
966 if (mPendingTransitions == null) {
967 mPendingTransitions = new ArrayList<LayoutTransition>();
969 mPendingTransitions.add(transition);
973 void scheduleTraversals() {
974 if (!mTraversalScheduled) {
975 mTraversalScheduled = true;
976 mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
977 mChoreographer.postCallback(
978 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
979 scheduleConsumeBatchedInput();
983 void unscheduleTraversals() {
984 if (mTraversalScheduled) {
985 mTraversalScheduled = false;
986 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
987 mChoreographer.removeCallbacks(
988 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
993 if (mTraversalScheduled) {
994 mTraversalScheduled = false;
995 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
998 Debug.startMethodTracing("ViewAncestor");
1001 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
1003 performTraversals();
1005 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1009 Debug.stopMethodTracing();
1015 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1016 // Update window's global keep screen on flag: if a view has requested
1017 // that the screen be kept on, then it is always set; otherwise, it is
1018 // set to whatever the client last requested for the global state.
1019 if (mAttachInfo.mKeepScreenOn) {
1020 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1022 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1023 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1027 private boolean collectViewAttributes() {
1028 final View.AttachInfo attachInfo = mAttachInfo;
1029 if (attachInfo.mRecomputeGlobalAttributes) {
1030 //Log.i(TAG, "Computing view hierarchy attributes!");
1031 attachInfo.mRecomputeGlobalAttributes = false;
1032 boolean oldScreenOn = attachInfo.mKeepScreenOn;
1033 attachInfo.mKeepScreenOn = false;
1034 attachInfo.mSystemUiVisibility = 0;
1035 attachInfo.mHasSystemUiListeners = false;
1036 mView.dispatchCollectViewAttributes(attachInfo, 0);
1037 attachInfo.mSystemUiVisibility &= ~attachInfo.mDisabledSystemUiVisibility;
1038 WindowManager.LayoutParams params = mWindowAttributes;
1039 if (attachInfo.mKeepScreenOn != oldScreenOn
1040 || attachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1041 || attachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
1042 applyKeepScreenOnFlag(params);
1043 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
1044 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners;
1045 mView.dispatchWindowSystemUiVisiblityChanged(attachInfo.mSystemUiVisibility);
1052 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1053 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1054 int childWidthMeasureSpec;
1055 int childHeightMeasureSpec;
1056 boolean windowSizeMayChange = false;
1058 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
1059 "Measuring " + host + " in display " + desiredWindowWidth
1060 + "x" + desiredWindowHeight + "...");
1062 boolean goodMeasure = false;
1063 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1064 // On large screens, we don't want to allow dialogs to just
1065 // stretch to fill the entire width of the screen to display
1066 // one line of text. First try doing the layout at a smaller
1067 // size to see if it will fit.
1068 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1069 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1071 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1072 baseSize = (int)mTmpValue.getDimension(packageMetrics);
1074 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
1075 if (baseSize != 0 && desiredWindowWidth > baseSize) {
1076 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1077 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1078 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1079 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1080 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1081 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1084 // Didn't fit in that size... try expanding a bit.
1085 baseSize = (baseSize+desiredWindowWidth)/2;
1086 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
1088 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1089 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1090 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1091 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1092 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1093 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
1101 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1102 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1103 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1104 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1105 windowSizeMayChange = true;
1110 System.out.println("======================================");
1111 System.out.println("performTraversals -- after measure");
1115 return windowSizeMayChange;
1118 private void performTraversals() {
1119 // cache mView since it is used so much below...
1120 final View host = mView;
1123 System.out.println("======================================");
1124 System.out.println("performTraversals");
1128 if (host == null || !mAdded)
1131 mIsInTraversal = true;
1132 mWillDrawSoon = true;
1133 boolean windowSizeMayChange = false;
1134 boolean newSurface = false;
1135 boolean surfaceChanged = false;
1136 WindowManager.LayoutParams lp = mWindowAttributes;
1138 int desiredWindowWidth;
1139 int desiredWindowHeight;
1141 final View.AttachInfo attachInfo = mAttachInfo;
1143 final int viewVisibility = getHostVisibility();
1144 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
1145 || mNewSurfaceNeeded;
1147 WindowManager.LayoutParams params = null;
1148 if (mWindowAttributesChanged) {
1149 mWindowAttributesChanged = false;
1150 surfaceChanged = true;
1153 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
1154 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1156 mFullRedrawNeeded = true;
1157 mLayoutRequested = true;
1158 if (mLastInCompatMode) {
1159 params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
1160 mLastInCompatMode = false;
1162 params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
1163 mLastInCompatMode = true;
1167 mWindowAttributesChangesFlag = 0;
1169 Rect frame = mWinFrame;
1171 mFullRedrawNeeded = true;
1172 mLayoutRequested = true;
1174 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
1175 // NOTE -- system code, won't try to do compat mode.
1176 Point size = new Point();
1177 mDisplay.getRealSize(size);
1178 desiredWindowWidth = size.x;
1179 desiredWindowHeight = size.y;
1181 DisplayMetrics packageMetrics =
1182 mView.getContext().getResources().getDisplayMetrics();
1183 desiredWindowWidth = packageMetrics.widthPixels;
1184 desiredWindowHeight = packageMetrics.heightPixels;
1187 // For the very first time, tell the view hierarchy that it
1188 // is attached to the window. Note that at this point the surface
1189 // object is not initialized to its backing store, but soon it
1190 // will be (assuming the window is visible).
1191 attachInfo.mSurface = mSurface;
1192 // We used to use the following condition to choose 32 bits drawing caches:
1193 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1194 // However, windows are now always 32 bits by default, so choose 32 bits
1195 attachInfo.mUse32BitDrawingCache = true;
1196 attachInfo.mHasWindowFocus = false;
1197 attachInfo.mWindowVisibility = viewVisibility;
1198 attachInfo.mRecomputeGlobalAttributes = false;
1199 viewVisibilityChanged = false;
1200 mLastConfiguration.setTo(host.getResources().getConfiguration());
1201 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1202 // Set the layout direction if it has not been set before (inherit is the default)
1203 if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1204 host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1206 host.dispatchAttachedToWindow(attachInfo, 0);
1207 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1208 host.fitSystemWindows(mFitSystemWindowsInsets);
1209 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
1212 desiredWindowWidth = frame.width();
1213 desiredWindowHeight = frame.height();
1214 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
1215 if (DEBUG_ORIENTATION) Log.v(TAG,
1216 "View " + host + " resized to: " + frame);
1217 mFullRedrawNeeded = true;
1218 mLayoutRequested = true;
1219 windowSizeMayChange = true;
1223 if (viewVisibilityChanged) {
1224 attachInfo.mWindowVisibility = viewVisibility;
1225 host.dispatchWindowVisibilityChanged(viewVisibility);
1226 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1227 destroyHardwareResources();
1229 if (viewVisibility == View.GONE) {
1230 // After making a window gone, we will count it as being
1231 // shown for the first time the next time it gets focus.
1232 mHasHadWindowFocus = false;
1236 // Execute enqueued actions on every traversal in case a detached view enqueued an action
1237 getRunQueue().executeActions(attachInfo.mHandler);
1239 boolean insetsChanged = false;
1241 boolean layoutRequested = mLayoutRequested && !mStopped;
1242 if (layoutRequested) {
1244 final Resources res = mView.getContext().getResources();
1247 // make sure touch mode code executes by setting cached value
1248 // to opposite of the added touch mode.
1249 mAttachInfo.mInTouchMode = !mAddedTouchMode;
1250 ensureTouchModeLocally(mAddedTouchMode);
1252 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
1253 insetsChanged = true;
1255 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
1256 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1257 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1258 + mAttachInfo.mVisibleInsets);
1260 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1261 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
1262 windowSizeMayChange = true;
1264 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
1265 // NOTE -- system code, won't try to do compat mode.
1266 Point size = new Point();
1267 mDisplay.getRealSize(size);
1268 desiredWindowWidth = size.x;
1269 desiredWindowHeight = size.y;
1271 DisplayMetrics packageMetrics = res.getDisplayMetrics();
1272 desiredWindowWidth = packageMetrics.widthPixels;
1273 desiredWindowHeight = packageMetrics.heightPixels;
1278 // Ask host how big it wants to be
1279 windowSizeMayChange |= measureHierarchy(host, lp, res,
1280 desiredWindowWidth, desiredWindowHeight);
1283 if (collectViewAttributes()) {
1286 if (attachInfo.mForceReportNewAttributes) {
1287 attachInfo.mForceReportNewAttributes = false;
1291 if (mFirst || attachInfo.mViewVisibilityChanged) {
1292 attachInfo.mViewVisibilityChanged = false;
1293 int resizeMode = mSoftInputMode &
1294 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1295 // If we are in auto resize mode, then we need to determine
1296 // what mode to use now.
1297 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1298 final int N = attachInfo.mScrollContainers.size();
1299 for (int i=0; i<N; i++) {
1300 if (attachInfo.mScrollContainers.get(i).isShown()) {
1301 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1304 if (resizeMode == 0) {
1305 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1307 if ((lp.softInputMode &
1308 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1309 lp.softInputMode = (lp.softInputMode &
1310 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1317 if (params != null && (host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1318 if (!PixelFormat.formatHasAlpha(params.format)) {
1319 params.format = PixelFormat.TRANSLUCENT;
1323 if (mFitSystemWindowsRequested) {
1324 mFitSystemWindowsRequested = false;
1325 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1326 host.fitSystemWindows(mFitSystemWindowsInsets);
1327 if (mLayoutRequested) {
1328 // Short-circuit catching a new layout request here, so
1329 // we don't need to go through two layout passes when things
1330 // change due to fitting system windows, which can happen a lot.
1331 windowSizeMayChange |= measureHierarchy(host, lp,
1332 mView.getContext().getResources(),
1333 desiredWindowWidth, desiredWindowHeight);
1337 if (layoutRequested) {
1338 // Clear this now, so that if anything requests a layout in the
1339 // rest of this function we will catch it and re-run a full
1341 mLayoutRequested = false;
1344 boolean windowShouldResize = layoutRequested && windowSizeMayChange
1345 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
1346 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1347 frame.width() < desiredWindowWidth && frame.width() != mWidth)
1348 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1349 frame.height() < desiredWindowHeight && frame.height() != mHeight));
1351 final boolean computesInternalInsets =
1352 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
1354 boolean insetsPending = false;
1355 int relayoutResult = 0;
1357 if (mFirst || windowShouldResize || insetsChanged ||
1358 viewVisibilityChanged || params != null) {
1360 if (viewVisibility == View.VISIBLE) {
1361 // If this window is giving internal insets to the window
1362 // manager, and it is being added or changing its visibility,
1363 // then we want to first give the window manager "fake"
1364 // insets to cause it to effectively ignore the content of
1365 // the window during layout. This avoids it briefly causing
1366 // other windows to resize/move based on the raw frame of the
1367 // window, waiting until we can finish laying out this window
1368 // and get back to the window manager with the ultimately
1370 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1373 if (mSurfaceHolder != null) {
1374 mSurfaceHolder.mSurfaceLock.lock();
1375 mDrawingAllowed = true;
1378 boolean hwInitialized = false;
1379 boolean contentInsetsChanged = false;
1380 boolean visibleInsetsChanged;
1381 boolean hadSurface = mSurface.isValid();
1385 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1386 host.getMeasuredHeight() + ", params=" + params);
1389 final int surfaceGenerationId = mSurface.getGenerationId();
1390 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1392 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1393 + " content=" + mPendingContentInsets.toShortString()
1394 + " visible=" + mPendingVisibleInsets.toShortString()
1395 + " surface=" + mSurface);
1397 if (mPendingConfiguration.seq != 0) {
1398 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1399 + mPendingConfiguration);
1400 updateConfiguration(mPendingConfiguration, !mFirst);
1401 mPendingConfiguration.seq = 0;
1404 contentInsetsChanged = !mPendingContentInsets.equals(
1405 mAttachInfo.mContentInsets);
1406 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1407 mAttachInfo.mVisibleInsets);
1408 if (contentInsetsChanged) {
1409 if (mWidth > 0 && mHeight > 0 && lp != null &&
1410 ((lp.systemUiVisibility|lp.subtreeSystemUiVisibility)
1411 & View.SYSTEM_UI_LAYOUT_FLAGS) == 0 &&
1412 mSurface != null && mSurface.isValid() &&
1413 !mAttachInfo.mTurnOffWindowResizeAnim &&
1414 mAttachInfo.mHardwareRenderer != null &&
1415 mAttachInfo.mHardwareRenderer.isEnabled() &&
1416 mAttachInfo.mHardwareRenderer.validate() &&
1417 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
1419 disposeResizeBuffer();
1421 boolean completed = false;
1422 HardwareCanvas hwRendererCanvas = mAttachInfo.mHardwareRenderer.getCanvas();
1423 HardwareCanvas layerCanvas = null;
1425 if (mResizeBuffer == null) {
1426 mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
1427 mWidth, mHeight, false);
1428 } else if (mResizeBuffer.getWidth() != mWidth ||
1429 mResizeBuffer.getHeight() != mHeight) {
1430 mResizeBuffer.resize(mWidth, mHeight);
1432 // TODO: should handle create/resize failure
1433 layerCanvas = mResizeBuffer.start(hwRendererCanvas);
1434 layerCanvas.setViewport(mWidth, mHeight);
1435 layerCanvas.onPreDraw(null);
1436 final int restoreCount = layerCanvas.save();
1439 final boolean scrolling = mScroller != null
1440 && mScroller.computeScrollOffset();
1442 yoff = mScroller.getCurrY();
1443 mScroller.abortAnimation();
1448 layerCanvas.translate(0, -yoff);
1449 if (mTranslator != null) {
1450 mTranslator.translateCanvas(layerCanvas);
1453 DisplayList displayList = mView.mDisplayList;
1454 if (displayList != null) {
1455 layerCanvas.drawDisplayList(displayList, null,
1456 DisplayList.FLAG_CLIP_CHILDREN);
1458 mView.draw(layerCanvas);
1461 drawAccessibilityFocusedDrawableIfNeeded(layerCanvas);
1463 mResizeBufferStartTime = SystemClock.uptimeMillis();
1464 mResizeBufferDuration = mView.getResources().getInteger(
1465 com.android.internal.R.integer.config_mediumAnimTime);
1468 layerCanvas.restoreToCount(restoreCount);
1469 } catch (OutOfMemoryError e) {
1470 Log.w(TAG, "Not enough memory for content change anim buffer", e);
1472 if (layerCanvas != null) {
1473 layerCanvas.onPostDraw();
1475 if (mResizeBuffer != null) {
1476 mResizeBuffer.end(hwRendererCanvas);
1478 mResizeBuffer.destroy();
1479 mResizeBuffer = null;
1484 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1485 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1486 + mAttachInfo.mContentInsets);
1488 if (contentInsetsChanged || mLastSystemUiVisibility !=
1489 mAttachInfo.mSystemUiVisibility || mFitSystemWindowsRequested) {
1490 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1491 mFitSystemWindowsRequested = false;
1492 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1493 host.fitSystemWindows(mFitSystemWindowsInsets);
1495 if (visibleInsetsChanged) {
1496 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1497 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1498 + mAttachInfo.mVisibleInsets);
1502 if (mSurface.isValid()) {
1503 // If we are creating a new surface, then we need to
1504 // completely redraw it. Also, when we get to the
1505 // point of drawing it we will hold off and schedule
1506 // a new traversal instead. This is so we can tell the
1507 // window manager about all of the windows being displayed
1508 // before actually drawing them, so it can display then
1511 mFullRedrawNeeded = true;
1512 mPreviousTransparentRegion.setEmpty();
1514 if (mAttachInfo.mHardwareRenderer != null) {
1516 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
1517 mHolder.getSurface());
1518 } catch (Surface.OutOfResourcesException e) {
1519 Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
1521 if (!mWindowSession.outOfMemory(mWindow) &&
1522 Process.myUid() != Process.SYSTEM_UID) {
1523 Slog.w(TAG, "No processes killed for memory; killing self");
1524 Process.killProcess(Process.myPid());
1526 } catch (RemoteException ex) {
1528 mLayoutRequested = true; // ask wm for a new surface next time.
1533 } else if (!mSurface.isValid()) {
1534 // If the surface has been removed, then reset the scroll
1536 mLastScrolledFocus = null;
1537 mScrollY = mCurScrollY = 0;
1538 if (mScroller != null) {
1539 mScroller.abortAnimation();
1541 disposeResizeBuffer();
1542 // Our surface is gone
1543 if (mAttachInfo.mHardwareRenderer != null &&
1544 mAttachInfo.mHardwareRenderer.isEnabled()) {
1545 mAttachInfo.mHardwareRenderer.destroy(true);
1547 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1548 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1549 mFullRedrawNeeded = true;
1551 mAttachInfo.mHardwareRenderer.updateSurface(mHolder.getSurface());
1552 } catch (Surface.OutOfResourcesException e) {
1553 Log.e(TAG, "OutOfResourcesException updating HW surface", e);
1555 if (!mWindowSession.outOfMemory(mWindow)) {
1556 Slog.w(TAG, "No processes killed for memory; killing self");
1557 Process.killProcess(Process.myPid());
1559 } catch (RemoteException ex) {
1561 mLayoutRequested = true; // ask wm for a new surface next time.
1565 } catch (RemoteException e) {
1568 if (DEBUG_ORIENTATION) Log.v(
1569 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1571 attachInfo.mWindowLeft = frame.left;
1572 attachInfo.mWindowTop = frame.top;
1574 // !!FIXME!! This next section handles the case where we did not get the
1575 // window size we asked for. We should avoid this by getting a maximum size from
1576 // the window session beforehand.
1577 if (mWidth != frame.width() || mHeight != frame.height()) {
1578 mWidth = frame.width();
1579 mHeight = frame.height();
1582 if (mSurfaceHolder != null) {
1583 // The app owns the surface; tell it about what is going on.
1584 if (mSurface.isValid()) {
1585 // XXX .copyFrom() doesn't work!
1586 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1587 mSurfaceHolder.mSurface = mSurface;
1589 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1590 mSurfaceHolder.mSurfaceLock.unlock();
1591 if (mSurface.isValid()) {
1593 mSurfaceHolder.ungetCallbacks();
1596 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1597 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1598 if (callbacks != null) {
1599 for (SurfaceHolder.Callback c : callbacks) {
1600 c.surfaceCreated(mSurfaceHolder);
1603 surfaceChanged = true;
1605 if (surfaceChanged) {
1606 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1607 lp.format, mWidth, mHeight);
1608 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1609 if (callbacks != null) {
1610 for (SurfaceHolder.Callback c : callbacks) {
1611 c.surfaceChanged(mSurfaceHolder, lp.format,
1616 mIsCreating = false;
1617 } else if (hadSurface) {
1618 mSurfaceHolder.ungetCallbacks();
1619 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1620 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1621 if (callbacks != null) {
1622 for (SurfaceHolder.Callback c : callbacks) {
1623 c.surfaceDestroyed(mSurfaceHolder);
1626 mSurfaceHolder.mSurfaceLock.lock();
1628 mSurfaceHolder.mSurface = new Surface();
1630 mSurfaceHolder.mSurfaceLock.unlock();
1635 if (mAttachInfo.mHardwareRenderer != null &&
1636 mAttachInfo.mHardwareRenderer.isEnabled()) {
1637 if (hwInitialized || windowShouldResize ||
1638 mWidth != mAttachInfo.mHardwareRenderer.getWidth() ||
1639 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) {
1640 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
1641 if (!hwInitialized) {
1642 mAttachInfo.mHardwareRenderer.invalidate(mHolder.getSurface());
1643 mFullRedrawNeeded = true;
1649 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1650 (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
1651 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1652 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1653 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1654 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1656 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1657 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1658 + " mHeight=" + mHeight
1659 + " measuredHeight=" + host.getMeasuredHeight()
1660 + " coveredInsetsChanged=" + contentInsetsChanged);
1662 // Ask host how big it wants to be
1663 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1665 // Implementation of weights from WindowManager.LayoutParams
1666 // We just grow the dimensions as needed and re-measure if
1668 int width = host.getMeasuredWidth();
1669 int height = host.getMeasuredHeight();
1670 boolean measureAgain = false;
1672 if (lp.horizontalWeight > 0.0f) {
1673 width += (int) ((mWidth - width) * lp.horizontalWeight);
1674 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1675 MeasureSpec.EXACTLY);
1676 measureAgain = true;
1678 if (lp.verticalWeight > 0.0f) {
1679 height += (int) ((mHeight - height) * lp.verticalWeight);
1680 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1681 MeasureSpec.EXACTLY);
1682 measureAgain = true;
1686 if (DEBUG_LAYOUT) Log.v(TAG,
1687 "And hey let's measure once more: width=" + width
1688 + " height=" + height);
1689 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1692 layoutRequested = true;
1696 // Not the first pass and no window/insets/visibility change but the window
1697 // may have moved and we need check that and if so to update the left and right
1698 // in the attach info. We translate only the window frame since on window move
1699 // the window manager tells us only for the new frame but the insets are the
1700 // same and we do not want to translate them more than once.
1702 // TODO: Well, we are checking whether the frame has changed similarly
1703 // to how this is done for the insets. This is however incorrect since
1704 // the insets and the frame are translated. For example, the old frame
1705 // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
1706 // reported frame is (2, 2 - 2, 2) which implies no change but this is not
1707 // true since we are comparing a not translated value to a translated one.
1708 // This scenario is rare but we may want to fix that.
1710 final boolean windowMoved = (attachInfo.mWindowLeft != frame.left
1711 || attachInfo.mWindowTop != frame.top);
1713 if (mTranslator != null) {
1714 mTranslator.translateRectInScreenToAppWinFrame(frame);
1716 attachInfo.mWindowLeft = frame.left;
1717 attachInfo.mWindowTop = frame.top;
1721 final boolean didLayout = layoutRequested && !mStopped;
1722 boolean triggerGlobalLayoutListener = didLayout
1723 || attachInfo.mRecomputeGlobalAttributes;
1725 performLayout(lp, desiredWindowWidth, desiredWindowHeight);
1727 // By this point all views have been sized and positionned
1728 // We can compute the transparent area
1730 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1731 // start out transparent
1732 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1733 host.getLocationInWindow(mTmpLocation);
1734 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1735 mTmpLocation[0] + host.mRight - host.mLeft,
1736 mTmpLocation[1] + host.mBottom - host.mTop);
1738 host.gatherTransparentRegion(mTransparentRegion);
1739 if (mTranslator != null) {
1740 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1743 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1744 mPreviousTransparentRegion.set(mTransparentRegion);
1745 // reconfigure window manager
1747 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1748 } catch (RemoteException e) {
1754 System.out.println("======================================");
1755 System.out.println("performTraversals -- after setFrame");
1760 if (triggerGlobalLayoutListener) {
1761 attachInfo.mRecomputeGlobalAttributes = false;
1762 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1764 if (AccessibilityManager.getInstance(host.mContext).isEnabled()) {
1765 postSendWindowContentChangedCallback(mView);
1769 if (computesInternalInsets) {
1770 // Clear the original insets.
1771 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1774 // Compute new insets in place.
1775 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
1777 // Tell the window manager.
1778 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1779 mLastGivenInsets.set(insets);
1781 // Translate insets to screen coordinates if needed.
1782 final Rect contentInsets;
1783 final Rect visibleInsets;
1784 final Region touchableRegion;
1785 if (mTranslator != null) {
1786 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1787 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1788 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1790 contentInsets = insets.contentInsets;
1791 visibleInsets = insets.visibleInsets;
1792 touchableRegion = insets.touchableRegion;
1796 mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
1797 contentInsets, visibleInsets, touchableRegion);
1798 } catch (RemoteException e) {
1803 boolean skipDraw = false;
1806 // handle first focus request
1807 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1808 + mView.hasFocus());
1809 if (mView != null) {
1810 if (!mView.hasFocus()) {
1811 mView.requestFocus(View.FOCUS_FORWARD);
1812 mFocusedView = mRealFocusedView = mView.findFocus();
1813 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1816 mRealFocusedView = mView.findFocus();
1817 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1818 + mRealFocusedView);
1821 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) {
1822 // The first time we relayout the window, if the system is
1823 // doing window animations, we want to hold of on any future
1824 // draws until the animation is done.
1825 mWindowsAnimating = true;
1827 } else if (mWindowsAnimating) {
1832 mWillDrawSoon = false;
1833 mNewSurfaceNeeded = false;
1834 mViewVisibility = viewVisibility;
1836 if (mAttachInfo.mHasWindowFocus) {
1837 final boolean imTarget = WindowManager.LayoutParams
1838 .mayUseInputMethod(mWindowAttributes.flags);
1839 if (imTarget != mLastWasImTarget) {
1840 mLastWasImTarget = imTarget;
1841 InputMethodManager imm = InputMethodManager.peekInstance();
1842 if (imm != null && imTarget) {
1843 imm.startGettingWindowFocus(mView);
1844 imm.onWindowFocus(mView, mView.findFocus(),
1845 mWindowAttributes.softInputMode,
1846 !mHasHadWindowFocus, mWindowAttributes.flags);
1851 // Remember if we must report the next draw.
1852 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
1853 mReportNextDraw = true;
1856 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() ||
1857 viewVisibility != View.VISIBLE;
1859 if (!cancelDraw && !newSurface) {
1860 if (!skipDraw || mReportNextDraw) {
1861 if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
1862 for (int i = 0; i < mPendingTransitions.size(); ++i) {
1863 mPendingTransitions.get(i).startChangingAnimations();
1865 mPendingTransitions.clear();
1871 if (viewVisibility == View.VISIBLE) {
1873 scheduleTraversals();
1874 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
1875 for (int i = 0; i < mPendingTransitions.size(); ++i) {
1876 mPendingTransitions.get(i).endChangingAnimations();
1878 mPendingTransitions.clear();
1882 mIsInTraversal = false;
1885 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
1886 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
1888 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1890 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1895 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
1896 * is currently undergoing a layout pass.
1898 * @return whether the view hierarchy is currently undergoing a layout pass
1900 boolean isInLayout() {
1905 * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
1906 * undergoing a layout pass. requestLayout() should not generally be called during layout,
1907 * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
1908 * all children in that container hierarchy are measured and laid out at the end of the layout
1909 * pass for that container). If requestLayout() is called anyway, we handle it correctly
1910 * by registering all requesters during a frame as it proceeds. At the end of the frame,
1911 * we check all of those views to see if any still have pending layout requests, which
1912 * indicates that they were not correctly handled by their container hierarchy. If that is
1913 * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
1914 * to blank containers, and force a second request/measure/layout pass in this frame. If
1915 * more requestLayout() calls are received during that second layout pass, we post those
1916 * requests to the next frame to avoid possible infinite loops.
1918 * <p>The return value from this method indicates whether the request should proceed
1919 * (if it is a request during the first layout pass) or should be skipped and posted to the
1920 * next frame (if it is a request during the second layout pass).</p>
1922 * @param view the view that requested the layout.
1924 * @return true if request should proceed, false otherwise.
1926 boolean requestLayoutDuringLayout(final View view) {
1927 if (view.mParent == null || view.mAttachInfo == null) {
1928 // Would not normally trigger another layout, so just let it pass through as usual
1931 if (!mHandlingLayoutInLayoutRequest) {
1932 if (!mLayoutRequesters.contains(view)) {
1933 mLayoutRequesters.add(view);
1937 Log.w("View", "requestLayout() called by " + view + " during second layout pass: " +
1938 "posting to next frame");
1939 view.post(new Runnable() {
1942 view.requestLayout();
1949 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
1950 int desiredWindowHeight) {
1951 mLayoutRequested = false;
1952 mScrollMayChange = true;
1955 final View host = mView;
1956 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
1957 Log.v(TAG, "Laying out " + host + " to (" +
1958 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
1961 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
1963 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
1966 int numViewsRequestingLayout = mLayoutRequesters.size();
1967 if (numViewsRequestingLayout > 0) {
1968 // requestLayout() was called during layout.
1969 // If no layout-request flags are set on the requesting views, there is no problem.
1970 // If some requests are still pending, then we need to clear those flags and do
1971 // a full request/measure/layout pass to handle this situation.
1973 // Check state of layout flags for all requesters
1974 ArrayList<View> mValidLayoutRequesters = null;
1975 for (int i = 0; i < numViewsRequestingLayout; ++i) {
1976 View view = mLayoutRequesters.get(i);
1977 if ((view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == View.PFLAG_FORCE_LAYOUT) {
1978 while (view != null && view.mAttachInfo != null && view.mParent != null &&
1979 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
1980 if ((view.mViewFlags & View.VISIBILITY_MASK) != View.GONE) {
1981 // Only trigger new requests for non-GONE views
1982 Log.w(TAG, "requestLayout() improperly called during " +
1983 "layout: running second layout pass for " + view);
1984 if (mValidLayoutRequesters == null) {
1985 mValidLayoutRequesters = new ArrayList<View>();
1987 mValidLayoutRequesters.add(view);
1990 if (view.mParent instanceof View) {
1991 view = (View) view.mParent;
1998 if (mValidLayoutRequesters != null) {
1999 // Clear flags throughout hierarchy, walking up from each flagged requester
2000 for (int i = 0; i < numViewsRequestingLayout; ++i) {
2001 View view = mLayoutRequesters.get(i);
2002 while (view != null &&
2003 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
2004 view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
2005 if (view.mParent instanceof View) {
2006 view = (View) view.mParent;
2012 // Process fresh layout requests, then measure and layout
2013 mHandlingLayoutInLayoutRequest = true;
2014 int numValidRequests = mValidLayoutRequesters.size();
2015 for (int i = 0; i < numValidRequests; ++i) {
2016 mValidLayoutRequesters.get(i).requestLayout();
2018 measureHierarchy(host, lp, mView.getContext().getResources(),
2019 desiredWindowWidth, desiredWindowHeight);
2021 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2022 mHandlingLayoutInLayoutRequest = false;
2024 mLayoutRequesters.clear();
2027 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2032 public void requestTransparentRegion(View child) {
2033 // the test below should not fail unless someone is messing with us
2035 if (mView == child) {
2036 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
2037 // Need to make sure we re-evaluate the window attributes next
2038 // time around, to ensure the window has the correct format.
2039 mWindowAttributesChanged = true;
2040 mWindowAttributesChangesFlag = 0;
2046 * Figures out the measure spec for the root view in a window based on it's
2050 * The available width or height of the window
2052 * @param rootDimension
2053 * The layout params for one dimension (width or height) of the
2056 * @return The measure spec to use to measure the root view.
2058 private static int getRootMeasureSpec(int windowSize, int rootDimension) {
2060 switch (rootDimension) {
2062 case ViewGroup.LayoutParams.MATCH_PARENT:
2063 // Window can't resize. Force root view to be windowSize.
2064 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2066 case ViewGroup.LayoutParams.WRAP_CONTENT:
2067 // Window can resize. Set max size for root view.
2068 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2071 // Window wants to be an exact size. Force root view to be that size.
2072 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2078 int mHardwareYOffset;
2080 final Paint mResizePaint = new Paint();
2082 public void onHardwarePreDraw(HardwareCanvas canvas) {
2083 canvas.translate(0, -mHardwareYOffset);
2086 public void onHardwarePostDraw(HardwareCanvas canvas) {
2087 if (mResizeBuffer != null) {
2088 mResizePaint.setAlpha(mResizeAlpha);
2089 canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint);
2091 drawAccessibilityFocusedDrawableIfNeeded(canvas);
2097 void outputDisplayList(View view) {
2098 if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) {
2099 DisplayList displayList = view.getDisplayList();
2100 if (displayList != null) {
2101 mAttachInfo.mHardwareCanvas.outputDisplayList(displayList);
2107 * @see #PROPERTY_PROFILE_RENDERING
2109 private void profileRendering(boolean enabled) {
2110 if (mProfileRendering) {
2111 mRenderProfilingEnabled = enabled;
2112 if (mRenderProfiler == null) {
2113 mRenderProfiler = new Choreographer.FrameCallback() {
2115 public void doFrame(long frameTimeNanos) {
2116 mDirty.set(0, 0, mWidth, mHeight);
2117 scheduleTraversals();
2118 if (mRenderProfilingEnabled) {
2119 mChoreographer.postFrameCallback(mRenderProfiler);
2123 mChoreographer.postFrameCallback(mRenderProfiler);
2125 mChoreographer.removeFrameCallback(mRenderProfiler);
2126 mRenderProfiler = null;
2132 * Called from draw() when DEBUG_FPS is enabled
2134 private void trackFPS() {
2135 // Tracks frames per second drawn. First value in a series of draws may be bogus
2136 // because it down not account for the intervening idle time
2137 long nowTime = System.currentTimeMillis();
2138 if (mFpsStartTime < 0) {
2139 mFpsStartTime = mFpsPrevTime = nowTime;
2143 String thisHash = Integer.toHexString(System.identityHashCode(this));
2144 long frameTime = nowTime - mFpsPrevTime;
2145 long totalTime = nowTime - mFpsStartTime;
2146 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime);
2147 mFpsPrevTime = nowTime;
2148 if (totalTime > 1000) {
2149 float fps = (float) mFpsNumFrames * 1000 / totalTime;
2150 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps);
2151 mFpsStartTime = nowTime;
2157 private void performDraw() {
2158 if (!mAttachInfo.mScreenOn && !mReportNextDraw) {
2162 final boolean fullRedrawNeeded = mFullRedrawNeeded;
2163 mFullRedrawNeeded = false;
2166 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2168 draw(fullRedrawNeeded);
2171 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2174 if (mReportNextDraw) {
2175 mReportNextDraw = false;
2178 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2180 if (mSurfaceHolder != null && mSurface.isValid()) {
2181 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2182 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2183 if (callbacks != null) {
2184 for (SurfaceHolder.Callback c : callbacks) {
2185 if (c instanceof SurfaceHolder.Callback2) {
2186 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
2193 mWindowSession.finishDrawing(mWindow);
2194 } catch (RemoteException e) {
2199 private void draw(boolean fullRedrawNeeded) {
2200 Surface surface = mSurface;
2201 if (!surface.isValid()) {
2209 if (!sFirstDrawComplete) {
2210 synchronized (sFirstDrawHandlers) {
2211 sFirstDrawComplete = true;
2212 final int count = sFirstDrawHandlers.size();
2213 for (int i = 0; i< count; i++) {
2214 mHandler.post(sFirstDrawHandlers.get(i));
2219 scrollToRectOrFocus(null, false);
2221 final AttachInfo attachInfo = mAttachInfo;
2222 if (attachInfo.mViewScrollChanged) {
2223 attachInfo.mViewScrollChanged = false;
2224 attachInfo.mTreeObserver.dispatchOnScrollChanged();
2228 boolean animating = mScroller != null && mScroller.computeScrollOffset();
2230 yoff = mScroller.getCurrY();
2234 if (mCurScrollY != yoff) {
2236 fullRedrawNeeded = true;
2239 final float appScale = attachInfo.mApplicationScale;
2240 final boolean scalingRequired = attachInfo.mScalingRequired;
2242 int resizeAlpha = 0;
2243 if (mResizeBuffer != null) {
2244 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
2245 if (deltaTime < mResizeBufferDuration) {
2246 float amt = deltaTime/(float) mResizeBufferDuration;
2247 amt = mResizeInterpolator.getInterpolation(amt);
2249 resizeAlpha = 255 - (int)(amt*255);
2251 disposeResizeBuffer();
2255 final Rect dirty = mDirty;
2256 if (mSurfaceHolder != null) {
2257 // The app owns the surface, we won't draw.
2260 if (mScroller != null) {
2261 mScroller.abortAnimation();
2263 disposeResizeBuffer();
2268 if (fullRedrawNeeded) {
2269 attachInfo.mIgnoreDirtyState = true;
2270 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2273 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2274 Log.v(TAG, "Draw " + mView + "/"
2275 + mWindowAttributes.getTitle()
2276 + ": dirty={" + dirty.left + "," + dirty.top
2277 + "," + dirty.right + "," + dirty.bottom + "} surface="
2278 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2279 appScale + ", width=" + mWidth + ", height=" + mHeight);
2282 invalidateDisplayLists();
2284 attachInfo.mTreeObserver.dispatchOnDraw();
2286 if (!dirty.isEmpty() || mIsAnimating) {
2287 if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) {
2288 // Draw with hardware renderer.
2289 mIsAnimating = false;
2290 mHardwareYOffset = yoff;
2291 mResizeAlpha = resizeAlpha;
2293 mCurrentDirty.set(dirty);
2294 mCurrentDirty.union(mPreviousDirty);
2295 mPreviousDirty.set(dirty);
2298 if (attachInfo.mHardwareRenderer.draw(mView, attachInfo, this,
2299 animating ? null : mCurrentDirty)) {
2300 mPreviousDirty.set(0, 0, mWidth, mHeight);
2302 } else if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) {
2308 mFullRedrawNeeded = true;
2309 scheduleTraversals();
2314 * @return true if drawing was succesfull, false if an error occurred
2316 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff,
2317 boolean scalingRequired, Rect dirty) {
2319 // If we get here with a disabled & requested hardware renderer, something went
2320 // wrong (an invalidate posted right before we destroyed the hardware surface
2321 // for instance) so we should just bail out. Locking the surface with software
2322 // rendering at this point would lock it forever and prevent hardware renderer
2323 // from doing its job when it comes back.
2324 if (attachInfo.mHardwareRenderer != null && !attachInfo.mHardwareRenderer.isEnabled() &&
2325 attachInfo.mHardwareRenderer.isRequested()) {
2326 mFullRedrawNeeded = true;
2327 scheduleTraversals();
2331 // Draw with software renderer.
2334 int left = dirty.left;
2335 int top = dirty.top;
2336 int right = dirty.right;
2337 int bottom = dirty.bottom;
2339 canvas = mSurface.lockCanvas(dirty);
2341 if (left != dirty.left || top != dirty.top || right != dirty.right ||
2342 bottom != dirty.bottom) {
2343 attachInfo.mIgnoreDirtyState = true;
2346 // TODO: Do this in native
2347 canvas.setDensity(mDensity);
2348 } catch (Surface.OutOfResourcesException e) {
2349 Log.e(TAG, "OutOfResourcesException locking surface", e);
2351 if (!mWindowSession.outOfMemory(mWindow)) {
2352 Slog.w(TAG, "No processes killed for memory; killing self");
2353 Process.killProcess(Process.myPid());
2355 } catch (RemoteException ex) {
2357 mLayoutRequested = true; // ask wm for a new surface next time.
2359 } catch (IllegalArgumentException e) {
2360 Log.e(TAG, "Could not lock surface", e);
2361 // Don't assume this is due to out of memory, it could be
2362 // something else, and if it is something else then we could
2363 // kill stuff (or ourself) for no reason.
2364 mLayoutRequested = true; // ask wm for a new surface next time.
2369 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2370 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
2371 + canvas.getWidth() + ", h=" + canvas.getHeight());
2372 //canvas.drawARGB(255, 255, 0, 0);
2375 // If this bitmap's format includes an alpha channel, we
2376 // need to clear it before drawing so that the child will
2377 // properly re-composite its drawing on a transparent
2378 // background. This automatically respects the clip/dirty region
2380 // If we are applying an offset, we need to clear the area
2381 // where the offset doesn't appear to avoid having garbage
2382 // left in the blank areas.
2383 if (!canvas.isOpaque() || yoff != 0) {
2384 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2388 mIsAnimating = false;
2389 attachInfo.mDrawingTime = SystemClock.uptimeMillis();
2390 mView.mPrivateFlags |= View.PFLAG_DRAWN;
2393 Context cxt = mView.getContext();
2394 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
2395 ", metrics=" + cxt.getResources().getDisplayMetrics() +
2396 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2399 canvas.translate(0, -yoff);
2400 if (mTranslator != null) {
2401 mTranslator.translateCanvas(canvas);
2403 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2404 attachInfo.mSetIgnoreDirtyState = false;
2408 drawAccessibilityFocusedDrawableIfNeeded(canvas);
2410 if (!attachInfo.mSetIgnoreDirtyState) {
2411 // Only clear the flag if it was not set during the mView.draw() call
2412 attachInfo.mIgnoreDirtyState = false;
2417 surface.unlockCanvasAndPost(canvas);
2418 } catch (IllegalArgumentException e) {
2419 Log.e(TAG, "Could not unlock surface", e);
2420 mLayoutRequested = true; // ask wm for a new surface next time.
2421 //noinspection ReturnInsideFinallyBlock
2426 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
2433 * We want to draw a highlight around the current accessibility focused.
2434 * Since adding a style for all possible view is not a viable option we
2435 * have this specialized drawing method.
2437 * Note: We are doing this here to be able to draw the highlight for
2438 * virtual views in addition to real ones.
2440 * @param canvas The canvas on which to draw.
2442 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2443 AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2444 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2447 if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) {
2450 Drawable drawable = getAccessibilityFocusedDrawable();
2451 if (drawable == null) {
2454 AccessibilityNodeProvider provider =
2455 mAccessibilityFocusedHost.getAccessibilityNodeProvider();
2456 Rect bounds = mView.mAttachInfo.mTmpInvalRect;
2457 if (provider == null) {
2458 mAccessibilityFocusedHost.getBoundsOnScreen(bounds);
2460 if (mAccessibilityFocusedVirtualView == null) {
2463 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2465 bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
2466 bounds.intersect(0, 0, mAttachInfo.mViewRootImpl.mWidth, mAttachInfo.mViewRootImpl.mHeight);
2467 drawable.setBounds(bounds);
2468 drawable.draw(canvas);
2471 private Drawable getAccessibilityFocusedDrawable() {
2472 if (mAttachInfo != null) {
2473 // Lazily load the accessibility focus drawable.
2474 if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2475 TypedValue value = new TypedValue();
2476 final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2477 R.attr.accessibilityFocusedDrawable, value, true);
2479 mAttachInfo.mAccessibilityFocusDrawable =
2480 mView.mContext.getResources().getDrawable(value.resourceId);
2483 return mAttachInfo.mAccessibilityFocusDrawable;
2488 void invalidateDisplayLists() {
2489 final ArrayList<DisplayList> displayLists = mDisplayLists;
2490 final int count = displayLists.size();
2492 for (int i = 0; i < count; i++) {
2493 final DisplayList displayList = displayLists.get(i);
2494 if (displayList.isDirty()) {
2495 displayList.invalidate();
2496 displayList.clear();
2497 displayList.setDirty(false);
2501 displayLists.clear();
2504 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2505 final View.AttachInfo attachInfo = mAttachInfo;
2506 final Rect ci = attachInfo.mContentInsets;
2507 final Rect vi = attachInfo.mVisibleInsets;
2509 boolean handled = false;
2511 if (vi.left > ci.left || vi.top > ci.top
2512 || vi.right > ci.right || vi.bottom > ci.bottom) {
2513 // We'll assume that we aren't going to change the scroll
2514 // offset, since we want to avoid that unless it is actually
2515 // going to make the focus visible... otherwise we scroll
2516 // all over the place.
2518 // We can be called for two different situations: during a draw,
2519 // to update the scroll position if the focus has changed (in which
2520 // case 'rectangle' is null), or in response to a
2521 // requestChildRectangleOnScreen() call (in which case 'rectangle'
2522 // is non-null and we just want to scroll to whatever that
2524 View focus = mRealFocusedView;
2526 // When in touch mode, focus points to the previously focused view,
2527 // which may have been removed from the view hierarchy. The following
2528 // line checks whether the view is still in our hierarchy.
2529 if (focus == null || focus.mAttachInfo != mAttachInfo) {
2530 mRealFocusedView = null;
2534 if (focus != mLastScrolledFocus) {
2535 // If the focus has changed, then ignore any requests to scroll
2536 // to a rectangle; first we want to make sure the entire focus
2540 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2541 + " rectangle=" + rectangle + " ci=" + ci
2543 if (focus == mLastScrolledFocus && !mScrollMayChange
2544 && rectangle == null) {
2545 // Optimization: if the focus hasn't changed since last
2546 // time, and no layout has happened, then just leave things
2548 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2549 + mScrollY + " vi=" + vi.toShortString());
2550 } else if (focus != null) {
2551 // We need to determine if the currently focused view is
2552 // within the visible part of the window and, if not, apply
2553 // a pan so it can be seen.
2554 mLastScrolledFocus = focus;
2555 mScrollMayChange = false;
2556 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2557 // Try to find the rectangle from the focus view.
2558 if (focus.getGlobalVisibleRect(mVisRect, null)) {
2559 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2560 + mView.getWidth() + " h=" + mView.getHeight()
2561 + " ci=" + ci.toShortString()
2562 + " vi=" + vi.toShortString());
2563 if (rectangle == null) {
2564 focus.getFocusedRect(mTempRect);
2565 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2566 + ": focusRect=" + mTempRect.toShortString());
2567 if (mView instanceof ViewGroup) {
2568 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2571 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2572 "Focus in window: focusRect="
2573 + mTempRect.toShortString()
2574 + " visRect=" + mVisRect.toShortString());
2576 mTempRect.set(rectangle);
2577 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2578 "Request scroll to rect: "
2579 + mTempRect.toShortString()
2580 + " visRect=" + mVisRect.toShortString());
2582 if (mTempRect.intersect(mVisRect)) {
2583 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2584 "Focus window visible rect: "
2585 + mTempRect.toShortString());
2586 if (mTempRect.height() >
2587 (mView.getHeight()-vi.top-vi.bottom)) {
2588 // If the focus simply is not going to fit, then
2589 // best is probably just to leave things as-is.
2590 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2591 "Too tall; leaving scrollY=" + scrollY);
2592 } else if ((mTempRect.top-scrollY) < vi.top) {
2593 scrollY -= vi.top - (mTempRect.top-scrollY);
2594 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2595 "Top covered; scrollY=" + scrollY);
2596 } else if ((mTempRect.bottom-scrollY)
2597 > (mView.getHeight()-vi.bottom)) {
2598 scrollY += (mTempRect.bottom-scrollY)
2599 - (mView.getHeight()-vi.bottom);
2600 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2601 "Bottom covered; scrollY=" + scrollY);
2609 if (scrollY != mScrollY) {
2610 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2611 + mScrollY + " , new=" + scrollY);
2612 if (!immediate && mResizeBuffer == null) {
2613 if (mScroller == null) {
2614 mScroller = new Scroller(mView.getContext());
2616 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2617 } else if (mScroller != null) {
2618 mScroller.abortAnimation();
2629 public View getAccessibilityFocusedHost() {
2630 return mAccessibilityFocusedHost;
2636 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
2637 return mAccessibilityFocusedVirtualView;
2640 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
2641 // If we have a virtual view with accessibility focus we need
2642 // to clear the focus and invalidate the virtual view bounds.
2643 if (mAccessibilityFocusedVirtualView != null) {
2645 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
2646 View focusHost = mAccessibilityFocusedHost;
2647 focusHost.clearAccessibilityFocusNoCallbacks();
2649 // Wipe the state of the current accessibility focus since
2650 // the call into the provider to clear accessibility focus
2651 // will fire an accessibility event which will end up calling
2652 // this method and we want to have clean state when this
2653 // invocation happens.
2654 mAccessibilityFocusedHost = null;
2655 mAccessibilityFocusedVirtualView = null;
2657 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
2658 if (provider != null) {
2659 // Invalidate the area of the cleared accessibility focus.
2660 focusNode.getBoundsInParent(mTempRect);
2661 focusHost.invalidate(mTempRect);
2662 // Clear accessibility focus in the virtual node.
2663 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
2664 focusNode.getSourceNodeId());
2665 provider.performAction(virtualNodeId,
2666 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
2668 focusNode.recycle();
2670 if (mAccessibilityFocusedHost != null) {
2671 // Clear accessibility focus in the view.
2672 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2675 // Set the new focus host and node.
2676 mAccessibilityFocusedHost = view;
2677 mAccessibilityFocusedVirtualView = node;
2680 public void requestChildFocus(View child, View focused) {
2683 if (DEBUG_INPUT_RESIZE) {
2684 Log.v(TAG, "Request child focus: focus now " + focused);
2687 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused);
2688 scheduleTraversals();
2690 mFocusedView = mRealFocusedView = focused;
2693 public void clearChildFocus(View child) {
2696 if (DEBUG_INPUT_RESIZE) {
2697 Log.v(TAG, "Clearing child focus");
2700 mOldFocusedView = mFocusedView;
2702 // Invoke the listener only if there is no view to take focus
2703 if (focusSearch(null, View.FOCUS_FORWARD) == null) {
2704 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null);
2707 mFocusedView = mRealFocusedView = null;
2711 public ViewParent getParentForAccessibility() {
2715 public void focusableViewAvailable(View v) {
2717 if (mView != null) {
2718 if (!mView.hasFocus()) {
2721 // the one case where will transfer focus away from the current one
2722 // is if the current view is a view group that prefers to give focus
2723 // to its children first AND the view is a descendant of it.
2724 mFocusedView = mView.findFocus();
2725 boolean descendantsHaveDibsOnFocus =
2726 (mFocusedView instanceof ViewGroup) &&
2727 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
2728 ViewGroup.FOCUS_AFTER_DESCENDANTS);
2729 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
2730 // If a view gets the focus, the listener will be invoked from requestChildFocus()
2737 public void recomputeViewAttributes(View child) {
2739 if (mView == child) {
2740 mAttachInfo.mRecomputeGlobalAttributes = true;
2741 if (!mWillDrawSoon) {
2742 scheduleTraversals();
2747 void dispatchDetachedFromWindow() {
2748 if (mView != null && mView.mAttachInfo != null) {
2749 if (mAttachInfo.mHardwareRenderer != null &&
2750 mAttachInfo.mHardwareRenderer.isEnabled()) {
2751 mAttachInfo.mHardwareRenderer.validate();
2753 mView.dispatchDetachedFromWindow();
2756 mAccessibilityInteractionConnectionManager.ensureNoConnection();
2757 mAccessibilityManager.removeAccessibilityStateChangeListener(
2758 mAccessibilityInteractionConnectionManager);
2759 removeSendWindowContentChangedCallback();
2761 destroyHardwareRenderer();
2763 setAccessibilityFocus(null, null);
2766 mAttachInfo.mRootView = null;
2767 mAttachInfo.mSurface = null;
2771 if (mInputQueueCallback != null && mInputQueue != null) {
2772 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2773 mInputQueueCallback = null;
2775 } else if (mInputEventReceiver != null) {
2776 mInputEventReceiver.dispose();
2777 mInputEventReceiver = null;
2780 mWindowSession.remove(mWindow);
2781 } catch (RemoteException e) {
2784 // Dispose the input channel after removing the window so the Window Manager
2785 // doesn't interpret the input channel being closed as an abnormal termination.
2786 if (mInputChannel != null) {
2787 mInputChannel.dispose();
2788 mInputChannel = null;
2791 unscheduleTraversals();
2794 void updateConfiguration(Configuration config, boolean force) {
2795 if (DEBUG_CONFIGURATION) Log.v(TAG,
2796 "Applying new config to window "
2797 + mWindowAttributes.getTitle()
2800 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2802 config = new Configuration(config);
2803 ci.applyToConfiguration(mNoncompatDensity, config);
2806 synchronized (sConfigCallbacks) {
2807 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2808 sConfigCallbacks.get(i).onConfigurationChanged(config);
2811 if (mView != null) {
2812 // At this point the resources have been updated to
2813 // have the most recent config, whatever that is. Use
2814 // the one in them which may be newer.
2815 config = mView.getResources().getConfiguration();
2816 if (force || mLastConfiguration.diff(config) != 0) {
2817 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
2818 final int currentLayoutDirection = config.getLayoutDirection();
2819 mLastConfiguration.setTo(config);
2820 if (lastLayoutDirection != currentLayoutDirection &&
2821 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
2822 mView.setLayoutDirection(currentLayoutDirection);
2824 mView.dispatchConfigurationChanged(config);
2830 * Return true if child is an ancestor of parent, (or equal to the parent).
2832 public static boolean isViewDescendantOf(View child, View parent) {
2833 if (child == parent) {
2837 final ViewParent theParent = child.getParent();
2838 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2841 private static void forceLayout(View view) {
2843 if (view instanceof ViewGroup) {
2844 ViewGroup group = (ViewGroup) view;
2845 final int count = group.getChildCount();
2846 for (int i = 0; i < count; i++) {
2847 forceLayout(group.getChildAt(i));
2852 private final static int MSG_INVALIDATE = 1;
2853 private final static int MSG_INVALIDATE_RECT = 2;
2854 private final static int MSG_DIE = 3;
2855 private final static int MSG_RESIZED = 4;
2856 private final static int MSG_RESIZED_REPORT = 5;
2857 private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
2858 private final static int MSG_DISPATCH_KEY = 7;
2859 private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
2860 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
2861 private final static int MSG_IME_FINISHED_EVENT = 10;
2862 private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
2863 private final static int MSG_FINISH_INPUT_CONNECTION = 12;
2864 private final static int MSG_CHECK_FOCUS = 13;
2865 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
2866 private final static int MSG_DISPATCH_DRAG_EVENT = 15;
2867 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
2868 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
2869 private final static int MSG_UPDATE_CONFIGURATION = 18;
2870 private final static int MSG_PROCESS_INPUT_EVENTS = 19;
2871 private final static int MSG_DISPATCH_SCREEN_STATE = 20;
2872 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
2873 private final static int MSG_DISPATCH_DONE_ANIMATING = 22;
2874 private final static int MSG_INVALIDATE_WORLD = 23;
2875 private final static int MSG_WINDOW_MOVED = 24;
2877 final class ViewRootHandler extends Handler {
2879 public String getMessageName(Message message) {
2880 switch (message.what) {
2881 case MSG_INVALIDATE:
2882 return "MSG_INVALIDATE";
2883 case MSG_INVALIDATE_RECT:
2884 return "MSG_INVALIDATE_RECT";
2888 return "MSG_RESIZED";
2889 case MSG_RESIZED_REPORT:
2890 return "MSG_RESIZED_REPORT";
2891 case MSG_WINDOW_FOCUS_CHANGED:
2892 return "MSG_WINDOW_FOCUS_CHANGED";
2893 case MSG_DISPATCH_KEY:
2894 return "MSG_DISPATCH_KEY";
2895 case MSG_DISPATCH_APP_VISIBILITY:
2896 return "MSG_DISPATCH_APP_VISIBILITY";
2897 case MSG_DISPATCH_GET_NEW_SURFACE:
2898 return "MSG_DISPATCH_GET_NEW_SURFACE";
2899 case MSG_IME_FINISHED_EVENT:
2900 return "MSG_IME_FINISHED_EVENT";
2901 case MSG_DISPATCH_KEY_FROM_IME:
2902 return "MSG_DISPATCH_KEY_FROM_IME";
2903 case MSG_FINISH_INPUT_CONNECTION:
2904 return "MSG_FINISH_INPUT_CONNECTION";
2905 case MSG_CHECK_FOCUS:
2906 return "MSG_CHECK_FOCUS";
2907 case MSG_CLOSE_SYSTEM_DIALOGS:
2908 return "MSG_CLOSE_SYSTEM_DIALOGS";
2909 case MSG_DISPATCH_DRAG_EVENT:
2910 return "MSG_DISPATCH_DRAG_EVENT";
2911 case MSG_DISPATCH_DRAG_LOCATION_EVENT:
2912 return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
2913 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
2914 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
2915 case MSG_UPDATE_CONFIGURATION:
2916 return "MSG_UPDATE_CONFIGURATION";
2917 case MSG_PROCESS_INPUT_EVENTS:
2918 return "MSG_PROCESS_INPUT_EVENTS";
2919 case MSG_DISPATCH_SCREEN_STATE:
2920 return "MSG_DISPATCH_SCREEN_STATE";
2921 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
2922 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
2923 case MSG_DISPATCH_DONE_ANIMATING:
2924 return "MSG_DISPATCH_DONE_ANIMATING";
2925 case MSG_WINDOW_MOVED:
2926 return "MSG_WINDOW_MOVED";
2928 return super.getMessageName(message);
2932 public void handleMessage(Message msg) {
2934 case MSG_INVALIDATE:
2935 ((View) msg.obj).invalidate();
2937 case MSG_INVALIDATE_RECT:
2938 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2939 info.target.invalidate(info.left, info.top, info.right, info.bottom);
2942 case MSG_IME_FINISHED_EVENT:
2943 handleImeFinishedEvent(msg.arg1, msg.arg2 != 0);
2945 case MSG_PROCESS_INPUT_EVENTS:
2946 mProcessInputEventsScheduled = false;
2947 doProcessInputEvents();
2949 case MSG_DISPATCH_APP_VISIBILITY:
2950 handleAppVisibility(msg.arg1 != 0);
2952 case MSG_DISPATCH_GET_NEW_SURFACE:
2953 handleGetNewSurface();
2956 // Recycled in the fall through...
2957 SomeArgs args = (SomeArgs) msg.obj;
2958 if (mWinFrame.equals(args.arg1)
2959 && mPendingContentInsets.equals(args.arg2)
2960 && mPendingVisibleInsets.equals(args.arg3)
2961 && args.arg4 == null) {
2964 } // fall through...
2965 case MSG_RESIZED_REPORT:
2967 SomeArgs args = (SomeArgs) msg.obj;
2969 Configuration config = (Configuration) args.arg4;
2970 if (config != null) {
2971 updateConfiguration(config, false);
2974 mWinFrame.set((Rect) args.arg1);
2975 mPendingContentInsets.set((Rect) args.arg2);
2976 mPendingVisibleInsets.set((Rect) args.arg3);
2980 if (msg.what == MSG_RESIZED_REPORT) {
2981 mReportNextDraw = true;
2984 if (mView != null) {
2991 case MSG_WINDOW_MOVED:
2993 final int w = mWinFrame.width();
2994 final int h = mWinFrame.height();
2995 final int l = msg.arg1;
2996 final int t = msg.arg2;
2998 mWinFrame.right = l + w;
3000 mWinFrame.bottom = t + h;
3002 if (mView != null) {
3008 case MSG_WINDOW_FOCUS_CHANGED: {
3010 boolean hasWindowFocus = msg.arg1 != 0;
3011 mAttachInfo.mHasWindowFocus = hasWindowFocus;
3013 profileRendering(hasWindowFocus);
3015 if (hasWindowFocus) {
3016 boolean inTouchMode = msg.arg2 != 0;
3017 ensureTouchModeLocally(inTouchMode);
3019 if (mAttachInfo.mHardwareRenderer != null &&
3020 mSurface != null && mSurface.isValid()) {
3021 mFullRedrawNeeded = true;
3023 if (mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3024 mWidth, mHeight, mHolder.getSurface())) {
3025 mFullRedrawNeeded = true;
3027 } catch (Surface.OutOfResourcesException e) {
3028 Log.e(TAG, "OutOfResourcesException locking surface", e);
3030 if (!mWindowSession.outOfMemory(mWindow)) {
3031 Slog.w(TAG, "No processes killed for memory; killing self");
3032 Process.killProcess(Process.myPid());
3034 } catch (RemoteException ex) {
3037 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3043 mLastWasImTarget = WindowManager.LayoutParams
3044 .mayUseInputMethod(mWindowAttributes.flags);
3046 InputMethodManager imm = InputMethodManager.peekInstance();
3047 if (mView != null) {
3048 if (hasWindowFocus && imm != null && mLastWasImTarget) {
3049 imm.startGettingWindowFocus(mView);
3051 mAttachInfo.mKeyDispatchState.reset();
3052 mView.dispatchWindowFocusChanged(hasWindowFocus);
3055 // Note: must be done after the focus change callbacks,
3056 // so all of the view state is set up correctly.
3057 if (hasWindowFocus) {
3058 if (imm != null && mLastWasImTarget) {
3059 imm.onWindowFocus(mView, mView.findFocus(),
3060 mWindowAttributes.softInputMode,
3061 !mHasHadWindowFocus, mWindowAttributes.flags);
3063 // Clear the forward bit. We can just do this directly, since
3064 // the window manager doesn't care about it.
3065 mWindowAttributes.softInputMode &=
3066 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3067 ((WindowManager.LayoutParams)mView.getLayoutParams())
3069 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3070 mHasHadWindowFocus = true;
3073 setAccessibilityFocus(null, null);
3075 if (mView != null && mAccessibilityManager.isEnabled()) {
3076 if (hasWindowFocus) {
3077 mView.sendAccessibilityEvent(
3078 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3086 case MSG_DISPATCH_KEY: {
3087 KeyEvent event = (KeyEvent)msg.obj;
3088 enqueueInputEvent(event, null, 0, true);
3090 case MSG_DISPATCH_KEY_FROM_IME: {
3091 if (LOCAL_LOGV) Log.v(
3092 TAG, "Dispatching key "
3093 + msg.obj + " from IME to " + mView);
3094 KeyEvent event = (KeyEvent)msg.obj;
3095 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3096 // The IME is trying to say this event is from the
3097 // system! Bad bad bad!
3098 //noinspection UnusedAssignment
3099 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
3101 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3103 case MSG_FINISH_INPUT_CONNECTION: {
3104 InputMethodManager imm = InputMethodManager.peekInstance();
3106 imm.reportFinishInputConnection((InputConnection)msg.obj);
3109 case MSG_CHECK_FOCUS: {
3110 InputMethodManager imm = InputMethodManager.peekInstance();
3115 case MSG_CLOSE_SYSTEM_DIALOGS: {
3116 if (mView != null) {
3117 mView.onCloseSystemDialogs((String)msg.obj);
3120 case MSG_DISPATCH_DRAG_EVENT:
3121 case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3122 DragEvent event = (DragEvent)msg.obj;
3123 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
3124 handleDragEvent(event);
3126 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3127 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3129 case MSG_UPDATE_CONFIGURATION: {
3130 Configuration config = (Configuration)msg.obj;
3131 if (config.isOtherSeqNewer(mLastConfiguration)) {
3132 config = mLastConfiguration;
3134 updateConfiguration(config, false);
3136 case MSG_DISPATCH_SCREEN_STATE: {
3137 if (mView != null) {
3138 handleScreenStateChange(msg.arg1 == 1);
3141 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3142 setAccessibilityFocus(null, null);
3144 case MSG_DISPATCH_DONE_ANIMATING: {
3145 handleDispatchDoneAnimating();
3147 case MSG_INVALIDATE_WORLD: {
3148 if (mView != null) {
3149 invalidateWorld(mView);
3156 final ViewRootHandler mHandler = new ViewRootHandler();
3159 * Something in the current window tells us we need to change the touch mode. For
3160 * example, we are not in touch mode, and the user touches the screen.
3162 * If the touch mode has changed, tell the window manager, and handle it locally.
3164 * @param inTouchMode Whether we want to be in touch mode.
3165 * @return True if the touch mode changed and focus changed was changed as a result
3167 boolean ensureTouchMode(boolean inTouchMode) {
3168 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3169 + "touch mode is " + mAttachInfo.mInTouchMode);
3170 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3172 // tell the window manager
3174 mWindowSession.setInTouchMode(inTouchMode);
3175 } catch (RemoteException e) {
3176 throw new RuntimeException(e);
3179 // handle the change
3180 return ensureTouchModeLocally(inTouchMode);
3184 * Ensure that the touch mode for this window is set, and if it is changing,
3185 * take the appropriate action.
3186 * @param inTouchMode Whether we want to be in touch mode.
3187 * @return True if the touch mode changed and focus changed was changed as a result
3189 private boolean ensureTouchModeLocally(boolean inTouchMode) {
3190 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3191 + "touch mode is " + mAttachInfo.mInTouchMode);
3193 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3195 mAttachInfo.mInTouchMode = inTouchMode;
3196 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3198 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3201 private boolean enterTouchMode() {
3202 if (mView != null) {
3203 if (mView.hasFocus()) {
3204 // note: not relying on mFocusedView here because this could
3205 // be when the window is first being added, and mFocused isn't
3207 final View focused = mView.findFocus();
3208 if (focused != null && !focused.isFocusableInTouchMode()) {
3210 final ViewGroup ancestorToTakeFocus =
3211 findAncestorToTakeFocusInTouchMode(focused);
3212 if (ancestorToTakeFocus != null) {
3213 // there is an ancestor that wants focus after its descendants that
3214 // is focusable in touch mode.. give it focus
3215 return ancestorToTakeFocus.requestFocus();
3217 // nothing appropriate to have focus in touch mode, clear it out
3219 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
3220 mFocusedView = null;
3221 mOldFocusedView = null;
3231 * Find an ancestor of focused that wants focus after its descendants and is
3232 * focusable in touch mode.
3233 * @param focused The currently focused view.
3234 * @return An appropriate view, or null if no such view exists.
3236 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3237 ViewParent parent = focused.getParent();
3238 while (parent instanceof ViewGroup) {
3239 final ViewGroup vgParent = (ViewGroup) parent;
3240 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3241 && vgParent.isFocusableInTouchMode()) {
3244 if (vgParent.isRootNamespace()) {
3247 parent = vgParent.getParent();
3253 private boolean leaveTouchMode() {
3254 if (mView != null) {
3255 if (mView.hasFocus()) {
3256 // i learned the hard way to not trust mFocusedView :)
3257 mFocusedView = mView.findFocus();
3258 if (!(mFocusedView instanceof ViewGroup)) {
3259 // some view has focus, let it keep it
3261 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
3262 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3263 // some view group has focus, and doesn't prefer its children
3264 // over itself for focus, so let them keep it.
3269 // find the best view to give focus to in this brave new non-touch-mode
3271 final View focused = focusSearch(null, View.FOCUS_DOWN);
3272 if (focused != null) {
3273 return focused.requestFocus(View.FOCUS_DOWN);
3279 private int deliverInputEvent(QueuedInputEvent q) {
3280 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
3282 if (q.mEvent instanceof KeyEvent) {
3283 return deliverKeyEvent(q);
3285 final int source = q.mEvent.getSource();
3286 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3287 return deliverPointerEvent(q);
3288 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3289 return deliverTrackballEvent(q);
3291 return deliverGenericMotionEvent(q);
3295 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3299 private int deliverInputEventPostIme(QueuedInputEvent q) {
3300 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEventPostIme");
3302 if (q.mEvent instanceof KeyEvent) {
3303 return deliverKeyEventPostIme(q);
3305 final int source = q.mEvent.getSource();
3306 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3307 return deliverTrackballEventPostIme(q);
3309 return deliverGenericMotionEventPostIme(q);
3313 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3317 private int deliverPointerEvent(QueuedInputEvent q) {
3318 final MotionEvent event = (MotionEvent)q.mEvent;
3319 final boolean isTouchEvent = event.isTouchEvent();
3320 if (mInputEventConsistencyVerifier != null) {
3322 mInputEventConsistencyVerifier.onTouchEvent(event, 0);
3324 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3328 // If there is no view, then the event will not be handled.
3329 if (mView == null || !mAdded) {
3330 return EVENT_NOT_HANDLED;
3333 // Translate the pointer event for compatibility, if needed.
3334 if (mTranslator != null) {
3335 mTranslator.translateEventInScreenToAppWindow(event);
3338 // Enter touch mode on down or scroll.
3339 final int action = event.getAction();
3340 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3341 ensureTouchMode(true);
3344 // Offset the scroll position.
3345 if (mCurScrollY != 0) {
3346 event.offsetLocation(0, mCurScrollY);
3348 if (MEASURE_LATENCY) {
3349 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
3352 // Remember the touch position for possible drag-initiation.
3354 mLastTouchPoint.x = event.getRawX();
3355 mLastTouchPoint.y = event.getRawY();
3358 // Dispatch touch to view hierarchy.
3359 boolean handled = mView.dispatchPointerEvent(event);
3360 if (MEASURE_LATENCY) {
3361 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
3363 return handled ? EVENT_HANDLED : EVENT_NOT_HANDLED;
3366 private int deliverTrackballEvent(QueuedInputEvent q) {
3367 final MotionEvent event = (MotionEvent)q.mEvent;
3368 if (mInputEventConsistencyVerifier != null) {
3369 mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
3372 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3374 Log.v(TAG, "Dispatching trackball " + event + " to " + mView);
3376 // Dispatch to the IME before propagating down the view hierarchy.
3377 // The IME will eventually call back into handleImeFinishedEvent.
3378 if (mLastWasImTarget) {
3379 InputMethodManager imm = InputMethodManager.peekInstance();
3381 final int seq = event.getSequenceNumber();
3383 Log.v(TAG, "Sending trackball event to IME: seq="
3384 + seq + " event=" + event);
3385 int result = imm.dispatchTrackballEvent(mView.getContext(), seq, event,
3386 mInputMethodCallback);
3387 if (result != EVENT_NOT_HANDLED) {
3394 // Not dispatching to IME, continue with post IME actions.
3395 return deliverTrackballEventPostIme(q);
3398 private int deliverTrackballEventPostIme(QueuedInputEvent q) {
3399 final MotionEvent event = (MotionEvent) q.mEvent;
3401 // If there is no view, then the event will not be handled.
3402 if (mView == null || !mAdded) {
3403 return EVENT_NOT_HANDLED;
3406 // Deliver the trackball event to the view.
3407 if (mView.dispatchTrackballEvent(event)) {
3408 // If we reach this, we delivered a trackball event to mView and
3409 // mView consumed it. Because we will not translate the trackball
3410 // event into a key event, touch mode will not exit, so we exit
3412 ensureTouchMode(false);
3413 mLastTrackballTime = Integer.MIN_VALUE;
3414 return EVENT_HANDLED;
3417 // Translate the trackball event into DPAD keys and try to deliver those.
3418 final TrackballAxis x = mTrackballAxisX;
3419 final TrackballAxis y = mTrackballAxisY;
3421 long curTime = SystemClock.uptimeMillis();
3422 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
3423 // It has been too long since the last movement,
3424 // so restart at the beginning.
3427 mLastTrackballTime = curTime;
3430 final int action = event.getAction();
3431 final int metaState = event.getMetaState();
3433 case MotionEvent.ACTION_DOWN:
3436 enqueueInputEvent(new KeyEvent(curTime, curTime,
3437 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3438 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3439 InputDevice.SOURCE_KEYBOARD));
3441 case MotionEvent.ACTION_UP:
3444 enqueueInputEvent(new KeyEvent(curTime, curTime,
3445 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3446 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3447 InputDevice.SOURCE_KEYBOARD));
3451 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
3452 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
3453 + " move=" + event.getX()
3454 + " / Y=" + y.position + " step="
3455 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
3456 + " move=" + event.getY());
3457 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
3458 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
3460 // Generate DPAD events based on the trackball movement.
3461 // We pick the axis that has moved the most as the direction of
3462 // the DPAD. When we generate DPAD events for one axis, then the
3463 // other axis is reset -- we don't want to perform DPAD jumps due
3464 // to slight movements in the trackball when making major movements
3465 // along the other axis.
3470 movement = x.generate((2/event.getXPrecision()));
3471 if (movement != 0) {
3472 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
3473 : KeyEvent.KEYCODE_DPAD_LEFT;
3474 accel = x.acceleration;
3477 } else if (yOff > 0) {
3478 movement = y.generate((2/event.getYPrecision()));
3479 if (movement != 0) {
3480 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
3481 : KeyEvent.KEYCODE_DPAD_UP;
3482 accel = y.acceleration;
3488 if (movement < 0) movement = -movement;
3489 int accelMovement = (int)(movement * accel);
3490 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
3491 + " accelMovement=" + accelMovement
3492 + " accel=" + accel);
3493 if (accelMovement > movement) {
3494 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3497 int repeatCount = accelMovement - movement;
3498 enqueueInputEvent(new KeyEvent(curTime, curTime,
3499 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
3500 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3501 InputDevice.SOURCE_KEYBOARD));
3503 while (movement > 0) {
3504 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3507 curTime = SystemClock.uptimeMillis();
3508 enqueueInputEvent(new KeyEvent(curTime, curTime,
3509 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
3510 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3511 InputDevice.SOURCE_KEYBOARD));
3512 enqueueInputEvent(new KeyEvent(curTime, curTime,
3513 KeyEvent.ACTION_UP, keycode, 0, metaState,
3514 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3515 InputDevice.SOURCE_KEYBOARD));
3517 mLastTrackballTime = curTime;
3520 // Unfortunately we can't tell whether the application consumed the keys, so
3521 // we always consider the trackball event handled.
3522 return EVENT_HANDLED;
3525 private int deliverGenericMotionEvent(QueuedInputEvent q) {
3526 final MotionEvent event = (MotionEvent)q.mEvent;
3527 if (mInputEventConsistencyVerifier != null) {
3528 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3530 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3532 Log.v(TAG, "Dispatching generic motion " + event + " to " + mView);
3534 // Dispatch to the IME before propagating down the view hierarchy.
3535 // The IME will eventually call back into handleImeFinishedEvent.
3536 if (mLastWasImTarget) {
3537 InputMethodManager imm = InputMethodManager.peekInstance();
3539 final int seq = event.getSequenceNumber();
3541 Log.v(TAG, "Sending generic motion event to IME: seq="
3542 + seq + " event=" + event);
3543 int result = imm.dispatchGenericMotionEvent(mView.getContext(), seq, event,
3544 mInputMethodCallback);
3545 if (result != EVENT_NOT_HANDLED) {
3552 // Not dispatching to IME, continue with post IME actions.
3553 return deliverGenericMotionEventPostIme(q);
3556 private int deliverGenericMotionEventPostIme(QueuedInputEvent q) {
3557 final MotionEvent event = (MotionEvent) q.mEvent;
3558 final int source = event.getSource();
3559 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
3560 final boolean isTouchPad = (source & InputDevice.SOURCE_CLASS_POSITION) != 0;
3562 // If there is no view, then the event will not be handled.
3563 if (mView == null || !mAdded) {
3565 updateJoystickDirection(event, false);
3566 } else if (isTouchPad) {
3567 //Convert TouchPad motion into a TrackBall event
3568 mSimulatedTrackball.updateTrackballDirection(this, event);
3570 return EVENT_NOT_HANDLED;
3573 // Deliver the event to the view.
3574 if (mView.dispatchGenericMotionEvent(event)) {
3576 updateJoystickDirection(event, false);
3577 } else if (isTouchPad) {
3578 //Convert TouchPad motion into a TrackBall event
3579 mSimulatedTrackball.updateTrackballDirection(this, event);
3581 return EVENT_HANDLED;
3585 // Translate the joystick event into DPAD keys and try to deliver
3587 updateJoystickDirection(event, true);
3588 return EVENT_HANDLED;
3591 //Convert TouchPad motion into a TrackBall event
3592 mSimulatedTrackball.updateTrackballDirection(this, event);
3593 return EVENT_HANDLED;
3595 return EVENT_NOT_HANDLED;
3598 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
3599 final long time = event.getEventTime();
3600 final int metaState = event.getMetaState();
3601 final int deviceId = event.getDeviceId();
3602 final int source = event.getSource();
3604 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
3605 if (xDirection == 0) {
3606 xDirection = joystickAxisValueToDirection(event.getX());
3609 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
3610 if (yDirection == 0) {
3611 yDirection = joystickAxisValueToDirection(event.getY());
3614 if (xDirection != mLastJoystickXDirection) {
3615 if (mLastJoystickXKeyCode != 0) {
3616 enqueueInputEvent(new KeyEvent(time, time,
3617 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
3618 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3619 mLastJoystickXKeyCode = 0;
3622 mLastJoystickXDirection = xDirection;
3624 if (xDirection != 0 && synthesizeNewKeys) {
3625 mLastJoystickXKeyCode = xDirection > 0
3626 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3627 enqueueInputEvent(new KeyEvent(time, time,
3628 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3629 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3633 if (yDirection != mLastJoystickYDirection) {
3634 if (mLastJoystickYKeyCode != 0) {
3635 enqueueInputEvent(new KeyEvent(time, time,
3636 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3637 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3638 mLastJoystickYKeyCode = 0;
3641 mLastJoystickYDirection = yDirection;
3643 if (yDirection != 0 && synthesizeNewKeys) {
3644 mLastJoystickYKeyCode = yDirection > 0
3645 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3646 enqueueInputEvent(new KeyEvent(time, time,
3647 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3648 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3653 private static int joystickAxisValueToDirection(float value) {
3654 if (value >= 0.5f) {
3656 } else if (value <= -0.5f) {
3664 * Returns true if the key is used for keyboard navigation.
3665 * @param keyEvent The key event.
3666 * @return True if the key is used for keyboard navigation.
3668 private static boolean isNavigationKey(KeyEvent keyEvent) {
3669 switch (keyEvent.getKeyCode()) {
3670 case KeyEvent.KEYCODE_DPAD_LEFT:
3671 case KeyEvent.KEYCODE_DPAD_RIGHT:
3672 case KeyEvent.KEYCODE_DPAD_UP:
3673 case KeyEvent.KEYCODE_DPAD_DOWN:
3674 case KeyEvent.KEYCODE_DPAD_CENTER:
3675 case KeyEvent.KEYCODE_PAGE_UP:
3676 case KeyEvent.KEYCODE_PAGE_DOWN:
3677 case KeyEvent.KEYCODE_MOVE_HOME:
3678 case KeyEvent.KEYCODE_MOVE_END:
3679 case KeyEvent.KEYCODE_TAB:
3680 case KeyEvent.KEYCODE_SPACE:
3681 case KeyEvent.KEYCODE_ENTER:
3688 * Returns true if the key is used for typing.
3689 * @param keyEvent The key event.
3690 * @return True if the key is used for typing.
3692 private static boolean isTypingKey(KeyEvent keyEvent) {
3693 return keyEvent.getUnicodeChar() > 0;
3697 * See if the key event means we should leave touch mode (and leave touch mode if so).
3698 * @param event The key event.
3699 * @return Whether this key event should be consumed (meaning the act of
3700 * leaving touch mode alone is considered the event).
3702 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3703 // Only relevant in touch mode.
3704 if (!mAttachInfo.mInTouchMode) {
3708 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3709 final int action = event.getAction();
3710 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3714 // Don't leave touch mode if the IME told us not to.
3715 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3719 // If the key can be used for keyboard navigation then leave touch mode
3720 // and select a focused view if needed (in ensureTouchMode).
3721 // When a new focused view is selected, we consume the navigation key because
3722 // navigation doesn't make much sense unless a view already has focus so
3723 // the key's purpose is to set focus.
3724 if (isNavigationKey(event)) {
3725 return ensureTouchMode(false);
3728 // If the key can be used for typing then leave touch mode
3729 // and select a focused view if needed (in ensureTouchMode).
3730 // Always allow the view to process the typing key.
3731 if (isTypingKey(event)) {
3732 ensureTouchMode(false);
3739 private int deliverKeyEvent(QueuedInputEvent q) {
3740 final KeyEvent event = (KeyEvent)q.mEvent;
3741 if (mInputEventConsistencyVerifier != null) {
3742 mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3745 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3746 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3748 // Perform predispatching before the IME.
3749 if (mView.dispatchKeyEventPreIme(event)) {
3750 return EVENT_HANDLED;
3753 // Dispatch to the IME before propagating down the view hierarchy.
3754 // The IME will eventually call back into handleImeFinishedEvent.
3755 if (mLastWasImTarget) {
3756 InputMethodManager imm = InputMethodManager.peekInstance();
3758 final int seq = event.getSequenceNumber();
3759 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3760 + seq + " event=" + event);
3761 int result = imm.dispatchKeyEvent(mView.getContext(), seq, event,
3762 mInputMethodCallback);
3763 if (result != EVENT_NOT_HANDLED) {
3770 // Not dispatching to IME, continue with post IME actions.
3771 return deliverKeyEventPostIme(q);
3774 private int deliverKeyEventPostIme(QueuedInputEvent q) {
3775 final KeyEvent event = (KeyEvent)q.mEvent;
3777 // If the view went away, then the event will not be handled.
3778 if (mView == null || !mAdded) {
3779 return EVENT_NOT_HANDLED;
3782 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3783 if (checkForLeavingTouchModeAndConsume(event)) {
3784 return EVENT_HANDLED;
3787 // Make sure the fallback event policy sees all keys that will be delivered to the
3789 mFallbackEventHandler.preDispatchKeyEvent(event);
3791 // Deliver the key to the view hierarchy.
3792 if (mView.dispatchKeyEvent(event)) {
3793 return EVENT_HANDLED;
3796 // If the Control modifier is held, try to interpret the key as a shortcut.
3797 if (event.getAction() == KeyEvent.ACTION_DOWN
3798 && event.isCtrlPressed()
3799 && event.getRepeatCount() == 0
3800 && !KeyEvent.isModifierKey(event.getKeyCode())) {
3801 if (mView.dispatchKeyShortcutEvent(event)) {
3802 return EVENT_HANDLED;
3806 // Apply the fallback event policy.
3807 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3808 return EVENT_HANDLED;
3811 // Handle automatic focus changes.
3812 if (event.getAction() == KeyEvent.ACTION_DOWN) {
3814 switch (event.getKeyCode()) {
3815 case KeyEvent.KEYCODE_DPAD_LEFT:
3816 if (event.hasNoModifiers()) {
3817 direction = View.FOCUS_LEFT;
3820 case KeyEvent.KEYCODE_DPAD_RIGHT:
3821 if (event.hasNoModifiers()) {
3822 direction = View.FOCUS_RIGHT;
3825 case KeyEvent.KEYCODE_DPAD_UP:
3826 if (event.hasNoModifiers()) {
3827 direction = View.FOCUS_UP;
3830 case KeyEvent.KEYCODE_DPAD_DOWN:
3831 if (event.hasNoModifiers()) {
3832 direction = View.FOCUS_DOWN;
3835 case KeyEvent.KEYCODE_TAB:
3836 if (event.hasNoModifiers()) {
3837 direction = View.FOCUS_FORWARD;
3838 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3839 direction = View.FOCUS_BACKWARD;
3843 if (direction != 0) {
3844 View focused = mView.findFocus();
3845 if (focused != null) {
3846 View v = focused.focusSearch(direction);
3847 if (v != null && v != focused) {
3848 // do the math the get the interesting rect
3849 // of previous focused into the coord system of
3850 // newly focused view
3851 focused.getFocusedRect(mTempRect);
3852 if (mView instanceof ViewGroup) {
3853 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3854 focused, mTempRect);
3855 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3858 if (v.requestFocus(direction, mTempRect)) {
3859 playSoundEffect(SoundEffectConstants
3860 .getContantForFocusDirection(direction));
3861 return EVENT_HANDLED;
3865 // Give the focused view a last chance to handle the dpad key.
3866 if (mView.dispatchUnhandledMove(focused, direction)) {
3867 return EVENT_HANDLED;
3873 // Key was unhandled.
3874 return EVENT_NOT_HANDLED;
3878 void setLocalDragState(Object obj) {
3879 mLocalDragState = obj;
3882 private void handleDragEvent(DragEvent event) {
3883 // From the root, only drag start/end/location are dispatched. entered/exited
3884 // are determined and dispatched by the viewgroup hierarchy, who then report
3885 // that back here for ultimate reporting back to the framework.
3886 if (mView != null && mAdded) {
3887 final int what = event.mAction;
3889 if (what == DragEvent.ACTION_DRAG_EXITED) {
3890 // A direct EXITED event means that the window manager knows we've just crossed
3891 // a window boundary, so the current drag target within this one must have
3892 // just been exited. Send it the usual notifications and then we're done
3894 mView.dispatchDragEvent(event);
3896 // Cache the drag description when the operation starts, then fill it in
3897 // on subsequent calls as a convenience
3898 if (what == DragEvent.ACTION_DRAG_STARTED) {
3899 mCurrentDragView = null; // Start the current-recipient tracking
3900 mDragDescription = event.mClipDescription;
3902 event.mClipDescription = mDragDescription;
3905 // For events with a [screen] location, translate into window coordinates
3906 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3907 mDragPoint.set(event.mX, event.mY);
3908 if (mTranslator != null) {
3909 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3912 if (mCurScrollY != 0) {
3913 mDragPoint.offset(0, mCurScrollY);
3916 event.mX = mDragPoint.x;
3917 event.mY = mDragPoint.y;
3920 // Remember who the current drag target is pre-dispatch
3921 final View prevDragView = mCurrentDragView;
3923 // Now dispatch the drag/drop event
3924 boolean result = mView.dispatchDragEvent(event);
3926 // If we changed apparent drag target, tell the OS about it
3927 if (prevDragView != mCurrentDragView) {
3929 if (prevDragView != null) {
3930 mWindowSession.dragRecipientExited(mWindow);
3932 if (mCurrentDragView != null) {
3933 mWindowSession.dragRecipientEntered(mWindow);
3935 } catch (RemoteException e) {
3936 Slog.e(TAG, "Unable to note drag target change");
3940 // Report the drop result when we're done
3941 if (what == DragEvent.ACTION_DROP) {
3942 mDragDescription = null;
3944 Log.i(TAG, "Reporting drop result: " + result);
3945 mWindowSession.reportDropResult(mWindow, result);
3946 } catch (RemoteException e) {
3947 Log.e(TAG, "Unable to report drop result");
3951 // When the drag operation ends, release any local state object
3952 // that may have been in use
3953 if (what == DragEvent.ACTION_DRAG_ENDED) {
3954 setLocalDragState(null);
3961 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
3962 if (mSeq != args.seq) {
3963 // The sequence has changed, so we need to update our value and make
3964 // sure to do a traversal afterward so the window manager is given our
3965 // most recent data.
3967 mAttachInfo.mForceReportNewAttributes = true;
3968 scheduleTraversals();
3970 if (mView == null) return;
3971 if (args.localChanges != 0) {
3972 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
3974 if (mAttachInfo != null) {
3975 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
3976 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
3977 mAttachInfo.mGlobalSystemUiVisibility = visibility;
3978 mView.dispatchSystemUiVisibilityChanged(visibility);
3983 public void handleDispatchDoneAnimating() {
3984 if (mWindowsAnimating) {
3985 mWindowsAnimating = false;
3986 if (!mDirty.isEmpty() || mIsAnimating) {
3987 scheduleTraversals();
3992 public void getLastTouchPoint(Point outLocation) {
3993 outLocation.x = (int) mLastTouchPoint.x;
3994 outLocation.y = (int) mLastTouchPoint.y;
3997 public void setDragFocus(View newDragTarget) {
3998 if (mCurrentDragView != newDragTarget) {
3999 mCurrentDragView = newDragTarget;
4003 private AudioManager getAudioManager() {
4004 if (mView == null) {
4005 throw new IllegalStateException("getAudioManager called when there is no mView");
4007 if (mAudioManager == null) {
4008 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
4010 return mAudioManager;
4013 public AccessibilityInteractionController getAccessibilityInteractionController() {
4014 if (mView == null) {
4015 throw new IllegalStateException("getAccessibilityInteractionController"
4016 + " called when there is no mView");
4018 if (mAccessibilityInteractionController == null) {
4019 mAccessibilityInteractionController = new AccessibilityInteractionController(this);
4021 return mAccessibilityInteractionController;
4024 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
4025 boolean insetsPending) throws RemoteException {
4027 float appScale = mAttachInfo.mApplicationScale;
4028 boolean restore = false;
4029 if (params != null && mTranslator != null) {
4032 mTranslator.translateWindowLayout(params);
4034 if (params != null) {
4035 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
4037 mPendingConfiguration.seq = 0;
4038 //Log.d(TAG, ">>>>>> CALLING relayout");
4039 if (params != null && mOrigWindowType != params.type) {
4040 // For compatibility with old apps, don't crash here.
4041 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4042 Slog.w(TAG, "Window type can not be changed after "
4043 + "the window is added; ignoring change of " + mView);
4044 params.type = mOrigWindowType;
4047 int relayoutResult = mWindowSession.relayout(
4048 mWindow, mSeq, params,
4049 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
4050 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
4051 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
4052 mWinFrame, mPendingContentInsets, mPendingVisibleInsets,
4053 mPendingConfiguration, mSurface);
4054 //Log.d(TAG, "<<<<<< BACK FROM relayout");
4059 if (mTranslator != null) {
4060 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
4061 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
4062 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
4064 return relayoutResult;
4070 public void playSoundEffect(int effectId) {
4074 final AudioManager audioManager = getAudioManager();
4077 case SoundEffectConstants.CLICK:
4078 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
4080 case SoundEffectConstants.NAVIGATION_DOWN:
4081 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
4083 case SoundEffectConstants.NAVIGATION_LEFT:
4084 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
4086 case SoundEffectConstants.NAVIGATION_RIGHT:
4087 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
4089 case SoundEffectConstants.NAVIGATION_UP:
4090 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
4093 throw new IllegalArgumentException("unknown effect id " + effectId +
4094 " not defined in " + SoundEffectConstants.class.getCanonicalName());
4096 } catch (IllegalStateException e) {
4097 // Exception thrown by getAudioManager() when mView is null
4098 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
4099 e.printStackTrace();
4106 public boolean performHapticFeedback(int effectId, boolean always) {
4108 return mWindowSession.performHapticFeedback(mWindow, effectId, always);
4109 } catch (RemoteException e) {
4117 public View focusSearch(View focused, int direction) {
4119 if (!(mView instanceof ViewGroup)) {
4122 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
4125 public void debug() {
4129 public void dumpGfxInfo(int[] info) {
4130 info[0] = info[1] = 0;
4131 if (mView != null) {
4132 getGfxInfo(mView, info);
4136 private static void getGfxInfo(View view, int[] info) {
4137 DisplayList displayList = view.mDisplayList;
4139 if (displayList != null) {
4140 info[1] += displayList.getSize();
4143 if (view instanceof ViewGroup) {
4144 ViewGroup group = (ViewGroup) view;
4146 int count = group.getChildCount();
4147 for (int i = 0; i < count; i++) {
4148 getGfxInfo(group.getChildAt(i), info);
4153 public void die(boolean immediate) {
4154 // Make sure we do execute immediately if we are in the middle of a traversal or the damage
4155 // done by dispatchDetachedFromWindow will cause havoc on return.
4156 if (immediate && !mIsInTraversal) {
4160 destroyHardwareRenderer();
4162 Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
4163 " window=" + this + ", title=" + mWindowAttributes.getTitle());
4165 mHandler.sendEmptyMessage(MSG_DIE);
4171 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
4172 synchronized (this) {
4174 dispatchDetachedFromWindow();
4177 if (mAdded && !mFirst) {
4178 invalidateDisplayLists();
4179 destroyHardwareRenderer();
4181 if (mView != null) {
4182 int viewVisibility = mView.getVisibility();
4183 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
4184 if (mWindowAttributesChanged || viewVisibilityChanged) {
4185 // If layout params have been changed, first give them
4186 // to the window manager to make sure it has the correct
4189 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
4190 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
4191 mWindowSession.finishDrawing(mWindow);
4193 } catch (RemoteException e) {
4205 public void requestUpdateConfiguration(Configuration config) {
4206 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
4207 mHandler.sendMessage(msg);
4210 public void loadSystemProperties() {
4211 mHandler.post(new Runnable() {
4215 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
4216 profileRendering(mAttachInfo.mHasWindowFocus);
4218 // Hardware rendering
4219 if (mAttachInfo.mHardwareRenderer != null) {
4220 if (mAttachInfo.mHardwareRenderer.loadSystemProperties(mHolder.getSurface())) {
4226 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
4227 if (layout != mAttachInfo.mDebugLayout) {
4228 mAttachInfo.mDebugLayout = layout;
4229 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
4230 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
4237 private void destroyHardwareRenderer() {
4238 AttachInfo attachInfo = mAttachInfo;
4239 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer;
4241 if (hardwareRenderer != null) {
4242 if (mView != null) {
4243 hardwareRenderer.destroyHardwareResources(mView);
4245 hardwareRenderer.destroy(true);
4246 hardwareRenderer.setRequested(false);
4248 attachInfo.mHardwareRenderer = null;
4249 attachInfo.mHardwareAccelerated = false;
4253 void dispatchImeFinishedEvent(int seq, boolean handled) {
4254 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT);
4256 msg.arg2 = handled ? 1 : 0;
4257 msg.setAsynchronous(true);
4258 mHandler.sendMessage(msg);
4261 public void dispatchFinishInputConnection(InputConnection connection) {
4262 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
4263 mHandler.sendMessage(msg);
4266 public void dispatchResized(Rect frame, Rect contentInsets,
4267 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4268 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
4269 + " contentInsets=" + contentInsets.toShortString()
4270 + " visibleInsets=" + visibleInsets.toShortString()
4271 + " reportDraw=" + reportDraw);
4272 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
4273 if (mTranslator != null) {
4274 mTranslator.translateRectInScreenToAppWindow(frame);
4275 mTranslator.translateRectInScreenToAppWindow(contentInsets);
4276 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
4278 SomeArgs args = SomeArgs.obtain();
4279 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
4280 args.arg1 = sameProcessCall ? new Rect(frame) : frame;
4281 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
4282 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
4283 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
4285 mHandler.sendMessage(msg);
4288 public void dispatchMoved(int newX, int newY) {
4289 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
4290 if (mTranslator != null) {
4291 PointF point = new PointF(newX, newY);
4292 mTranslator.translatePointInScreenToAppWindow(point);
4293 newX = (int) (point.x + 0.5);
4294 newY = (int) (point.y + 0.5);
4296 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
4297 mHandler.sendMessage(msg);
4301 * Represents a pending input event that is waiting in a queue.
4303 * Input events are processed in serial order by the timestamp specified by
4304 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers
4305 * one input event to the application at a time and waits for the application
4306 * to finish handling it before delivering the next one.
4308 * However, because the application or IME can synthesize and inject multiple
4309 * key events at a time without going through the input dispatcher, we end up
4310 * needing a queue on the application's side.
4312 private static final class QueuedInputEvent {
4313 public static final int FLAG_DELIVER_POST_IME = 1;
4315 public QueuedInputEvent mNext;
4317 public InputEvent mEvent;
4318 public InputEventReceiver mReceiver;
4322 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
4323 InputEventReceiver receiver, int flags) {
4324 QueuedInputEvent q = mQueuedInputEventPool;
4326 mQueuedInputEventPoolSize -= 1;
4327 mQueuedInputEventPool = q.mNext;
4330 q = new QueuedInputEvent();
4334 q.mReceiver = receiver;
4339 private void recycleQueuedInputEvent(QueuedInputEvent q) {
4343 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
4344 mQueuedInputEventPoolSize += 1;
4345 q.mNext = mQueuedInputEventPool;
4346 mQueuedInputEventPool = q;
4350 void enqueueInputEvent(InputEvent event) {
4351 enqueueInputEvent(event, null, 0, false);
4354 void enqueueInputEvent(InputEvent event,
4355 InputEventReceiver receiver, int flags, boolean processImmediately) {
4356 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
4358 // Always enqueue the input event in order, regardless of its time stamp.
4359 // We do this because the application or the IME may inject key events
4360 // in response to touch events and we want to ensure that the injected keys
4361 // are processed in the order they were received and we cannot trust that
4362 // the time stamp of injected events are monotonic.
4363 QueuedInputEvent last = mFirstPendingInputEvent;
4365 mFirstPendingInputEvent = q;
4367 while (last.mNext != null) {
4373 if (processImmediately) {
4374 doProcessInputEvents();
4376 scheduleProcessInputEvents();
4380 private void scheduleProcessInputEvents() {
4381 if (!mProcessInputEventsScheduled) {
4382 mProcessInputEventsScheduled = true;
4383 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
4384 msg.setAsynchronous(true);
4385 mHandler.sendMessage(msg);
4389 void doProcessInputEvents() {
4390 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) {
4391 QueuedInputEvent q = mFirstPendingInputEvent;
4392 mFirstPendingInputEvent = q.mNext;
4394 mCurrentInputEvent = q;
4396 final int result = deliverInputEvent(q);
4397 if (result != EVENT_IN_PROGRESS) {
4398 finishCurrentInputEvent(result == EVENT_HANDLED);
4402 // We are done processing all input events that we can process right now
4403 // so we can clear the pending flag immediately.
4404 if (mProcessInputEventsScheduled) {
4405 mProcessInputEventsScheduled = false;
4406 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
4410 void handleImeFinishedEvent(int seq, boolean handled) {
4411 final QueuedInputEvent q = mCurrentInputEvent;
4412 if (q != null && q.mEvent.getSequenceNumber() == seq) {
4414 Log.v(TAG, "IME finished event: seq=" + seq
4415 + " handled=" + handled + " event=" + q);
4419 // If the window doesn't currently have input focus, then drop
4420 // this event. This could be an event that came back from the
4421 // IME dispatch but the window has lost focus in the meantime.
4422 if (!mAttachInfo.mHasWindowFocus && !isTerminalInputEvent(q.mEvent)) {
4423 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent);
4425 final int result = deliverInputEventPostIme(q);
4426 if (result == EVENT_HANDLED) {
4431 finishCurrentInputEvent(handled);
4433 // Immediately start processing the next input event.
4434 doProcessInputEvents();
4437 Log.v(TAG, "IME finished event: seq=" + seq
4438 + " handled=" + handled + ", event not found!");
4443 private void finishCurrentInputEvent(boolean handled) {
4444 final QueuedInputEvent q = mCurrentInputEvent;
4445 mCurrentInputEvent = null;
4447 if (q.mReceiver != null) {
4448 q.mReceiver.finishInputEvent(q.mEvent, handled);
4450 q.mEvent.recycleIfNeededAfterDispatch();
4453 recycleQueuedInputEvent(q);
4456 private static boolean isTerminalInputEvent(InputEvent event) {
4457 if (event instanceof KeyEvent) {
4458 final KeyEvent keyEvent = (KeyEvent)event;
4459 return keyEvent.getAction() == KeyEvent.ACTION_UP;
4461 final MotionEvent motionEvent = (MotionEvent)event;
4462 final int action = motionEvent.getAction();
4463 return action == MotionEvent.ACTION_UP
4464 || action == MotionEvent.ACTION_CANCEL
4465 || action == MotionEvent.ACTION_HOVER_EXIT;
4469 void scheduleConsumeBatchedInput() {
4470 if (!mConsumeBatchedInputScheduled) {
4471 mConsumeBatchedInputScheduled = true;
4472 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
4473 mConsumedBatchedInputRunnable, null);
4477 void unscheduleConsumeBatchedInput() {
4478 if (mConsumeBatchedInputScheduled) {
4479 mConsumeBatchedInputScheduled = false;
4480 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
4481 mConsumedBatchedInputRunnable, null);
4485 void doConsumeBatchedInput(long frameTimeNanos) {
4486 if (mConsumeBatchedInputScheduled) {
4487 mConsumeBatchedInputScheduled = false;
4488 if (mInputEventReceiver != null) {
4489 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos);
4491 doProcessInputEvents();
4495 final class TraversalRunnable implements Runnable {
4501 final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
4503 final class WindowInputEventReceiver extends InputEventReceiver {
4504 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
4505 super(inputChannel, looper);
4509 public void onInputEvent(InputEvent event) {
4510 enqueueInputEvent(event, this, 0, true);
4514 public void onBatchedInputEventPending() {
4515 scheduleConsumeBatchedInput();
4519 public void dispose() {
4520 unscheduleConsumeBatchedInput();
4524 WindowInputEventReceiver mInputEventReceiver;
4526 final class ConsumeBatchedInputRunnable implements Runnable {
4529 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
4532 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
4533 new ConsumeBatchedInputRunnable();
4534 boolean mConsumeBatchedInputScheduled;
4536 final class InvalidateOnAnimationRunnable implements Runnable {
4537 private boolean mPosted;
4538 private ArrayList<View> mViews = new ArrayList<View>();
4539 private ArrayList<AttachInfo.InvalidateInfo> mViewRects =
4540 new ArrayList<AttachInfo.InvalidateInfo>();
4541 private View[] mTempViews;
4542 private AttachInfo.InvalidateInfo[] mTempViewRects;
4544 public void addView(View view) {
4545 synchronized (this) {
4547 postIfNeededLocked();
4551 public void addViewRect(AttachInfo.InvalidateInfo info) {
4552 synchronized (this) {
4553 mViewRects.add(info);
4554 postIfNeededLocked();
4558 public void removeView(View view) {
4559 synchronized (this) {
4560 mViews.remove(view);
4562 for (int i = mViewRects.size(); i-- > 0; ) {
4563 AttachInfo.InvalidateInfo info = mViewRects.get(i);
4564 if (info.target == view) {
4565 mViewRects.remove(i);
4570 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
4571 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
4579 final int viewCount;
4580 final int viewRectCount;
4581 synchronized (this) {
4584 viewCount = mViews.size();
4585 if (viewCount != 0) {
4586 mTempViews = mViews.toArray(mTempViews != null
4587 ? mTempViews : new View[viewCount]);
4591 viewRectCount = mViewRects.size();
4592 if (viewRectCount != 0) {
4593 mTempViewRects = mViewRects.toArray(mTempViewRects != null
4594 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
4599 for (int i = 0; i < viewCount; i++) {
4600 mTempViews[i].invalidate();
4601 mTempViews[i] = null;
4604 for (int i = 0; i < viewRectCount; i++) {
4605 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
4606 info.target.invalidate(info.left, info.top, info.right, info.bottom);
4611 private void postIfNeededLocked() {
4613 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
4618 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
4619 new InvalidateOnAnimationRunnable();
4621 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
4622 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
4623 mHandler.sendMessageDelayed(msg, delayMilliseconds);
4626 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
4627 long delayMilliseconds) {
4628 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
4629 mHandler.sendMessageDelayed(msg, delayMilliseconds);
4632 public void dispatchInvalidateOnAnimation(View view) {
4633 mInvalidateOnAnimationRunnable.addView(view);
4636 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
4637 mInvalidateOnAnimationRunnable.addViewRect(info);
4640 public void enqueueDisplayList(DisplayList displayList) {
4641 mDisplayLists.add(displayList);
4644 public void cancelInvalidate(View view) {
4645 mHandler.removeMessages(MSG_INVALIDATE, view);
4646 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
4648 mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
4649 mInvalidateOnAnimationRunnable.removeView(view);
4652 public void dispatchKey(KeyEvent event) {
4653 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event);
4654 msg.setAsynchronous(true);
4655 mHandler.sendMessage(msg);
4658 public void dispatchKeyFromIme(KeyEvent event) {
4659 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
4660 msg.setAsynchronous(true);
4661 mHandler.sendMessage(msg);
4664 public void dispatchUnhandledKey(KeyEvent event) {
4665 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4666 final KeyCharacterMap kcm = event.getKeyCharacterMap();
4667 final int keyCode = event.getKeyCode();
4668 final int metaState = event.getMetaState();
4670 // Check for fallback actions specified by the key character map.
4671 KeyCharacterMap.FallbackAction fallbackAction =
4672 kcm.getFallbackAction(keyCode, metaState);
4673 if (fallbackAction != null) {
4674 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
4675 KeyEvent fallbackEvent = KeyEvent.obtain(
4676 event.getDownTime(), event.getEventTime(),
4677 event.getAction(), fallbackAction.keyCode,
4678 event.getRepeatCount(), fallbackAction.metaState,
4679 event.getDeviceId(), event.getScanCode(),
4680 flags, event.getSource(), null);
4681 fallbackAction.recycle();
4683 dispatchKey(fallbackEvent);
4688 public void dispatchAppVisibility(boolean visible) {
4689 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
4690 msg.arg1 = visible ? 1 : 0;
4691 mHandler.sendMessage(msg);
4694 public void dispatchScreenStateChange(boolean on) {
4695 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE);
4696 msg.arg1 = on ? 1 : 0;
4697 mHandler.sendMessage(msg);
4700 public void dispatchGetNewSurface() {
4701 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
4702 mHandler.sendMessage(msg);
4705 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4706 Message msg = Message.obtain();
4707 msg.what = MSG_WINDOW_FOCUS_CHANGED;
4708 msg.arg1 = hasFocus ? 1 : 0;
4709 msg.arg2 = inTouchMode ? 1 : 0;
4710 mHandler.sendMessage(msg);
4713 public void dispatchCloseSystemDialogs(String reason) {
4714 Message msg = Message.obtain();
4715 msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
4717 mHandler.sendMessage(msg);
4720 public void dispatchDragEvent(DragEvent event) {
4722 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
4723 what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
4724 mHandler.removeMessages(what);
4726 what = MSG_DISPATCH_DRAG_EVENT;
4728 Message msg = mHandler.obtainMessage(what, event);
4729 mHandler.sendMessage(msg);
4732 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4733 int localValue, int localChanges) {
4734 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
4736 args.globalVisibility = globalVisibility;
4737 args.localValue = localValue;
4738 args.localChanges = localChanges;
4739 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
4742 public void dispatchDoneAnimating() {
4743 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
4746 public void dispatchCheckFocus() {
4747 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
4748 // This will result in a call to checkFocus() below.
4749 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
4754 * Post a callback to send a
4755 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4756 * This event is send at most once every
4757 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
4759 private void postSendWindowContentChangedCallback(View source) {
4760 if (mSendWindowContentChangedAccessibilityEvent == null) {
4761 mSendWindowContentChangedAccessibilityEvent =
4762 new SendWindowContentChangedAccessibilityEvent();
4764 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource;
4765 if (oldSource == null) {
4766 mSendWindowContentChangedAccessibilityEvent.mSource = source;
4767 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent,
4768 ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
4770 mSendWindowContentChangedAccessibilityEvent.mSource =
4771 getCommonPredecessor(oldSource, source);
4776 * Remove a posted callback to send a
4777 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4779 private void removeSendWindowContentChangedCallback() {
4780 if (mSendWindowContentChangedAccessibilityEvent != null) {
4781 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
4785 public boolean showContextMenuForChild(View originalView) {
4789 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
4793 public void createContextMenu(ContextMenu menu) {
4796 public void childDrawableStateChanged(View child) {
4799 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
4800 if (mView == null) {
4803 // Intercept accessibility focus events fired by virtual nodes to keep
4804 // track of accessibility focus position in such nodes.
4805 final int eventType = event.getEventType();
4806 switch (eventType) {
4807 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4808 final long sourceNodeId = event.getSourceNodeId();
4809 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4811 View source = mView.findViewByAccessibilityId(accessibilityViewId);
4812 if (source != null) {
4813 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4814 if (provider != null) {
4815 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(
4816 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId));
4817 setAccessibilityFocus(source, node);
4821 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4822 final long sourceNodeId = event.getSourceNodeId();
4823 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4825 View source = mView.findViewByAccessibilityId(accessibilityViewId);
4826 if (source != null) {
4827 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4828 if (provider != null) {
4829 setAccessibilityFocus(null, null);
4834 mAccessibilityManager.sendAccessibilityEvent(event);
4839 public void childAccessibilityStateChanged(View child) {
4840 postSendWindowContentChangedCallback(child);
4843 private View getCommonPredecessor(View first, View second) {
4844 if (mAttachInfo != null) {
4845 if (mTempHashSet == null) {
4846 mTempHashSet = new HashSet<View>();
4848 HashSet<View> seen = mTempHashSet;
4850 View firstCurrent = first;
4851 while (firstCurrent != null) {
4852 seen.add(firstCurrent);
4853 ViewParent firstCurrentParent = firstCurrent.mParent;
4854 if (firstCurrentParent instanceof View) {
4855 firstCurrent = (View) firstCurrentParent;
4857 firstCurrent = null;
4860 View secondCurrent = second;
4861 while (secondCurrent != null) {
4862 if (seen.contains(secondCurrent)) {
4864 return secondCurrent;
4866 ViewParent secondCurrentParent = secondCurrent.mParent;
4867 if (secondCurrentParent instanceof View) {
4868 secondCurrent = (View) secondCurrentParent;
4870 secondCurrent = null;
4878 void checkThread() {
4879 if (mThread != Thread.currentThread()) {
4880 throw new CalledFromWrongThreadException(
4881 "Only the original thread that created a view hierarchy can touch its views.");
4885 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
4886 // ViewAncestor never intercepts touch event, so this can be a no-op
4889 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
4890 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
4891 if (rectangle != null) {
4892 mTempRect.set(rectangle);
4893 mTempRect.offset(0, -mCurScrollY);
4894 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4896 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate);
4897 } catch (RemoteException re) {
4904 public void childHasTransientStateChanged(View child, boolean hasTransientState) {
4908 class TakenSurfaceHolder extends BaseSurfaceHolder {
4910 public boolean onAllowLockCanvas() {
4911 return mDrawingAllowed;
4915 public void onRelayoutContainer() {
4916 // Not currently interesting -- from changing between fixed and layout size.
4919 public void setFormat(int format) {
4920 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
4923 public void setType(int type) {
4924 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
4928 public void onUpdateSurface() {
4929 // We take care of format and type changes on our own.
4930 throw new IllegalStateException("Shouldn't be here");
4933 public boolean isCreating() {
4938 public void setFixedSize(int width, int height) {
4939 throw new UnsupportedOperationException(
4940 "Currently only support sizing from layout");
4943 public void setKeepScreenOn(boolean screenOn) {
4944 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
4948 static final class InputMethodCallback implements InputMethodManager.FinishedEventCallback {
4949 private WeakReference<ViewRootImpl> mViewAncestor;
4951 public InputMethodCallback(ViewRootImpl viewAncestor) {
4952 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4956 public void finishedEvent(int seq, boolean handled) {
4957 final ViewRootImpl viewAncestor = mViewAncestor.get();
4958 if (viewAncestor != null) {
4959 viewAncestor.dispatchImeFinishedEvent(seq, handled);
4964 static class W extends IWindow.Stub {
4965 private final WeakReference<ViewRootImpl> mViewAncestor;
4966 private final IWindowSession mWindowSession;
4968 W(ViewRootImpl viewAncestor) {
4969 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4970 mWindowSession = viewAncestor.mWindowSession;
4973 public void resized(Rect frame, Rect contentInsets,
4974 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4975 final ViewRootImpl viewAncestor = mViewAncestor.get();
4976 if (viewAncestor != null) {
4977 viewAncestor.dispatchResized(frame, contentInsets,
4978 visibleInsets, reportDraw, newConfig);
4983 public void moved(int newX, int newY) {
4984 final ViewRootImpl viewAncestor = mViewAncestor.get();
4985 if (viewAncestor != null) {
4986 viewAncestor.dispatchMoved(newX, newY);
4990 public void dispatchAppVisibility(boolean visible) {
4991 final ViewRootImpl viewAncestor = mViewAncestor.get();
4992 if (viewAncestor != null) {
4993 viewAncestor.dispatchAppVisibility(visible);
4997 public void dispatchScreenState(boolean on) {
4998 final ViewRootImpl viewAncestor = mViewAncestor.get();
4999 if (viewAncestor != null) {
5000 viewAncestor.dispatchScreenStateChange(on);
5004 public void dispatchGetNewSurface() {
5005 final ViewRootImpl viewAncestor = mViewAncestor.get();
5006 if (viewAncestor != null) {
5007 viewAncestor.dispatchGetNewSurface();
5011 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
5012 final ViewRootImpl viewAncestor = mViewAncestor.get();
5013 if (viewAncestor != null) {
5014 viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
5018 private static int checkCallingPermission(String permission) {
5020 return ActivityManagerNative.getDefault().checkPermission(
5021 permission, Binder.getCallingPid(), Binder.getCallingUid());
5022 } catch (RemoteException e) {
5023 return PackageManager.PERMISSION_DENIED;
5027 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
5028 final ViewRootImpl viewAncestor = mViewAncestor.get();
5029 if (viewAncestor != null) {
5030 final View view = viewAncestor.mView;
5032 if (checkCallingPermission(Manifest.permission.DUMP) !=
5033 PackageManager.PERMISSION_GRANTED) {
5034 throw new SecurityException("Insufficient permissions to invoke"
5035 + " executeCommand() from pid=" + Binder.getCallingPid()
5036 + ", uid=" + Binder.getCallingUid());
5039 OutputStream clientStream = null;
5041 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
5042 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
5043 } catch (IOException e) {
5044 e.printStackTrace();
5046 if (clientStream != null) {
5048 clientStream.close();
5049 } catch (IOException e) {
5050 e.printStackTrace();
5058 public void closeSystemDialogs(String reason) {
5059 final ViewRootImpl viewAncestor = mViewAncestor.get();
5060 if (viewAncestor != null) {
5061 viewAncestor.dispatchCloseSystemDialogs(reason);
5065 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
5069 mWindowSession.wallpaperOffsetsComplete(asBinder());
5070 } catch (RemoteException e) {
5075 public void dispatchWallpaperCommand(String action, int x, int y,
5076 int z, Bundle extras, boolean sync) {
5079 mWindowSession.wallpaperCommandComplete(asBinder(), null);
5080 } catch (RemoteException e) {
5086 public void dispatchDragEvent(DragEvent event) {
5087 final ViewRootImpl viewAncestor = mViewAncestor.get();
5088 if (viewAncestor != null) {
5089 viewAncestor.dispatchDragEvent(event);
5093 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
5094 int localValue, int localChanges) {
5095 final ViewRootImpl viewAncestor = mViewAncestor.get();
5096 if (viewAncestor != null) {
5097 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
5098 localValue, localChanges);
5102 public void doneAnimating() {
5103 final ViewRootImpl viewAncestor = mViewAncestor.get();
5104 if (viewAncestor != null) {
5105 viewAncestor.dispatchDoneAnimating();
5111 * Maintains state information for a single trackball axis, generating
5112 * discrete (DPAD) movements based on raw trackball motion.
5114 static final class TrackballAxis {
5116 * The maximum amount of acceleration we will apply.
5118 static final float MAX_ACCELERATION = 20;
5121 * The maximum amount of time (in milliseconds) between events in order
5122 * for us to consider the user to be doing fast trackball movements,
5123 * and thus apply an acceleration.
5125 static final long FAST_MOVE_TIME = 150;
5128 * Scaling factor to the time (in milliseconds) between events to how
5129 * much to multiple/divide the current acceleration. When movement
5130 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
5131 * FAST_MOVE_TIME it divides it.
5133 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
5137 float acceleration = 1;
5138 long lastMoveTime = 0;
5141 int nonAccelMovement;
5143 void reset(int _step) {
5152 * Add trackball movement into the state. If the direction of movement
5153 * has been reversed, the state is reset before adding the
5154 * movement (so that you don't have to compensate for any previously
5155 * collected movement before see the result of the movement in the
5158 * @return Returns the absolute value of the amount of movement
5161 float collect(float off, long time, String axis) {
5164 normTime = (long)(off * FAST_MOVE_TIME);
5166 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
5173 } else if (off < 0) {
5174 normTime = (long)((-off) * FAST_MOVE_TIME);
5176 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
5187 // The number of milliseconds between each movement that is
5188 // considered "normal" and will not result in any acceleration
5189 // or deceleration, scaled by the offset we have here.
5191 long delta = time - lastMoveTime;
5192 lastMoveTime = time;
5193 float acc = acceleration;
5194 if (delta < normTime) {
5195 // The user is scrolling rapidly, so increase acceleration.
5196 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
5197 if (scale > 1) acc *= scale;
5198 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
5199 + off + " normTime=" + normTime + " delta=" + delta
5200 + " scale=" + scale + " acc=" + acc);
5201 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
5203 // The user is scrolling slowly, so decrease acceleration.
5204 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
5205 if (scale > 1) acc /= scale;
5206 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
5207 + off + " normTime=" + normTime + " delta=" + delta
5208 + " scale=" + scale + " acc=" + acc);
5209 acceleration = acc > 1 ? acc : 1;
5213 return (absPosition = Math.abs(position));
5217 * Generate the number of discrete movement events appropriate for
5218 * the currently collected trackball movement.
5220 * @param precision The minimum movement required to generate the
5221 * first discrete movement.
5223 * @return Returns the number of discrete movements, either positive
5224 * or negative, or 0 if there is not enough trackball movement yet
5225 * for a discrete movement.
5227 int generate(float precision) {
5229 nonAccelMovement = 0;
5231 final int dir = position >= 0 ? 1 : -1;
5233 // If we are going to execute the first step, then we want
5234 // to do this as soon as possible instead of waiting for
5235 // a full movement, in order to make things look responsive.
5237 if (absPosition < precision) {
5241 nonAccelMovement += dir;
5244 // If we have generated the first movement, then we need
5245 // to wait for the second complete trackball motion before
5246 // generating the second discrete movement.
5248 if (absPosition < 2) {
5252 nonAccelMovement += dir;
5253 position += dir > 0 ? -2 : 2;
5254 absPosition = Math.abs(position);
5257 // After the first two, we generate discrete movements
5258 // consistently with the trackball, applying an acceleration
5259 // if the trackball is moving quickly. This is a simple
5260 // acceleration on top of what we already compute based
5261 // on how quickly the wheel is being turned, to apply
5262 // a longer increasing acceleration to continuous movement
5263 // in one direction.
5265 if (absPosition < 1) {
5269 position += dir >= 0 ? -1 : 1;
5270 absPosition = Math.abs(position);
5271 float acc = acceleration;
5273 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
5280 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
5281 public CalledFromWrongThreadException(String msg) {
5286 private SurfaceHolder mHolder = new SurfaceHolder() {
5287 // we only need a SurfaceHolder for opengl. it would be nice
5288 // to implement everything else though, especially the callback
5289 // support (opengl doesn't make use of it right now, but eventually
5291 public Surface getSurface() {
5295 public boolean isCreating() {
5299 public void addCallback(Callback callback) {
5302 public void removeCallback(Callback callback) {
5305 public void setFixedSize(int width, int height) {
5308 public void setSizeFromLayout() {
5311 public void setFormat(int format) {
5314 public void setType(int type) {
5317 public void setKeepScreenOn(boolean screenOn) {
5320 public Canvas lockCanvas() {
5324 public Canvas lockCanvas(Rect dirty) {
5328 public void unlockCanvasAndPost(Canvas canvas) {
5330 public Rect getSurfaceFrame() {
5335 static RunQueue getRunQueue() {
5336 RunQueue rq = sRunQueues.get();
5340 rq = new RunQueue();
5346 * The run queue is used to enqueue pending work from Views when no Handler is
5347 * attached. The work is executed during the next call to performTraversals on
5351 static final class RunQueue {
5352 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
5354 void post(Runnable action) {
5355 postDelayed(action, 0);
5358 void postDelayed(Runnable action, long delayMillis) {
5359 HandlerAction handlerAction = new HandlerAction();
5360 handlerAction.action = action;
5361 handlerAction.delay = delayMillis;
5363 synchronized (mActions) {
5364 mActions.add(handlerAction);
5368 void removeCallbacks(Runnable action) {
5369 final HandlerAction handlerAction = new HandlerAction();
5370 handlerAction.action = action;
5372 synchronized (mActions) {
5373 final ArrayList<HandlerAction> actions = mActions;
5375 while (actions.remove(handlerAction)) {
5381 void executeActions(Handler handler) {
5382 synchronized (mActions) {
5383 final ArrayList<HandlerAction> actions = mActions;
5384 final int count = actions.size();
5386 for (int i = 0; i < count; i++) {
5387 final HandlerAction handlerAction = actions.get(i);
5388 handler.postDelayed(handlerAction.action, handlerAction.delay);
5395 private static class HandlerAction {
5400 public boolean equals(Object o) {
5401 if (this == o) return true;
5402 if (o == null || getClass() != o.getClass()) return false;
5404 HandlerAction that = (HandlerAction) o;
5405 return !(action != null ? !action.equals(that.action) : that.action != null);
5410 public int hashCode() {
5411 int result = action != null ? action.hashCode() : 0;
5412 result = 31 * result + (int) (delay ^ (delay >>> 32));
5419 * Class for managing the accessibility interaction connection
5420 * based on the global accessibility state.
5422 final class AccessibilityInteractionConnectionManager
5423 implements AccessibilityStateChangeListener {
5424 public void onAccessibilityStateChanged(boolean enabled) {
5427 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
5428 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
5429 View focusedView = mView.findFocus();
5430 if (focusedView != null && focusedView != mView) {
5431 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5435 ensureNoConnection();
5436 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
5440 public void ensureConnection() {
5441 if (mAttachInfo != null) {
5442 final boolean registered =
5443 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5445 mAttachInfo.mAccessibilityWindowId =
5446 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
5447 new AccessibilityInteractionConnection(ViewRootImpl.this));
5452 public void ensureNoConnection() {
5453 final boolean registered =
5454 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5456 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED;
5457 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
5463 * This class is an interface this ViewAncestor provides to the
5464 * AccessibilityManagerService to the latter can interact with
5465 * the view hierarchy in this ViewAncestor.
5467 static final class AccessibilityInteractionConnection
5468 extends IAccessibilityInteractionConnection.Stub {
5469 private final WeakReference<ViewRootImpl> mViewRootImpl;
5471 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
5472 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
5476 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
5477 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5478 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5479 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5480 if (viewRootImpl != null && viewRootImpl.mView != null) {
5481 viewRootImpl.getAccessibilityInteractionController()
5482 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
5483 interactionId, callback, flags, interrogatingPid, interrogatingTid,
5486 // We cannot make the call and notify the caller so it does not wait.
5488 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5489 } catch (RemoteException re) {
5490 /* best effort - ignore */
5496 public void performAccessibilityAction(long accessibilityNodeId, int action,
5497 Bundle arguments, int interactionId,
5498 IAccessibilityInteractionConnectionCallback callback, int flags,
5499 int interogatingPid, long interrogatingTid) {
5500 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5501 if (viewRootImpl != null && viewRootImpl.mView != null) {
5502 viewRootImpl.getAccessibilityInteractionController()
5503 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
5504 interactionId, callback, flags, interogatingPid, interrogatingTid);
5506 // We cannot make the call and notify the caller so it does not wait.
5508 callback.setPerformAccessibilityActionResult(false, interactionId);
5509 } catch (RemoteException re) {
5510 /* best effort - ignore */
5516 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId,
5517 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5518 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5519 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5520 if (viewRootImpl != null && viewRootImpl.mView != null) {
5521 viewRootImpl.getAccessibilityInteractionController()
5522 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId,
5523 interactionId, callback, flags, interrogatingPid, interrogatingTid,
5526 // We cannot make the call and notify the caller so it does not wait.
5528 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5529 } catch (RemoteException re) {
5530 /* best effort - ignore */
5536 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
5537 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5538 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5539 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5540 if (viewRootImpl != null && viewRootImpl.mView != null) {
5541 viewRootImpl.getAccessibilityInteractionController()
5542 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
5543 interactionId, callback, flags, interrogatingPid, interrogatingTid,
5546 // We cannot make the call and notify the caller so it does not wait.
5548 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5549 } catch (RemoteException re) {
5550 /* best effort - ignore */
5556 public void findFocus(long accessibilityNodeId, int focusType, int interactionId,
5557 IAccessibilityInteractionConnectionCallback callback, int flags,
5558 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5559 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5560 if (viewRootImpl != null && viewRootImpl.mView != null) {
5561 viewRootImpl.getAccessibilityInteractionController()
5562 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback,
5563 flags, interrogatingPid, interrogatingTid, spec);
5565 // We cannot make the call and notify the caller so it does not wait.
5567 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5568 } catch (RemoteException re) {
5569 /* best effort - ignore */
5575 public void focusSearch(long accessibilityNodeId, int direction, int interactionId,
5576 IAccessibilityInteractionConnectionCallback callback, int flags,
5577 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5578 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5579 if (viewRootImpl != null && viewRootImpl.mView != null) {
5580 viewRootImpl.getAccessibilityInteractionController()
5581 .focusSearchClientThread(accessibilityNodeId, direction, interactionId,
5582 callback, flags, interrogatingPid, interrogatingTid, spec);
5584 // We cannot make the call and notify the caller so it does not wait.
5586 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5587 } catch (RemoteException re) {
5588 /* best effort - ignore */
5594 private class SendWindowContentChangedAccessibilityEvent implements Runnable {
5595 public View mSource;
5598 if (mSource != null) {
5599 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
5600 mSource.resetAccessibilityStateChanged();