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;
235 // Pool of queued input events.
236 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
237 private QueuedInputEvent mQueuedInputEventPool;
238 private int mQueuedInputEventPoolSize;
240 // Input event queue.
241 QueuedInputEvent mFirstPendingInputEvent;
242 QueuedInputEvent mCurrentInputEvent;
243 boolean mProcessInputEventsScheduled;
245 boolean mWindowAttributesChanged = false;
246 int mWindowAttributesChangesFlag = 0;
248 // These can be accessed by any thread, must be protected with a lock.
249 // Surface can never be reassigned or cleared (use Surface.clear()).
250 private final Surface mSurface = new Surface();
253 boolean mAddedTouchMode;
255 final CompatibilityInfoHolder mCompatibilityInfo;
257 // These are accessed by multiple threads.
258 final Rect mWinFrame; // frame given by window manager.
260 final Rect mPendingVisibleInsets = new Rect();
261 final Rect mPendingContentInsets = new Rect();
262 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
263 = new ViewTreeObserver.InternalInsetsInfo();
265 final Rect mFitSystemWindowsInsets = new Rect();
267 final Configuration mLastConfiguration = new Configuration();
268 final Configuration mPendingConfiguration = new Configuration();
270 boolean mScrollMayChange;
272 View mLastScrolledFocus;
276 HardwareLayer mResizeBuffer;
277 long mResizeBufferStartTime;
278 int mResizeBufferDuration;
279 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
280 private ArrayList<LayoutTransition> mPendingTransitions;
282 final ViewConfiguration mViewConfiguration;
285 ClipDescription mDragDescription;
286 View mCurrentDragView;
287 volatile Object mLocalDragState;
288 final PointF mDragPoint = new PointF();
289 final PointF mLastTouchPoint = new PointF();
291 private boolean mProfileRendering;
292 private Choreographer.FrameCallback mRenderProfiler;
293 private boolean mRenderProfilingEnabled;
295 // Variables to track frames per second, enabled via DEBUG_FPS flag
296 private long mFpsStartTime = -1;
297 private long mFpsPrevTime = -1;
298 private int mFpsNumFrames;
300 private final ArrayList<DisplayList> mDisplayLists = new ArrayList<DisplayList>();
303 * see {@link #playSoundEffect(int)}
305 AudioManager mAudioManager;
307 final AccessibilityManager mAccessibilityManager;
309 AccessibilityInteractionController mAccessibilityInteractionController;
311 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
313 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
315 HashSet<View> mTempHashSet;
317 private final int mDensity;
318 private final int mNoncompatDensity;
320 private boolean mInLayout = false;
321 ArrayList<View> mLayoutRequesters = new ArrayList<View>();
322 boolean mHandlingLayoutInLayoutRequest = false;
324 private int mViewLayoutDirectionInitial;
327 * Consistency verifier for debugging purposes.
329 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
330 InputEventConsistencyVerifier.isInstrumentationEnabled() ?
331 new InputEventConsistencyVerifier(this, 0) : null;
333 static final class SystemUiVisibilityInfo {
335 int globalVisibility;
340 public ViewRootImpl(Context context, Display display) {
343 if (MEASURE_LATENCY) {
345 lt = new LatencyTimer(100, 1000);
349 // Initialize the statics when this class is first instantiated. This is
350 // done here instead of in the static block because Zygote does not
351 // allow the spawning of threads.
352 mWindowSession = WindowManagerGlobal.getWindowSession(context.getMainLooper());
355 CompatibilityInfoHolder cih = display.getCompatibilityInfo();
356 mCompatibilityInfo = cih != null ? cih : new CompatibilityInfoHolder();
358 mThread = Thread.currentThread();
359 mLocation = new WindowLeaked(null);
360 mLocation.fillInStackTrace();
364 mTempRect = new Rect();
365 mVisRect = new Rect();
366 mWinFrame = new Rect();
367 mWindow = new W(this);
368 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
369 mInputMethodCallback = new InputMethodCallback(this);
370 mViewVisibility = View.GONE;
371 mTransparentRegion = new Region();
372 mPreviousTransparentRegion = new Region();
373 mFirst = true; // true for the first time the view is added
375 mAccessibilityManager = AccessibilityManager.getInstance(context);
376 mAccessibilityInteractionConnectionManager =
377 new AccessibilityInteractionConnectionManager();
378 mAccessibilityManager.addAccessibilityStateChangeListener(
379 mAccessibilityInteractionConnectionManager);
380 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
381 mViewConfiguration = ViewConfiguration.get(context);
382 mDensity = context.getResources().getDisplayMetrics().densityDpi;
383 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
384 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
385 mChoreographer = Choreographer.getInstance();
387 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
388 mAttachInfo.mScreenOn = powerManager.isScreenOn();
389 loadSystemProperties();
390 mSimulatedTrackball = new SimulatedTrackball(context);
394 * @return True if the application requests the use of a separate render thread,
397 private static boolean isRenderThreadRequested(Context context) {
398 if (USE_RENDER_THREAD) {
399 synchronized (sRenderThreadQueryLock) {
400 if (!sRenderThreadQueried) {
401 final PackageManager packageManager = context.getPackageManager();
402 final String packageName = context.getApplicationInfo().packageName;
404 ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName,
405 PackageManager.GET_META_DATA);
406 if (applicationInfo.metaData != null) {
407 sUseRenderThread = applicationInfo.metaData.getBoolean(
408 "android.graphics.renderThread", false);
410 } catch (PackageManager.NameNotFoundException e) {
412 sRenderThreadQueried = true;
415 return sUseRenderThread;
422 public static void addFirstDrawHandler(Runnable callback) {
423 synchronized (sFirstDrawHandlers) {
424 if (!sFirstDrawComplete) {
425 sFirstDrawHandlers.add(callback);
430 public static void addConfigCallback(ComponentCallbacks callback) {
431 synchronized (sConfigCallbacks) {
432 sConfigCallbacks.add(callback);
436 // FIXME for perf testing only
437 private boolean mProfile = false;
440 * Call this to profile the next traversal call.
441 * FIXME for perf testing only. Remove eventually
443 public void profile() {
448 * Indicates whether we are in touch mode. Calling this method triggers an IPC
449 * call and should be avoided whenever possible.
451 * @return True, if the device is in touch mode, false otherwise.
455 static boolean isInTouchMode() {
456 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
457 if (windowSession != null) {
459 return windowSession.getInTouchMode();
460 } catch (RemoteException e) {
469 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
470 synchronized (this) {
473 mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
474 mFallbackEventHandler.setView(view);
475 mWindowAttributes.copyFrom(attrs);
476 attrs = mWindowAttributes;
477 // Keep track of the actual window flags supplied by the client.
478 mClientWindowLayoutFlags = attrs.flags;
480 setAccessibilityFocus(null, null);
482 if (view instanceof RootViewSurfaceTaker) {
483 mSurfaceHolderCallback =
484 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
485 if (mSurfaceHolderCallback != null) {
486 mSurfaceHolder = new TakenSurfaceHolder();
487 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
491 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
492 mTranslator = compatibilityInfo.getTranslator();
494 // If the application owns the surface, don't enable hardware acceleration
495 if (mSurfaceHolder == null) {
496 enableHardwareAcceleration(mView.getContext(), attrs);
499 boolean restore = false;
500 if (mTranslator != null) {
501 mSurface.setCompatibilityTranslator(mTranslator);
504 mTranslator.translateWindowLayout(attrs);
506 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
508 if (!compatibilityInfo.supportsScreen()) {
509 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
510 mLastInCompatMode = true;
513 mSoftInputMode = attrs.softInputMode;
514 mWindowAttributesChanged = true;
515 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
516 mAttachInfo.mRootView = view;
517 mAttachInfo.mScalingRequired = mTranslator != null;
518 mAttachInfo.mApplicationScale =
519 mTranslator == null ? 1.0f : mTranslator.applicationScale;
520 if (panelParentView != null) {
521 mAttachInfo.mPanelParentWindowToken
522 = panelParentView.getApplicationWindowToken();
525 int res; /* = WindowManagerImpl.ADD_OKAY; */
527 // Schedule the first layout -before- adding to the window
528 // manager, to make sure we do the relayout before receiving
529 // any other events from the system.
531 if ((mWindowAttributes.inputFeatures
532 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
533 mInputChannel = new InputChannel();
536 mOrigWindowType = mWindowAttributes.type;
537 mAttachInfo.mRecomputeGlobalAttributes = true;
538 collectViewAttributes();
539 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
540 getHostVisibility(), mDisplay.getDisplayId(),
541 mAttachInfo.mContentInsets, mInputChannel);
542 } catch (RemoteException e) {
545 mAttachInfo.mRootView = null;
546 mInputChannel = null;
547 mFallbackEventHandler.setView(null);
548 unscheduleTraversals();
549 setAccessibilityFocus(null, null);
550 throw new RuntimeException("Adding window failed", e);
557 if (mTranslator != null) {
558 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
560 mPendingContentInsets.set(mAttachInfo.mContentInsets);
561 mPendingVisibleInsets.set(0, 0, 0, 0);
562 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
563 if (res < WindowManagerGlobal.ADD_OKAY) {
564 mAttachInfo.mRootView = null;
566 mFallbackEventHandler.setView(null);
567 unscheduleTraversals();
568 setAccessibilityFocus(null, null);
570 case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
571 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
572 throw new WindowManager.BadTokenException(
573 "Unable to add window -- token " + attrs.token
574 + " is not valid; is your activity running?");
575 case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
576 throw new WindowManager.BadTokenException(
577 "Unable to add window -- token " + attrs.token
578 + " is not for an application");
579 case WindowManagerGlobal.ADD_APP_EXITING:
580 throw new WindowManager.BadTokenException(
581 "Unable to add window -- app for token " + attrs.token
583 case WindowManagerGlobal.ADD_DUPLICATE_ADD:
584 throw new WindowManager.BadTokenException(
585 "Unable to add window -- window " + mWindow
586 + " has already been added");
587 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
588 // Silently ignore -- we would have just removed it
589 // right away, anyway.
591 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
592 throw new WindowManager.BadTokenException(
593 "Unable to add window " + mWindow +
594 " -- another window of this type already exists");
595 case WindowManagerGlobal.ADD_PERMISSION_DENIED:
596 throw new WindowManager.BadTokenException(
597 "Unable to add window " + mWindow +
598 " -- permission denied for this window type");
599 case WindowManagerGlobal.ADD_INVALID_DISPLAY:
600 throw new WindowManager.InvalidDisplayException(
601 "Unable to add window " + mWindow +
602 " -- the specified display can not be found");
604 throw new RuntimeException(
605 "Unable to add window -- unknown error code " + res);
608 if (view instanceof RootViewSurfaceTaker) {
609 mInputQueueCallback =
610 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
612 if (mInputChannel != null) {
613 if (mInputQueueCallback != null) {
614 mInputQueue = new InputQueue(mInputChannel);
615 mInputQueueCallback.onInputQueueCreated(mInputQueue);
617 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
622 view.assignParent(this);
623 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
624 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
626 if (mAccessibilityManager.isEnabled()) {
627 mAccessibilityInteractionConnectionManager.ensureConnection();
630 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
631 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
637 void destroyHardwareResources() {
638 if (mAttachInfo.mHardwareRenderer != null) {
639 if (mAttachInfo.mHardwareRenderer.isEnabled()) {
640 mAttachInfo.mHardwareRenderer.destroyLayers(mView);
642 mAttachInfo.mHardwareRenderer.destroy(false);
646 void terminateHardwareResources() {
647 if (mAttachInfo.mHardwareRenderer != null) {
648 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
649 mAttachInfo.mHardwareRenderer.destroy(false);
653 void destroyHardwareLayers() {
654 if (mThread != Thread.currentThread()) {
655 if (mAttachInfo.mHardwareRenderer != null &&
656 mAttachInfo.mHardwareRenderer.isEnabled()) {
657 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE);
660 if (mAttachInfo.mHardwareRenderer != null &&
661 mAttachInfo.mHardwareRenderer.isEnabled()) {
662 mAttachInfo.mHardwareRenderer.destroyLayers(mView);
667 void pushHardwareLayerUpdate(HardwareLayer layer) {
668 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
669 mAttachInfo.mHardwareRenderer.pushLayerUpdate(layer);
673 public boolean attachFunctor(int functor) {
674 //noinspection SimplifiableIfStatement
675 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
676 return mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor);
681 public void detachFunctor(int functor) {
682 if (mAttachInfo.mHardwareRenderer != null) {
683 mAttachInfo.mHardwareRenderer.detachFunctor(functor);
687 private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) {
688 mAttachInfo.mHardwareAccelerated = false;
689 mAttachInfo.mHardwareAccelerationRequested = false;
691 // Don't enable hardware acceleration when the application is in compatibility mode
692 if (mTranslator != null) return;
694 // Try to enable hardware acceleration if requested
695 final boolean hardwareAccelerated =
696 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
698 if (hardwareAccelerated) {
699 if (!HardwareRenderer.isAvailable()) {
703 // Persistent processes (including the system) should not do
704 // accelerated rendering on low-end devices. In that case,
705 // sRendererDisabled will be set. In addition, the system process
706 // itself should never do accelerated rendering. In that case, both
707 // sRendererDisabled and sSystemRendererDisabled are set. When
708 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
709 // can be used by code on the system process to escape that and enable
710 // HW accelerated drawing. (This is basically for the lock screen.)
712 final boolean fakeHwAccelerated = (attrs.privateFlags &
713 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
714 final boolean forceHwAccelerated = (attrs.privateFlags &
715 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
717 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled
718 && forceHwAccelerated)) {
719 // Don't enable hardware acceleration when we're not on the main thread
720 if (!HardwareRenderer.sSystemRendererDisabled &&
721 Looper.getMainLooper() != Looper.myLooper()) {
722 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
723 + "acceleration outside of the main thread, aborting");
727 final boolean renderThread = isRenderThreadRequested(context);
729 Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated");
732 if (mAttachInfo.mHardwareRenderer != null) {
733 mAttachInfo.mHardwareRenderer.destroy(true);
736 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
737 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
738 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
739 = mAttachInfo.mHardwareRenderer != null;
741 } else if (fakeHwAccelerated) {
742 // The window had wanted to use hardware acceleration, but this
743 // is not allowed in its process. By setting this flag, it can
744 // still render as if it was accelerated. This is basically for
745 // the preview windows the window manager shows for launching
746 // applications, so they will look more like the app being launched.
747 mAttachInfo.mHardwareAccelerationRequested = true;
752 public View getView() {
756 final WindowLeaked getLocation() {
760 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
761 synchronized (this) {
762 int oldSoftInputMode = mWindowAttributes.softInputMode;
763 // Keep track of the actual window flags supplied by the client.
764 mClientWindowLayoutFlags = attrs.flags;
765 // preserve compatible window flag if exists.
766 int compatibleWindowFlag =
767 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
768 // transfer over system UI visibility values as they carry current state.
769 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
770 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
771 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
772 mWindowAttributes.flags |= compatibleWindowFlag;
774 applyKeepScreenOnFlag(mWindowAttributes);
777 mSoftInputMode = attrs.softInputMode;
780 // Don't lose the mode we last auto-computed.
781 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
782 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
783 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
784 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
786 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
788 mWindowAttributesChanged = true;
789 scheduleTraversals();
793 void handleAppVisibility(boolean visible) {
794 if (mAppVisible != visible) {
795 mAppVisible = visible;
796 scheduleTraversals();
800 void handleGetNewSurface() {
801 mNewSurfaceNeeded = true;
802 mFullRedrawNeeded = true;
803 scheduleTraversals();
806 void handleScreenStateChange(boolean on) {
807 if (on != mAttachInfo.mScreenOn) {
808 mAttachInfo.mScreenOn = on;
810 mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF);
813 mFullRedrawNeeded = true;
814 scheduleTraversals();
820 public void requestFitSystemWindows() {
822 mFitSystemWindowsRequested = true;
823 scheduleTraversals();
827 public void requestLayout() {
828 if (!mHandlingLayoutInLayoutRequest) {
830 mLayoutRequested = true;
831 scheduleTraversals();
836 public boolean isLayoutRequested() {
837 return mLayoutRequested;
841 mDirty.set(0, 0, mWidth, mHeight);
842 scheduleTraversals();
845 void invalidateWorld(View view) {
847 if (view instanceof ViewGroup) {
848 ViewGroup parent = (ViewGroup) view;
849 for (int i = 0; i < parent.getChildCount(); i++) {
850 invalidateWorld(parent.getChildAt(i));
856 public void invalidateChild(View child, Rect dirty) {
857 invalidateChildInParent(null, dirty);
860 public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
862 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
867 } else if (dirty.isEmpty() && !mIsAnimating) {
871 if (mCurScrollY != 0 || mTranslator != null) {
872 mTempRect.set(dirty);
874 if (mCurScrollY != 0) {
875 dirty.offset(0, -mCurScrollY);
877 if (mTranslator != null) {
878 mTranslator.translateRectInAppWindowToScreen(dirty);
880 if (mAttachInfo.mScalingRequired) {
885 final Rect localDirty = mDirty;
886 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
887 mAttachInfo.mSetIgnoreDirtyState = true;
888 mAttachInfo.mIgnoreDirtyState = true;
891 // Add the new dirty rect to the current one
892 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
893 // Intersect with the bounds of the window to skip
894 // updates that lie outside of the visible region
895 final float appScale = mAttachInfo.mApplicationScale;
896 final boolean intersected = localDirty.intersect(0, 0,
897 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
899 localDirty.setEmpty();
901 if (!mWillDrawSoon && (intersected || mIsAnimating)) {
902 scheduleTraversals();
908 void setStopped(boolean stopped) {
909 if (mStopped != stopped) {
912 scheduleTraversals();
917 public ViewParent getParent() {
921 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
922 if (child != mView) {
923 throw new RuntimeException("child is not mine, honest!");
925 // Note: don't apply scroll offset, because we want to know its
926 // visibility in the virtual canvas being given to the view hierarchy.
927 return r.intersect(0, 0, mWidth, mHeight);
930 public void bringChildToFront(View child) {
933 int getHostVisibility() {
934 return mAppVisible ? mView.getVisibility() : View.GONE;
937 void disposeResizeBuffer() {
938 if (mResizeBuffer != null) {
939 mResizeBuffer.destroy();
940 mResizeBuffer = null;
945 * Add LayoutTransition to the list of transitions to be started in the next traversal.
946 * This list will be cleared after the transitions on the list are start()'ed. These
947 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
948 * happens during the layout phase of traversal, which we want to complete before any of the
949 * animations are started (because those animations may side-effect properties that layout
950 * depends upon, like the bounding rectangles of the affected views). So we add the transition
951 * to the list and it is started just prior to starting the drawing phase of traversal.
953 * @param transition The LayoutTransition to be started on the next traversal.
957 public void requestTransitionStart(LayoutTransition transition) {
958 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
959 if (mPendingTransitions == null) {
960 mPendingTransitions = new ArrayList<LayoutTransition>();
962 mPendingTransitions.add(transition);
966 void scheduleTraversals() {
967 if (!mTraversalScheduled) {
968 mTraversalScheduled = true;
969 mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
970 mChoreographer.postCallback(
971 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
972 scheduleConsumeBatchedInput();
976 void unscheduleTraversals() {
977 if (mTraversalScheduled) {
978 mTraversalScheduled = false;
979 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
980 mChoreographer.removeCallbacks(
981 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
986 if (mTraversalScheduled) {
987 mTraversalScheduled = false;
988 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);
991 Debug.startMethodTracing("ViewAncestor");
994 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
998 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1002 Debug.stopMethodTracing();
1008 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1009 // Update window's global keep screen on flag: if a view has requested
1010 // that the screen be kept on, then it is always set; otherwise, it is
1011 // set to whatever the client last requested for the global state.
1012 if (mAttachInfo.mKeepScreenOn) {
1013 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1015 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1016 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1020 private boolean collectViewAttributes() {
1021 final View.AttachInfo attachInfo = mAttachInfo;
1022 if (attachInfo.mRecomputeGlobalAttributes) {
1023 //Log.i(TAG, "Computing view hierarchy attributes!");
1024 attachInfo.mRecomputeGlobalAttributes = false;
1025 boolean oldScreenOn = attachInfo.mKeepScreenOn;
1026 attachInfo.mKeepScreenOn = false;
1027 attachInfo.mSystemUiVisibility = 0;
1028 attachInfo.mHasSystemUiListeners = false;
1029 mView.dispatchCollectViewAttributes(attachInfo, 0);
1030 attachInfo.mSystemUiVisibility &= ~attachInfo.mDisabledSystemUiVisibility;
1031 WindowManager.LayoutParams params = mWindowAttributes;
1032 if (attachInfo.mKeepScreenOn != oldScreenOn
1033 || attachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1034 || attachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
1035 applyKeepScreenOnFlag(params);
1036 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
1037 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners;
1038 mView.dispatchWindowSystemUiVisiblityChanged(attachInfo.mSystemUiVisibility);
1045 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1046 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1047 int childWidthMeasureSpec;
1048 int childHeightMeasureSpec;
1049 boolean windowSizeMayChange = false;
1051 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
1052 "Measuring " + host + " in display " + desiredWindowWidth
1053 + "x" + desiredWindowHeight + "...");
1055 boolean goodMeasure = false;
1056 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1057 // On large screens, we don't want to allow dialogs to just
1058 // stretch to fill the entire width of the screen to display
1059 // one line of text. First try doing the layout at a smaller
1060 // size to see if it will fit.
1061 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1062 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1064 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1065 baseSize = (int)mTmpValue.getDimension(packageMetrics);
1067 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
1068 if (baseSize != 0 && desiredWindowWidth > baseSize) {
1069 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1070 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1071 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1072 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1073 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1074 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1077 // Didn't fit in that size... try expanding a bit.
1078 baseSize = (baseSize+desiredWindowWidth)/2;
1079 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
1081 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1082 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1083 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
1084 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1085 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1086 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
1094 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1095 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1096 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1097 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1098 windowSizeMayChange = true;
1103 System.out.println("======================================");
1104 System.out.println("performTraversals -- after measure");
1108 return windowSizeMayChange;
1111 private void performTraversals() {
1112 // cache mView since it is used so much below...
1113 final View host = mView;
1116 System.out.println("======================================");
1117 System.out.println("performTraversals");
1121 if (host == null || !mAdded)
1124 mIsInTraversal = true;
1125 mWillDrawSoon = true;
1126 boolean windowSizeMayChange = false;
1127 boolean newSurface = false;
1128 boolean surfaceChanged = false;
1129 WindowManager.LayoutParams lp = mWindowAttributes;
1131 int desiredWindowWidth;
1132 int desiredWindowHeight;
1134 final View.AttachInfo attachInfo = mAttachInfo;
1136 final int viewVisibility = getHostVisibility();
1137 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
1138 || mNewSurfaceNeeded;
1140 WindowManager.LayoutParams params = null;
1141 if (mWindowAttributesChanged) {
1142 mWindowAttributesChanged = false;
1143 surfaceChanged = true;
1146 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get();
1147 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1149 mFullRedrawNeeded = true;
1150 mLayoutRequested = true;
1151 if (mLastInCompatMode) {
1152 params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
1153 mLastInCompatMode = false;
1155 params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
1156 mLastInCompatMode = true;
1160 mWindowAttributesChangesFlag = 0;
1162 Rect frame = mWinFrame;
1164 mFullRedrawNeeded = true;
1165 mLayoutRequested = true;
1167 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
1168 // NOTE -- system code, won't try to do compat mode.
1169 Point size = new Point();
1170 mDisplay.getRealSize(size);
1171 desiredWindowWidth = size.x;
1172 desiredWindowHeight = size.y;
1174 DisplayMetrics packageMetrics =
1175 mView.getContext().getResources().getDisplayMetrics();
1176 desiredWindowWidth = packageMetrics.widthPixels;
1177 desiredWindowHeight = packageMetrics.heightPixels;
1180 // For the very first time, tell the view hierarchy that it
1181 // is attached to the window. Note that at this point the surface
1182 // object is not initialized to its backing store, but soon it
1183 // will be (assuming the window is visible).
1184 attachInfo.mSurface = mSurface;
1185 // We used to use the following condition to choose 32 bits drawing caches:
1186 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1187 // However, windows are now always 32 bits by default, so choose 32 bits
1188 attachInfo.mUse32BitDrawingCache = true;
1189 attachInfo.mHasWindowFocus = false;
1190 attachInfo.mWindowVisibility = viewVisibility;
1191 attachInfo.mRecomputeGlobalAttributes = false;
1192 viewVisibilityChanged = false;
1193 mLastConfiguration.setTo(host.getResources().getConfiguration());
1194 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1195 // Set the layout direction if it has not been set before (inherit is the default)
1196 if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1197 host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1199 host.dispatchAttachedToWindow(attachInfo, 0);
1200 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1201 host.fitSystemWindows(mFitSystemWindowsInsets);
1202 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
1205 desiredWindowWidth = frame.width();
1206 desiredWindowHeight = frame.height();
1207 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
1208 if (DEBUG_ORIENTATION) Log.v(TAG,
1209 "View " + host + " resized to: " + frame);
1210 mFullRedrawNeeded = true;
1211 mLayoutRequested = true;
1212 windowSizeMayChange = true;
1216 if (viewVisibilityChanged) {
1217 attachInfo.mWindowVisibility = viewVisibility;
1218 host.dispatchWindowVisibilityChanged(viewVisibility);
1219 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1220 destroyHardwareResources();
1222 if (viewVisibility == View.GONE) {
1223 // After making a window gone, we will count it as being
1224 // shown for the first time the next time it gets focus.
1225 mHasHadWindowFocus = false;
1229 // Execute enqueued actions on every traversal in case a detached view enqueued an action
1230 getRunQueue().executeActions(attachInfo.mHandler);
1232 boolean insetsChanged = false;
1234 boolean layoutRequested = mLayoutRequested && !mStopped;
1235 if (layoutRequested) {
1237 final Resources res = mView.getContext().getResources();
1240 // make sure touch mode code executes by setting cached value
1241 // to opposite of the added touch mode.
1242 mAttachInfo.mInTouchMode = !mAddedTouchMode;
1243 ensureTouchModeLocally(mAddedTouchMode);
1245 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
1246 insetsChanged = true;
1248 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
1249 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1250 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1251 + mAttachInfo.mVisibleInsets);
1253 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1254 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
1255 windowSizeMayChange = true;
1257 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) {
1258 // NOTE -- system code, won't try to do compat mode.
1259 Point size = new Point();
1260 mDisplay.getRealSize(size);
1261 desiredWindowWidth = size.x;
1262 desiredWindowHeight = size.y;
1264 DisplayMetrics packageMetrics = res.getDisplayMetrics();
1265 desiredWindowWidth = packageMetrics.widthPixels;
1266 desiredWindowHeight = packageMetrics.heightPixels;
1271 // Ask host how big it wants to be
1272 windowSizeMayChange |= measureHierarchy(host, lp, res,
1273 desiredWindowWidth, desiredWindowHeight);
1276 if (collectViewAttributes()) {
1279 if (attachInfo.mForceReportNewAttributes) {
1280 attachInfo.mForceReportNewAttributes = false;
1284 if (mFirst || attachInfo.mViewVisibilityChanged) {
1285 attachInfo.mViewVisibilityChanged = false;
1286 int resizeMode = mSoftInputMode &
1287 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1288 // If we are in auto resize mode, then we need to determine
1289 // what mode to use now.
1290 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1291 final int N = attachInfo.mScrollContainers.size();
1292 for (int i=0; i<N; i++) {
1293 if (attachInfo.mScrollContainers.get(i).isShown()) {
1294 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1297 if (resizeMode == 0) {
1298 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1300 if ((lp.softInputMode &
1301 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1302 lp.softInputMode = (lp.softInputMode &
1303 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1310 if (params != null && (host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1311 if (!PixelFormat.formatHasAlpha(params.format)) {
1312 params.format = PixelFormat.TRANSLUCENT;
1316 if (mFitSystemWindowsRequested) {
1317 mFitSystemWindowsRequested = false;
1318 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1319 host.fitSystemWindows(mFitSystemWindowsInsets);
1320 if (mLayoutRequested) {
1321 // Short-circuit catching a new layout request here, so
1322 // we don't need to go through two layout passes when things
1323 // change due to fitting system windows, which can happen a lot.
1324 windowSizeMayChange |= measureHierarchy(host, lp,
1325 mView.getContext().getResources(),
1326 desiredWindowWidth, desiredWindowHeight);
1330 if (layoutRequested) {
1331 // Clear this now, so that if anything requests a layout in the
1332 // rest of this function we will catch it and re-run a full
1334 mLayoutRequested = false;
1337 boolean windowShouldResize = layoutRequested && windowSizeMayChange
1338 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
1339 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1340 frame.width() < desiredWindowWidth && frame.width() != mWidth)
1341 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1342 frame.height() < desiredWindowHeight && frame.height() != mHeight));
1344 final boolean computesInternalInsets =
1345 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
1347 boolean insetsPending = false;
1348 int relayoutResult = 0;
1350 if (mFirst || windowShouldResize || insetsChanged ||
1351 viewVisibilityChanged || params != null) {
1353 if (viewVisibility == View.VISIBLE) {
1354 // If this window is giving internal insets to the window
1355 // manager, and it is being added or changing its visibility,
1356 // then we want to first give the window manager "fake"
1357 // insets to cause it to effectively ignore the content of
1358 // the window during layout. This avoids it briefly causing
1359 // other windows to resize/move based on the raw frame of the
1360 // window, waiting until we can finish laying out this window
1361 // and get back to the window manager with the ultimately
1363 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1366 if (mSurfaceHolder != null) {
1367 mSurfaceHolder.mSurfaceLock.lock();
1368 mDrawingAllowed = true;
1371 boolean hwInitialized = false;
1372 boolean contentInsetsChanged = false;
1373 boolean visibleInsetsChanged;
1374 boolean hadSurface = mSurface.isValid();
1378 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1379 host.getMeasuredHeight() + ", params=" + params);
1382 final int surfaceGenerationId = mSurface.getGenerationId();
1383 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1385 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1386 + " content=" + mPendingContentInsets.toShortString()
1387 + " visible=" + mPendingVisibleInsets.toShortString()
1388 + " surface=" + mSurface);
1390 if (mPendingConfiguration.seq != 0) {
1391 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1392 + mPendingConfiguration);
1393 updateConfiguration(mPendingConfiguration, !mFirst);
1394 mPendingConfiguration.seq = 0;
1397 contentInsetsChanged = !mPendingContentInsets.equals(
1398 mAttachInfo.mContentInsets);
1399 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1400 mAttachInfo.mVisibleInsets);
1401 if (contentInsetsChanged) {
1402 if (mWidth > 0 && mHeight > 0 && lp != null &&
1403 ((lp.systemUiVisibility|lp.subtreeSystemUiVisibility)
1404 & View.SYSTEM_UI_LAYOUT_FLAGS) == 0 &&
1405 mSurface != null && mSurface.isValid() &&
1406 !mAttachInfo.mTurnOffWindowResizeAnim &&
1407 mAttachInfo.mHardwareRenderer != null &&
1408 mAttachInfo.mHardwareRenderer.isEnabled() &&
1409 mAttachInfo.mHardwareRenderer.validate() &&
1410 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
1412 disposeResizeBuffer();
1414 boolean completed = false;
1415 HardwareCanvas hwRendererCanvas = mAttachInfo.mHardwareRenderer.getCanvas();
1416 HardwareCanvas layerCanvas = null;
1418 if (mResizeBuffer == null) {
1419 mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
1420 mWidth, mHeight, false);
1421 } else if (mResizeBuffer.getWidth() != mWidth ||
1422 mResizeBuffer.getHeight() != mHeight) {
1423 mResizeBuffer.resize(mWidth, mHeight);
1425 // TODO: should handle create/resize failure
1426 layerCanvas = mResizeBuffer.start(hwRendererCanvas);
1427 layerCanvas.setViewport(mWidth, mHeight);
1428 layerCanvas.onPreDraw(null);
1429 final int restoreCount = layerCanvas.save();
1432 final boolean scrolling = mScroller != null
1433 && mScroller.computeScrollOffset();
1435 yoff = mScroller.getCurrY();
1436 mScroller.abortAnimation();
1441 layerCanvas.translate(0, -yoff);
1442 if (mTranslator != null) {
1443 mTranslator.translateCanvas(layerCanvas);
1446 DisplayList displayList = mView.mDisplayList;
1447 if (displayList != null) {
1448 layerCanvas.drawDisplayList(displayList, null,
1449 DisplayList.FLAG_CLIP_CHILDREN);
1451 mView.draw(layerCanvas);
1454 drawAccessibilityFocusedDrawableIfNeeded(layerCanvas);
1456 mResizeBufferStartTime = SystemClock.uptimeMillis();
1457 mResizeBufferDuration = mView.getResources().getInteger(
1458 com.android.internal.R.integer.config_mediumAnimTime);
1461 layerCanvas.restoreToCount(restoreCount);
1462 } catch (OutOfMemoryError e) {
1463 Log.w(TAG, "Not enough memory for content change anim buffer", e);
1465 if (layerCanvas != null) {
1466 layerCanvas.onPostDraw();
1468 if (mResizeBuffer != null) {
1469 mResizeBuffer.end(hwRendererCanvas);
1471 mResizeBuffer.destroy();
1472 mResizeBuffer = null;
1477 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1478 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1479 + mAttachInfo.mContentInsets);
1481 if (contentInsetsChanged || mLastSystemUiVisibility !=
1482 mAttachInfo.mSystemUiVisibility || mFitSystemWindowsRequested) {
1483 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1484 mFitSystemWindowsRequested = false;
1485 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets);
1486 host.fitSystemWindows(mFitSystemWindowsInsets);
1488 if (visibleInsetsChanged) {
1489 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1490 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1491 + mAttachInfo.mVisibleInsets);
1495 if (mSurface.isValid()) {
1496 // If we are creating a new surface, then we need to
1497 // completely redraw it. Also, when we get to the
1498 // point of drawing it we will hold off and schedule
1499 // a new traversal instead. This is so we can tell the
1500 // window manager about all of the windows being displayed
1501 // before actually drawing them, so it can display then
1504 mFullRedrawNeeded = true;
1505 mPreviousTransparentRegion.setEmpty();
1507 if (mAttachInfo.mHardwareRenderer != null) {
1509 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
1510 mHolder.getSurface());
1511 } catch (Surface.OutOfResourcesException e) {
1512 Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
1514 if (!mWindowSession.outOfMemory(mWindow) &&
1515 Process.myUid() != Process.SYSTEM_UID) {
1516 Slog.w(TAG, "No processes killed for memory; killing self");
1517 Process.killProcess(Process.myPid());
1519 } catch (RemoteException ex) {
1521 mLayoutRequested = true; // ask wm for a new surface next time.
1526 } else if (!mSurface.isValid()) {
1527 // If the surface has been removed, then reset the scroll
1529 mLastScrolledFocus = null;
1530 mScrollY = mCurScrollY = 0;
1531 if (mScroller != null) {
1532 mScroller.abortAnimation();
1534 disposeResizeBuffer();
1535 // Our surface is gone
1536 if (mAttachInfo.mHardwareRenderer != null &&
1537 mAttachInfo.mHardwareRenderer.isEnabled()) {
1538 mAttachInfo.mHardwareRenderer.destroy(true);
1540 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1541 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1542 mFullRedrawNeeded = true;
1544 mAttachInfo.mHardwareRenderer.updateSurface(mHolder.getSurface());
1545 } catch (Surface.OutOfResourcesException e) {
1546 Log.e(TAG, "OutOfResourcesException updating HW surface", e);
1548 if (!mWindowSession.outOfMemory(mWindow)) {
1549 Slog.w(TAG, "No processes killed for memory; killing self");
1550 Process.killProcess(Process.myPid());
1552 } catch (RemoteException ex) {
1554 mLayoutRequested = true; // ask wm for a new surface next time.
1558 } catch (RemoteException e) {
1561 if (DEBUG_ORIENTATION) Log.v(
1562 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1564 attachInfo.mWindowLeft = frame.left;
1565 attachInfo.mWindowTop = frame.top;
1567 // !!FIXME!! This next section handles the case where we did not get the
1568 // window size we asked for. We should avoid this by getting a maximum size from
1569 // the window session beforehand.
1570 if (mWidth != frame.width() || mHeight != frame.height()) {
1571 mWidth = frame.width();
1572 mHeight = frame.height();
1575 if (mSurfaceHolder != null) {
1576 // The app owns the surface; tell it about what is going on.
1577 if (mSurface.isValid()) {
1578 // XXX .copyFrom() doesn't work!
1579 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1580 mSurfaceHolder.mSurface = mSurface;
1582 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1583 mSurfaceHolder.mSurfaceLock.unlock();
1584 if (mSurface.isValid()) {
1586 mSurfaceHolder.ungetCallbacks();
1589 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1590 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1591 if (callbacks != null) {
1592 for (SurfaceHolder.Callback c : callbacks) {
1593 c.surfaceCreated(mSurfaceHolder);
1596 surfaceChanged = true;
1598 if (surfaceChanged) {
1599 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1600 lp.format, mWidth, mHeight);
1601 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1602 if (callbacks != null) {
1603 for (SurfaceHolder.Callback c : callbacks) {
1604 c.surfaceChanged(mSurfaceHolder, lp.format,
1609 mIsCreating = false;
1610 } else if (hadSurface) {
1611 mSurfaceHolder.ungetCallbacks();
1612 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1613 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1614 if (callbacks != null) {
1615 for (SurfaceHolder.Callback c : callbacks) {
1616 c.surfaceDestroyed(mSurfaceHolder);
1619 mSurfaceHolder.mSurfaceLock.lock();
1621 mSurfaceHolder.mSurface = new Surface();
1623 mSurfaceHolder.mSurfaceLock.unlock();
1628 if (mAttachInfo.mHardwareRenderer != null &&
1629 mAttachInfo.mHardwareRenderer.isEnabled()) {
1630 if (hwInitialized || windowShouldResize ||
1631 mWidth != mAttachInfo.mHardwareRenderer.getWidth() ||
1632 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) {
1633 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
1634 if (!hwInitialized) {
1635 mAttachInfo.mHardwareRenderer.invalidate(mHolder.getSurface());
1636 mFullRedrawNeeded = true;
1642 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1643 (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
1644 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1645 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1646 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1647 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1649 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1650 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1651 + " mHeight=" + mHeight
1652 + " measuredHeight=" + host.getMeasuredHeight()
1653 + " coveredInsetsChanged=" + contentInsetsChanged);
1655 // Ask host how big it wants to be
1656 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1658 // Implementation of weights from WindowManager.LayoutParams
1659 // We just grow the dimensions as needed and re-measure if
1661 int width = host.getMeasuredWidth();
1662 int height = host.getMeasuredHeight();
1663 boolean measureAgain = false;
1665 if (lp.horizontalWeight > 0.0f) {
1666 width += (int) ((mWidth - width) * lp.horizontalWeight);
1667 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1668 MeasureSpec.EXACTLY);
1669 measureAgain = true;
1671 if (lp.verticalWeight > 0.0f) {
1672 height += (int) ((mHeight - height) * lp.verticalWeight);
1673 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1674 MeasureSpec.EXACTLY);
1675 measureAgain = true;
1679 if (DEBUG_LAYOUT) Log.v(TAG,
1680 "And hey let's measure once more: width=" + width
1681 + " height=" + height);
1682 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1685 layoutRequested = true;
1689 // Not the first pass and no window/insets/visibility change but the window
1690 // may have moved and we need check that and if so to update the left and right
1691 // in the attach info. We translate only the window frame since on window move
1692 // the window manager tells us only for the new frame but the insets are the
1693 // same and we do not want to translate them more than once.
1695 // TODO: Well, we are checking whether the frame has changed similarly
1696 // to how this is done for the insets. This is however incorrect since
1697 // the insets and the frame are translated. For example, the old frame
1698 // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
1699 // reported frame is (2, 2 - 2, 2) which implies no change but this is not
1700 // true since we are comparing a not translated value to a translated one.
1701 // This scenario is rare but we may want to fix that.
1703 final boolean windowMoved = (attachInfo.mWindowLeft != frame.left
1704 || attachInfo.mWindowTop != frame.top);
1706 if (mTranslator != null) {
1707 mTranslator.translateRectInScreenToAppWinFrame(frame);
1709 attachInfo.mWindowLeft = frame.left;
1710 attachInfo.mWindowTop = frame.top;
1714 final boolean didLayout = layoutRequested && !mStopped;
1715 boolean triggerGlobalLayoutListener = didLayout
1716 || attachInfo.mRecomputeGlobalAttributes;
1718 performLayout(lp, desiredWindowWidth, desiredWindowHeight);
1720 // By this point all views have been sized and positionned
1721 // We can compute the transparent area
1723 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1724 // start out transparent
1725 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1726 host.getLocationInWindow(mTmpLocation);
1727 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1728 mTmpLocation[0] + host.mRight - host.mLeft,
1729 mTmpLocation[1] + host.mBottom - host.mTop);
1731 host.gatherTransparentRegion(mTransparentRegion);
1732 if (mTranslator != null) {
1733 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1736 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1737 mPreviousTransparentRegion.set(mTransparentRegion);
1738 // reconfigure window manager
1740 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1741 } catch (RemoteException e) {
1747 System.out.println("======================================");
1748 System.out.println("performTraversals -- after setFrame");
1753 if (triggerGlobalLayoutListener) {
1754 attachInfo.mRecomputeGlobalAttributes = false;
1755 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1757 if (AccessibilityManager.getInstance(host.mContext).isEnabled()) {
1758 postSendWindowContentChangedCallback(mView);
1762 if (computesInternalInsets) {
1763 // Clear the original insets.
1764 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1767 // Compute new insets in place.
1768 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
1770 // Tell the window manager.
1771 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1772 mLastGivenInsets.set(insets);
1774 // Translate insets to screen coordinates if needed.
1775 final Rect contentInsets;
1776 final Rect visibleInsets;
1777 final Region touchableRegion;
1778 if (mTranslator != null) {
1779 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1780 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1781 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1783 contentInsets = insets.contentInsets;
1784 visibleInsets = insets.visibleInsets;
1785 touchableRegion = insets.touchableRegion;
1789 mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
1790 contentInsets, visibleInsets, touchableRegion);
1791 } catch (RemoteException e) {
1796 boolean skipDraw = false;
1799 // handle first focus request
1800 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1801 + mView.hasFocus());
1802 if (mView != null) {
1803 if (!mView.hasFocus()) {
1804 mView.requestFocus(View.FOCUS_FORWARD);
1805 mFocusedView = mRealFocusedView = mView.findFocus();
1806 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1809 mRealFocusedView = mView.findFocus();
1810 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1811 + mRealFocusedView);
1814 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) {
1815 // The first time we relayout the window, if the system is
1816 // doing window animations, we want to hold of on any future
1817 // draws until the animation is done.
1818 mWindowsAnimating = true;
1820 } else if (mWindowsAnimating) {
1825 mWillDrawSoon = false;
1826 mNewSurfaceNeeded = false;
1827 mViewVisibility = viewVisibility;
1829 if (mAttachInfo.mHasWindowFocus) {
1830 final boolean imTarget = WindowManager.LayoutParams
1831 .mayUseInputMethod(mWindowAttributes.flags);
1832 if (imTarget != mLastWasImTarget) {
1833 mLastWasImTarget = imTarget;
1834 InputMethodManager imm = InputMethodManager.peekInstance();
1835 if (imm != null && imTarget) {
1836 imm.startGettingWindowFocus(mView);
1837 imm.onWindowFocus(mView, mView.findFocus(),
1838 mWindowAttributes.softInputMode,
1839 !mHasHadWindowFocus, mWindowAttributes.flags);
1844 // Remember if we must report the next draw.
1845 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
1846 mReportNextDraw = true;
1849 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() ||
1850 viewVisibility != View.VISIBLE;
1852 if (!cancelDraw && !newSurface) {
1853 if (!skipDraw || mReportNextDraw) {
1854 if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
1855 for (int i = 0; i < mPendingTransitions.size(); ++i) {
1856 mPendingTransitions.get(i).startChangingAnimations();
1858 mPendingTransitions.clear();
1864 if (viewVisibility == View.VISIBLE) {
1866 scheduleTraversals();
1867 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
1868 for (int i = 0; i < mPendingTransitions.size(); ++i) {
1869 mPendingTransitions.get(i).endChangingAnimations();
1871 mPendingTransitions.clear();
1875 mIsInTraversal = false;
1878 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
1879 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
1881 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1883 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1888 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
1889 * is currently undergoing a layout pass.
1891 * @return whether the view hierarchy is currently undergoing a layout pass
1893 boolean isInLayout() {
1898 * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
1899 * undergoing a layout pass. requestLayout() should not generally be called during layout,
1900 * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
1901 * all children in that container hierarchy are measured and laid out at the end of the layout
1902 * pass for that container). If requestLayout() is called anyway, we handle it correctly
1903 * by registering all requesters during a frame as it proceeds. At the end of the frame,
1904 * we check all of those views to see if any still have pending layout requests, which
1905 * indicates that they were not correctly handled by their container hierarchy. If that is
1906 * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
1907 * to blank containers, and force a second request/measure/layout pass in this frame. If
1908 * more requestLayout() calls are received during that second layout pass, we post those
1909 * requests to the next frame to avoid possible infinite loops.
1911 * <p>The return value from this method indicates whether the request should proceed
1912 * (if it is a request during the first layout pass) or should be skipped and posted to the
1913 * next frame (if it is a request during the second layout pass).</p>
1915 * @param view the view that requested the layout.
1917 * @return true if request should proceed, false otherwise.
1919 boolean requestLayoutDuringLayout(final View view) {
1920 if (view.mParent == null || view.mAttachInfo == null) {
1921 // Would not normally trigger another layout, so just let it pass through as usual
1924 if (!mHandlingLayoutInLayoutRequest) {
1925 if (!mLayoutRequesters.contains(view)) {
1926 mLayoutRequesters.add(view);
1930 Log.w("View", "requestLayout() called by " + view + " during second layout pass: " +
1931 "posting to next frame");
1932 view.post(new Runnable() {
1935 view.requestLayout();
1942 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
1943 int desiredWindowHeight) {
1944 mLayoutRequested = false;
1945 mScrollMayChange = true;
1948 final View host = mView;
1949 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
1950 Log.v(TAG, "Laying out " + host + " to (" +
1951 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
1954 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
1956 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
1959 int numViewsRequestingLayout = mLayoutRequesters.size();
1960 if (numViewsRequestingLayout > 0) {
1961 // requestLayout() was called during layout.
1962 // If no layout-request flags are set on the requesting views, there is no problem.
1963 // If some requests are still pending, then we need to clear those flags and do
1964 // a full request/measure/layout pass to handle this situation.
1966 // Check state of layout flags for all requesters
1967 ArrayList<View> mValidLayoutRequesters = null;
1968 for (int i = 0; i < numViewsRequestingLayout; ++i) {
1969 View view = mLayoutRequesters.get(i);
1970 if ((view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == View.PFLAG_FORCE_LAYOUT) {
1971 while (view != null && view.mAttachInfo != null && view.mParent != null &&
1972 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
1973 if ((view.mViewFlags & View.VISIBILITY_MASK) != View.GONE) {
1974 // Only trigger new requests for non-GONE views
1975 Log.w(TAG, "requestLayout() improperly called during " +
1976 "layout: running second layout pass for " + view);
1977 if (mValidLayoutRequesters == null) {
1978 mValidLayoutRequesters = new ArrayList<View>();
1980 mValidLayoutRequesters.add(view);
1983 if (view.mParent instanceof View) {
1984 view = (View) view.mParent;
1991 if (mValidLayoutRequesters != null) {
1992 // Clear flags throughout hierarchy, walking up from each flagged requester
1993 for (int i = 0; i < numViewsRequestingLayout; ++i) {
1994 View view = mLayoutRequesters.get(i);
1995 while (view != null &&
1996 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
1997 view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
1998 if (view.mParent instanceof View) {
1999 view = (View) view.mParent;
2005 // Process fresh layout requests, then measure and layout
2006 mHandlingLayoutInLayoutRequest = true;
2007 int numValidRequests = mValidLayoutRequesters.size();
2008 for (int i = 0; i < numValidRequests; ++i) {
2009 mValidLayoutRequesters.get(i).requestLayout();
2011 measureHierarchy(host, lp, mView.getContext().getResources(),
2012 desiredWindowWidth, desiredWindowHeight);
2014 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2015 mHandlingLayoutInLayoutRequest = false;
2017 mLayoutRequesters.clear();
2020 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2025 public void requestTransparentRegion(View child) {
2026 // the test below should not fail unless someone is messing with us
2028 if (mView == child) {
2029 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
2030 // Need to make sure we re-evaluate the window attributes next
2031 // time around, to ensure the window has the correct format.
2032 mWindowAttributesChanged = true;
2033 mWindowAttributesChangesFlag = 0;
2039 * Figures out the measure spec for the root view in a window based on it's
2043 * The available width or height of the window
2045 * @param rootDimension
2046 * The layout params for one dimension (width or height) of the
2049 * @return The measure spec to use to measure the root view.
2051 private static int getRootMeasureSpec(int windowSize, int rootDimension) {
2053 switch (rootDimension) {
2055 case ViewGroup.LayoutParams.MATCH_PARENT:
2056 // Window can't resize. Force root view to be windowSize.
2057 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2059 case ViewGroup.LayoutParams.WRAP_CONTENT:
2060 // Window can resize. Set max size for root view.
2061 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2064 // Window wants to be an exact size. Force root view to be that size.
2065 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2071 int mHardwareYOffset;
2073 final Paint mResizePaint = new Paint();
2075 public void onHardwarePreDraw(HardwareCanvas canvas) {
2076 canvas.translate(0, -mHardwareYOffset);
2079 public void onHardwarePostDraw(HardwareCanvas canvas) {
2080 if (mResizeBuffer != null) {
2081 mResizePaint.setAlpha(mResizeAlpha);
2082 canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint);
2084 drawAccessibilityFocusedDrawableIfNeeded(canvas);
2090 void outputDisplayList(View view) {
2091 if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) {
2092 DisplayList displayList = view.getDisplayList();
2093 if (displayList != null) {
2094 mAttachInfo.mHardwareCanvas.outputDisplayList(displayList);
2100 * @see #PROPERTY_PROFILE_RENDERING
2102 private void profileRendering(boolean enabled) {
2103 if (mProfileRendering) {
2104 mRenderProfilingEnabled = enabled;
2105 if (mRenderProfiler == null) {
2106 mRenderProfiler = new Choreographer.FrameCallback() {
2108 public void doFrame(long frameTimeNanos) {
2109 mDirty.set(0, 0, mWidth, mHeight);
2110 scheduleTraversals();
2111 if (mRenderProfilingEnabled) {
2112 mChoreographer.postFrameCallback(mRenderProfiler);
2116 mChoreographer.postFrameCallback(mRenderProfiler);
2118 mChoreographer.removeFrameCallback(mRenderProfiler);
2119 mRenderProfiler = null;
2125 * Called from draw() when DEBUG_FPS is enabled
2127 private void trackFPS() {
2128 // Tracks frames per second drawn. First value in a series of draws may be bogus
2129 // because it down not account for the intervening idle time
2130 long nowTime = System.currentTimeMillis();
2131 if (mFpsStartTime < 0) {
2132 mFpsStartTime = mFpsPrevTime = nowTime;
2136 String thisHash = Integer.toHexString(System.identityHashCode(this));
2137 long frameTime = nowTime - mFpsPrevTime;
2138 long totalTime = nowTime - mFpsStartTime;
2139 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime);
2140 mFpsPrevTime = nowTime;
2141 if (totalTime > 1000) {
2142 float fps = (float) mFpsNumFrames * 1000 / totalTime;
2143 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps);
2144 mFpsStartTime = nowTime;
2150 private void performDraw() {
2151 if (!mAttachInfo.mScreenOn && !mReportNextDraw) {
2155 final boolean fullRedrawNeeded = mFullRedrawNeeded;
2156 mFullRedrawNeeded = false;
2159 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2161 draw(fullRedrawNeeded);
2164 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2167 if (mReportNextDraw) {
2168 mReportNextDraw = false;
2171 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2173 if (mSurfaceHolder != null && mSurface.isValid()) {
2174 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2175 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2176 if (callbacks != null) {
2177 for (SurfaceHolder.Callback c : callbacks) {
2178 if (c instanceof SurfaceHolder.Callback2) {
2179 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
2186 mWindowSession.finishDrawing(mWindow);
2187 } catch (RemoteException e) {
2192 private void draw(boolean fullRedrawNeeded) {
2193 Surface surface = mSurface;
2194 if (!surface.isValid()) {
2202 if (!sFirstDrawComplete) {
2203 synchronized (sFirstDrawHandlers) {
2204 sFirstDrawComplete = true;
2205 final int count = sFirstDrawHandlers.size();
2206 for (int i = 0; i< count; i++) {
2207 mHandler.post(sFirstDrawHandlers.get(i));
2212 scrollToRectOrFocus(null, false);
2214 final AttachInfo attachInfo = mAttachInfo;
2215 if (attachInfo.mViewScrollChanged) {
2216 attachInfo.mViewScrollChanged = false;
2217 attachInfo.mTreeObserver.dispatchOnScrollChanged();
2221 boolean animating = mScroller != null && mScroller.computeScrollOffset();
2223 yoff = mScroller.getCurrY();
2227 if (mCurScrollY != yoff) {
2229 fullRedrawNeeded = true;
2232 final float appScale = attachInfo.mApplicationScale;
2233 final boolean scalingRequired = attachInfo.mScalingRequired;
2235 int resizeAlpha = 0;
2236 if (mResizeBuffer != null) {
2237 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime;
2238 if (deltaTime < mResizeBufferDuration) {
2239 float amt = deltaTime/(float) mResizeBufferDuration;
2240 amt = mResizeInterpolator.getInterpolation(amt);
2242 resizeAlpha = 255 - (int)(amt*255);
2244 disposeResizeBuffer();
2248 final Rect dirty = mDirty;
2249 if (mSurfaceHolder != null) {
2250 // The app owns the surface, we won't draw.
2253 if (mScroller != null) {
2254 mScroller.abortAnimation();
2256 disposeResizeBuffer();
2261 if (fullRedrawNeeded) {
2262 attachInfo.mIgnoreDirtyState = true;
2263 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2266 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2267 Log.v(TAG, "Draw " + mView + "/"
2268 + mWindowAttributes.getTitle()
2269 + ": dirty={" + dirty.left + "," + dirty.top
2270 + "," + dirty.right + "," + dirty.bottom + "} surface="
2271 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2272 appScale + ", width=" + mWidth + ", height=" + mHeight);
2275 invalidateDisplayLists();
2277 attachInfo.mTreeObserver.dispatchOnDraw();
2279 if (!dirty.isEmpty() || mIsAnimating) {
2280 if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) {
2281 // Draw with hardware renderer.
2282 mIsAnimating = false;
2283 mHardwareYOffset = yoff;
2284 mResizeAlpha = resizeAlpha;
2286 mCurrentDirty.set(dirty);
2287 mCurrentDirty.union(mPreviousDirty);
2288 mPreviousDirty.set(dirty);
2291 if (attachInfo.mHardwareRenderer.draw(mView, attachInfo, this,
2292 animating ? null : mCurrentDirty)) {
2293 mPreviousDirty.set(0, 0, mWidth, mHeight);
2295 } else if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) {
2301 mFullRedrawNeeded = true;
2302 scheduleTraversals();
2307 * @return true if drawing was succesfull, false if an error occurred
2309 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff,
2310 boolean scalingRequired, Rect dirty) {
2312 // If we get here with a disabled & requested hardware renderer, something went
2313 // wrong (an invalidate posted right before we destroyed the hardware surface
2314 // for instance) so we should just bail out. Locking the surface with software
2315 // rendering at this point would lock it forever and prevent hardware renderer
2316 // from doing its job when it comes back.
2317 if (attachInfo.mHardwareRenderer != null && !attachInfo.mHardwareRenderer.isEnabled() &&
2318 attachInfo.mHardwareRenderer.isRequested()) {
2319 mFullRedrawNeeded = true;
2320 scheduleTraversals();
2324 // Draw with software renderer.
2327 int left = dirty.left;
2328 int top = dirty.top;
2329 int right = dirty.right;
2330 int bottom = dirty.bottom;
2332 canvas = mSurface.lockCanvas(dirty);
2334 if (left != dirty.left || top != dirty.top || right != dirty.right ||
2335 bottom != dirty.bottom) {
2336 attachInfo.mIgnoreDirtyState = true;
2339 // TODO: Do this in native
2340 canvas.setDensity(mDensity);
2341 } catch (Surface.OutOfResourcesException e) {
2342 Log.e(TAG, "OutOfResourcesException locking surface", e);
2344 if (!mWindowSession.outOfMemory(mWindow)) {
2345 Slog.w(TAG, "No processes killed for memory; killing self");
2346 Process.killProcess(Process.myPid());
2348 } catch (RemoteException ex) {
2350 mLayoutRequested = true; // ask wm for a new surface next time.
2352 } catch (IllegalArgumentException e) {
2353 Log.e(TAG, "Could not lock surface", e);
2354 // Don't assume this is due to out of memory, it could be
2355 // something else, and if it is something else then we could
2356 // kill stuff (or ourself) for no reason.
2357 mLayoutRequested = true; // ask wm for a new surface next time.
2362 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2363 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
2364 + canvas.getWidth() + ", h=" + canvas.getHeight());
2365 //canvas.drawARGB(255, 255, 0, 0);
2368 // If this bitmap's format includes an alpha channel, we
2369 // need to clear it before drawing so that the child will
2370 // properly re-composite its drawing on a transparent
2371 // background. This automatically respects the clip/dirty region
2373 // If we are applying an offset, we need to clear the area
2374 // where the offset doesn't appear to avoid having garbage
2375 // left in the blank areas.
2376 if (!canvas.isOpaque() || yoff != 0) {
2377 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2381 mIsAnimating = false;
2382 attachInfo.mDrawingTime = SystemClock.uptimeMillis();
2383 mView.mPrivateFlags |= View.PFLAG_DRAWN;
2386 Context cxt = mView.getContext();
2387 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
2388 ", metrics=" + cxt.getResources().getDisplayMetrics() +
2389 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2392 canvas.translate(0, -yoff);
2393 if (mTranslator != null) {
2394 mTranslator.translateCanvas(canvas);
2396 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2397 attachInfo.mSetIgnoreDirtyState = false;
2401 drawAccessibilityFocusedDrawableIfNeeded(canvas);
2403 if (!attachInfo.mSetIgnoreDirtyState) {
2404 // Only clear the flag if it was not set during the mView.draw() call
2405 attachInfo.mIgnoreDirtyState = false;
2410 surface.unlockCanvasAndPost(canvas);
2411 } catch (IllegalArgumentException e) {
2412 Log.e(TAG, "Could not unlock surface", e);
2413 mLayoutRequested = true; // ask wm for a new surface next time.
2414 //noinspection ReturnInsideFinallyBlock
2419 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
2426 * We want to draw a highlight around the current accessibility focused.
2427 * Since adding a style for all possible view is not a viable option we
2428 * have this specialized drawing method.
2430 * Note: We are doing this here to be able to draw the highlight for
2431 * virtual views in addition to real ones.
2433 * @param canvas The canvas on which to draw.
2435 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2436 AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2437 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2440 if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) {
2443 Drawable drawable = getAccessibilityFocusedDrawable();
2444 if (drawable == null) {
2447 AccessibilityNodeProvider provider =
2448 mAccessibilityFocusedHost.getAccessibilityNodeProvider();
2449 Rect bounds = mView.mAttachInfo.mTmpInvalRect;
2450 if (provider == null) {
2451 mAccessibilityFocusedHost.getBoundsOnScreen(bounds);
2453 if (mAccessibilityFocusedVirtualView == null) {
2456 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2458 bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
2459 bounds.intersect(0, 0, mAttachInfo.mViewRootImpl.mWidth, mAttachInfo.mViewRootImpl.mHeight);
2460 drawable.setBounds(bounds);
2461 drawable.draw(canvas);
2464 private Drawable getAccessibilityFocusedDrawable() {
2465 if (mAttachInfo != null) {
2466 // Lazily load the accessibility focus drawable.
2467 if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2468 TypedValue value = new TypedValue();
2469 final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2470 R.attr.accessibilityFocusedDrawable, value, true);
2472 mAttachInfo.mAccessibilityFocusDrawable =
2473 mView.mContext.getResources().getDrawable(value.resourceId);
2476 return mAttachInfo.mAccessibilityFocusDrawable;
2481 void invalidateDisplayLists() {
2482 final ArrayList<DisplayList> displayLists = mDisplayLists;
2483 final int count = displayLists.size();
2485 for (int i = 0; i < count; i++) {
2486 final DisplayList displayList = displayLists.get(i);
2487 if (displayList.isDirty()) {
2488 displayList.invalidate();
2489 displayList.clear();
2490 displayList.setDirty(false);
2494 displayLists.clear();
2497 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2498 final View.AttachInfo attachInfo = mAttachInfo;
2499 final Rect ci = attachInfo.mContentInsets;
2500 final Rect vi = attachInfo.mVisibleInsets;
2502 boolean handled = false;
2504 if (vi.left > ci.left || vi.top > ci.top
2505 || vi.right > ci.right || vi.bottom > ci.bottom) {
2506 // We'll assume that we aren't going to change the scroll
2507 // offset, since we want to avoid that unless it is actually
2508 // going to make the focus visible... otherwise we scroll
2509 // all over the place.
2511 // We can be called for two different situations: during a draw,
2512 // to update the scroll position if the focus has changed (in which
2513 // case 'rectangle' is null), or in response to a
2514 // requestChildRectangleOnScreen() call (in which case 'rectangle'
2515 // is non-null and we just want to scroll to whatever that
2517 View focus = mRealFocusedView;
2519 // When in touch mode, focus points to the previously focused view,
2520 // which may have been removed from the view hierarchy. The following
2521 // line checks whether the view is still in our hierarchy.
2522 if (focus == null || focus.mAttachInfo != mAttachInfo) {
2523 mRealFocusedView = null;
2527 if (focus != mLastScrolledFocus) {
2528 // If the focus has changed, then ignore any requests to scroll
2529 // to a rectangle; first we want to make sure the entire focus
2533 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
2534 + " rectangle=" + rectangle + " ci=" + ci
2536 if (focus == mLastScrolledFocus && !mScrollMayChange
2537 && rectangle == null) {
2538 // Optimization: if the focus hasn't changed since last
2539 // time, and no layout has happened, then just leave things
2541 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
2542 + mScrollY + " vi=" + vi.toShortString());
2543 } else if (focus != null) {
2544 // We need to determine if the currently focused view is
2545 // within the visible part of the window and, if not, apply
2546 // a pan so it can be seen.
2547 mLastScrolledFocus = focus;
2548 mScrollMayChange = false;
2549 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
2550 // Try to find the rectangle from the focus view.
2551 if (focus.getGlobalVisibleRect(mVisRect, null)) {
2552 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
2553 + mView.getWidth() + " h=" + mView.getHeight()
2554 + " ci=" + ci.toShortString()
2555 + " vi=" + vi.toShortString());
2556 if (rectangle == null) {
2557 focus.getFocusedRect(mTempRect);
2558 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
2559 + ": focusRect=" + mTempRect.toShortString());
2560 if (mView instanceof ViewGroup) {
2561 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2564 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2565 "Focus in window: focusRect="
2566 + mTempRect.toShortString()
2567 + " visRect=" + mVisRect.toShortString());
2569 mTempRect.set(rectangle);
2570 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2571 "Request scroll to rect: "
2572 + mTempRect.toShortString()
2573 + " visRect=" + mVisRect.toShortString());
2575 if (mTempRect.intersect(mVisRect)) {
2576 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2577 "Focus window visible rect: "
2578 + mTempRect.toShortString());
2579 if (mTempRect.height() >
2580 (mView.getHeight()-vi.top-vi.bottom)) {
2581 // If the focus simply is not going to fit, then
2582 // best is probably just to leave things as-is.
2583 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2584 "Too tall; leaving scrollY=" + scrollY);
2585 } else if ((mTempRect.top-scrollY) < vi.top) {
2586 scrollY -= vi.top - (mTempRect.top-scrollY);
2587 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2588 "Top covered; scrollY=" + scrollY);
2589 } else if ((mTempRect.bottom-scrollY)
2590 > (mView.getHeight()-vi.bottom)) {
2591 scrollY += (mTempRect.bottom-scrollY)
2592 - (mView.getHeight()-vi.bottom);
2593 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
2594 "Bottom covered; scrollY=" + scrollY);
2602 if (scrollY != mScrollY) {
2603 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
2604 + mScrollY + " , new=" + scrollY);
2605 if (!immediate && mResizeBuffer == null) {
2606 if (mScroller == null) {
2607 mScroller = new Scroller(mView.getContext());
2609 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2610 } else if (mScroller != null) {
2611 mScroller.abortAnimation();
2622 public View getAccessibilityFocusedHost() {
2623 return mAccessibilityFocusedHost;
2629 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
2630 return mAccessibilityFocusedVirtualView;
2633 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
2634 // If we have a virtual view with accessibility focus we need
2635 // to clear the focus and invalidate the virtual view bounds.
2636 if (mAccessibilityFocusedVirtualView != null) {
2638 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
2639 View focusHost = mAccessibilityFocusedHost;
2640 focusHost.clearAccessibilityFocusNoCallbacks();
2642 // Wipe the state of the current accessibility focus since
2643 // the call into the provider to clear accessibility focus
2644 // will fire an accessibility event which will end up calling
2645 // this method and we want to have clean state when this
2646 // invocation happens.
2647 mAccessibilityFocusedHost = null;
2648 mAccessibilityFocusedVirtualView = null;
2650 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
2651 if (provider != null) {
2652 // Invalidate the area of the cleared accessibility focus.
2653 focusNode.getBoundsInParent(mTempRect);
2654 focusHost.invalidate(mTempRect);
2655 // Clear accessibility focus in the virtual node.
2656 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
2657 focusNode.getSourceNodeId());
2658 provider.performAction(virtualNodeId,
2659 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
2661 focusNode.recycle();
2663 if (mAccessibilityFocusedHost != null) {
2664 // Clear accessibility focus in the view.
2665 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
2668 // Set the new focus host and node.
2669 mAccessibilityFocusedHost = view;
2670 mAccessibilityFocusedVirtualView = node;
2673 public void requestChildFocus(View child, View focused) {
2676 if (DEBUG_INPUT_RESIZE) {
2677 Log.v(TAG, "Request child focus: focus now " + focused);
2680 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused);
2681 scheduleTraversals();
2683 mFocusedView = mRealFocusedView = focused;
2686 public void clearChildFocus(View child) {
2689 if (DEBUG_INPUT_RESIZE) {
2690 Log.v(TAG, "Clearing child focus");
2693 mOldFocusedView = mFocusedView;
2695 // Invoke the listener only if there is no view to take focus
2696 if (focusSearch(null, View.FOCUS_FORWARD) == null) {
2697 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null);
2700 mFocusedView = mRealFocusedView = null;
2704 public ViewParent getParentForAccessibility() {
2708 public void focusableViewAvailable(View v) {
2710 if (mView != null) {
2711 if (!mView.hasFocus()) {
2714 // the one case where will transfer focus away from the current one
2715 // is if the current view is a view group that prefers to give focus
2716 // to its children first AND the view is a descendant of it.
2717 mFocusedView = mView.findFocus();
2718 boolean descendantsHaveDibsOnFocus =
2719 (mFocusedView instanceof ViewGroup) &&
2720 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
2721 ViewGroup.FOCUS_AFTER_DESCENDANTS);
2722 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
2723 // If a view gets the focus, the listener will be invoked from requestChildFocus()
2730 public void recomputeViewAttributes(View child) {
2732 if (mView == child) {
2733 mAttachInfo.mRecomputeGlobalAttributes = true;
2734 if (!mWillDrawSoon) {
2735 scheduleTraversals();
2740 void dispatchDetachedFromWindow() {
2741 if (mView != null && mView.mAttachInfo != null) {
2742 if (mAttachInfo.mHardwareRenderer != null &&
2743 mAttachInfo.mHardwareRenderer.isEnabled()) {
2744 mAttachInfo.mHardwareRenderer.validate();
2746 mView.dispatchDetachedFromWindow();
2749 mAccessibilityInteractionConnectionManager.ensureNoConnection();
2750 mAccessibilityManager.removeAccessibilityStateChangeListener(
2751 mAccessibilityInteractionConnectionManager);
2752 removeSendWindowContentChangedCallback();
2754 destroyHardwareRenderer();
2756 setAccessibilityFocus(null, null);
2759 mAttachInfo.mRootView = null;
2760 mAttachInfo.mSurface = null;
2764 if (mInputQueueCallback != null && mInputQueue != null) {
2765 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
2766 mInputQueueCallback = null;
2768 } else if (mInputEventReceiver != null) {
2769 mInputEventReceiver.dispose();
2770 mInputEventReceiver = null;
2773 mWindowSession.remove(mWindow);
2774 } catch (RemoteException e) {
2777 // Dispose the input channel after removing the window so the Window Manager
2778 // doesn't interpret the input channel being closed as an abnormal termination.
2779 if (mInputChannel != null) {
2780 mInputChannel.dispose();
2781 mInputChannel = null;
2784 unscheduleTraversals();
2787 void updateConfiguration(Configuration config, boolean force) {
2788 if (DEBUG_CONFIGURATION) Log.v(TAG,
2789 "Applying new config to window "
2790 + mWindowAttributes.getTitle()
2793 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded();
2795 config = new Configuration(config);
2796 ci.applyToConfiguration(mNoncompatDensity, config);
2799 synchronized (sConfigCallbacks) {
2800 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
2801 sConfigCallbacks.get(i).onConfigurationChanged(config);
2804 if (mView != null) {
2805 // At this point the resources have been updated to
2806 // have the most recent config, whatever that is. Use
2807 // the one in them which may be newer.
2808 config = mView.getResources().getConfiguration();
2809 if (force || mLastConfiguration.diff(config) != 0) {
2810 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
2811 final int currentLayoutDirection = config.getLayoutDirection();
2812 mLastConfiguration.setTo(config);
2813 if (lastLayoutDirection != currentLayoutDirection &&
2814 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
2815 mView.setLayoutDirection(currentLayoutDirection);
2817 mView.dispatchConfigurationChanged(config);
2823 * Return true if child is an ancestor of parent, (or equal to the parent).
2825 public static boolean isViewDescendantOf(View child, View parent) {
2826 if (child == parent) {
2830 final ViewParent theParent = child.getParent();
2831 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2834 private static void forceLayout(View view) {
2836 if (view instanceof ViewGroup) {
2837 ViewGroup group = (ViewGroup) view;
2838 final int count = group.getChildCount();
2839 for (int i = 0; i < count; i++) {
2840 forceLayout(group.getChildAt(i));
2845 private final static int MSG_INVALIDATE = 1;
2846 private final static int MSG_INVALIDATE_RECT = 2;
2847 private final static int MSG_DIE = 3;
2848 private final static int MSG_RESIZED = 4;
2849 private final static int MSG_RESIZED_REPORT = 5;
2850 private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
2851 private final static int MSG_DISPATCH_KEY = 7;
2852 private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
2853 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
2854 private final static int MSG_IME_FINISHED_EVENT = 10;
2855 private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
2856 private final static int MSG_FINISH_INPUT_CONNECTION = 12;
2857 private final static int MSG_CHECK_FOCUS = 13;
2858 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
2859 private final static int MSG_DISPATCH_DRAG_EVENT = 15;
2860 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
2861 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
2862 private final static int MSG_UPDATE_CONFIGURATION = 18;
2863 private final static int MSG_PROCESS_INPUT_EVENTS = 19;
2864 private final static int MSG_DISPATCH_SCREEN_STATE = 20;
2865 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
2866 private final static int MSG_DISPATCH_DONE_ANIMATING = 22;
2867 private final static int MSG_INVALIDATE_WORLD = 23;
2868 private final static int MSG_WINDOW_MOVED = 24;
2870 final class ViewRootHandler extends Handler {
2872 public String getMessageName(Message message) {
2873 switch (message.what) {
2874 case MSG_INVALIDATE:
2875 return "MSG_INVALIDATE";
2876 case MSG_INVALIDATE_RECT:
2877 return "MSG_INVALIDATE_RECT";
2881 return "MSG_RESIZED";
2882 case MSG_RESIZED_REPORT:
2883 return "MSG_RESIZED_REPORT";
2884 case MSG_WINDOW_FOCUS_CHANGED:
2885 return "MSG_WINDOW_FOCUS_CHANGED";
2886 case MSG_DISPATCH_KEY:
2887 return "MSG_DISPATCH_KEY";
2888 case MSG_DISPATCH_APP_VISIBILITY:
2889 return "MSG_DISPATCH_APP_VISIBILITY";
2890 case MSG_DISPATCH_GET_NEW_SURFACE:
2891 return "MSG_DISPATCH_GET_NEW_SURFACE";
2892 case MSG_IME_FINISHED_EVENT:
2893 return "MSG_IME_FINISHED_EVENT";
2894 case MSG_DISPATCH_KEY_FROM_IME:
2895 return "MSG_DISPATCH_KEY_FROM_IME";
2896 case MSG_FINISH_INPUT_CONNECTION:
2897 return "MSG_FINISH_INPUT_CONNECTION";
2898 case MSG_CHECK_FOCUS:
2899 return "MSG_CHECK_FOCUS";
2900 case MSG_CLOSE_SYSTEM_DIALOGS:
2901 return "MSG_CLOSE_SYSTEM_DIALOGS";
2902 case MSG_DISPATCH_DRAG_EVENT:
2903 return "MSG_DISPATCH_DRAG_EVENT";
2904 case MSG_DISPATCH_DRAG_LOCATION_EVENT:
2905 return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
2906 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
2907 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
2908 case MSG_UPDATE_CONFIGURATION:
2909 return "MSG_UPDATE_CONFIGURATION";
2910 case MSG_PROCESS_INPUT_EVENTS:
2911 return "MSG_PROCESS_INPUT_EVENTS";
2912 case MSG_DISPATCH_SCREEN_STATE:
2913 return "MSG_DISPATCH_SCREEN_STATE";
2914 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
2915 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
2916 case MSG_DISPATCH_DONE_ANIMATING:
2917 return "MSG_DISPATCH_DONE_ANIMATING";
2918 case MSG_WINDOW_MOVED:
2919 return "MSG_WINDOW_MOVED";
2921 return super.getMessageName(message);
2925 public void handleMessage(Message msg) {
2927 case MSG_INVALIDATE:
2928 ((View) msg.obj).invalidate();
2930 case MSG_INVALIDATE_RECT:
2931 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2932 info.target.invalidate(info.left, info.top, info.right, info.bottom);
2935 case MSG_IME_FINISHED_EVENT:
2936 handleImeFinishedEvent(msg.arg1, msg.arg2 != 0);
2938 case MSG_PROCESS_INPUT_EVENTS:
2939 mProcessInputEventsScheduled = false;
2940 doProcessInputEvents();
2942 case MSG_DISPATCH_APP_VISIBILITY:
2943 handleAppVisibility(msg.arg1 != 0);
2945 case MSG_DISPATCH_GET_NEW_SURFACE:
2946 handleGetNewSurface();
2949 // Recycled in the fall through...
2950 SomeArgs args = (SomeArgs) msg.obj;
2951 if (mWinFrame.equals(args.arg1)
2952 && mPendingContentInsets.equals(args.arg2)
2953 && mPendingVisibleInsets.equals(args.arg3)
2954 && args.arg4 == null) {
2957 } // fall through...
2958 case MSG_RESIZED_REPORT:
2960 SomeArgs args = (SomeArgs) msg.obj;
2962 Configuration config = (Configuration) args.arg4;
2963 if (config != null) {
2964 updateConfiguration(config, false);
2967 mWinFrame.set((Rect) args.arg1);
2968 mPendingContentInsets.set((Rect) args.arg2);
2969 mPendingVisibleInsets.set((Rect) args.arg3);
2973 if (msg.what == MSG_RESIZED_REPORT) {
2974 mReportNextDraw = true;
2977 if (mView != null) {
2984 case MSG_WINDOW_MOVED:
2986 final int w = mWinFrame.width();
2987 final int h = mWinFrame.height();
2988 final int l = msg.arg1;
2989 final int t = msg.arg2;
2991 mWinFrame.right = l + w;
2993 mWinFrame.bottom = t + h;
2995 if (mView != null) {
3001 case MSG_WINDOW_FOCUS_CHANGED: {
3003 boolean hasWindowFocus = msg.arg1 != 0;
3004 mAttachInfo.mHasWindowFocus = hasWindowFocus;
3006 profileRendering(hasWindowFocus);
3008 if (hasWindowFocus) {
3009 boolean inTouchMode = msg.arg2 != 0;
3010 ensureTouchModeLocally(inTouchMode);
3012 if (mAttachInfo.mHardwareRenderer != null &&
3013 mSurface != null && mSurface.isValid()) {
3014 mFullRedrawNeeded = true;
3016 if (mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3017 mWidth, mHeight, mHolder.getSurface())) {
3018 mFullRedrawNeeded = true;
3020 } catch (Surface.OutOfResourcesException e) {
3021 Log.e(TAG, "OutOfResourcesException locking surface", e);
3023 if (!mWindowSession.outOfMemory(mWindow)) {
3024 Slog.w(TAG, "No processes killed for memory; killing self");
3025 Process.killProcess(Process.myPid());
3027 } catch (RemoteException ex) {
3030 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3036 mLastWasImTarget = WindowManager.LayoutParams
3037 .mayUseInputMethod(mWindowAttributes.flags);
3039 InputMethodManager imm = InputMethodManager.peekInstance();
3040 if (mView != null) {
3041 if (hasWindowFocus && imm != null && mLastWasImTarget) {
3042 imm.startGettingWindowFocus(mView);
3044 mAttachInfo.mKeyDispatchState.reset();
3045 mView.dispatchWindowFocusChanged(hasWindowFocus);
3048 // Note: must be done after the focus change callbacks,
3049 // so all of the view state is set up correctly.
3050 if (hasWindowFocus) {
3051 if (imm != null && mLastWasImTarget) {
3052 imm.onWindowFocus(mView, mView.findFocus(),
3053 mWindowAttributes.softInputMode,
3054 !mHasHadWindowFocus, mWindowAttributes.flags);
3056 // Clear the forward bit. We can just do this directly, since
3057 // the window manager doesn't care about it.
3058 mWindowAttributes.softInputMode &=
3059 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3060 ((WindowManager.LayoutParams)mView.getLayoutParams())
3062 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3063 mHasHadWindowFocus = true;
3066 setAccessibilityFocus(null, null);
3068 if (mView != null && mAccessibilityManager.isEnabled()) {
3069 if (hasWindowFocus) {
3070 mView.sendAccessibilityEvent(
3071 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3079 case MSG_DISPATCH_KEY: {
3080 KeyEvent event = (KeyEvent)msg.obj;
3081 enqueueInputEvent(event, null, 0, true);
3083 case MSG_DISPATCH_KEY_FROM_IME: {
3084 if (LOCAL_LOGV) Log.v(
3085 TAG, "Dispatching key "
3086 + msg.obj + " from IME to " + mView);
3087 KeyEvent event = (KeyEvent)msg.obj;
3088 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3089 // The IME is trying to say this event is from the
3090 // system! Bad bad bad!
3091 //noinspection UnusedAssignment
3092 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
3094 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3096 case MSG_FINISH_INPUT_CONNECTION: {
3097 InputMethodManager imm = InputMethodManager.peekInstance();
3099 imm.reportFinishInputConnection((InputConnection)msg.obj);
3102 case MSG_CHECK_FOCUS: {
3103 InputMethodManager imm = InputMethodManager.peekInstance();
3108 case MSG_CLOSE_SYSTEM_DIALOGS: {
3109 if (mView != null) {
3110 mView.onCloseSystemDialogs((String)msg.obj);
3113 case MSG_DISPATCH_DRAG_EVENT:
3114 case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3115 DragEvent event = (DragEvent)msg.obj;
3116 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
3117 handleDragEvent(event);
3119 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3120 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3122 case MSG_UPDATE_CONFIGURATION: {
3123 Configuration config = (Configuration)msg.obj;
3124 if (config.isOtherSeqNewer(mLastConfiguration)) {
3125 config = mLastConfiguration;
3127 updateConfiguration(config, false);
3129 case MSG_DISPATCH_SCREEN_STATE: {
3130 if (mView != null) {
3131 handleScreenStateChange(msg.arg1 == 1);
3134 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3135 setAccessibilityFocus(null, null);
3137 case MSG_DISPATCH_DONE_ANIMATING: {
3138 handleDispatchDoneAnimating();
3140 case MSG_INVALIDATE_WORLD: {
3141 if (mView != null) {
3142 invalidateWorld(mView);
3149 final ViewRootHandler mHandler = new ViewRootHandler();
3152 * Something in the current window tells us we need to change the touch mode. For
3153 * example, we are not in touch mode, and the user touches the screen.
3155 * If the touch mode has changed, tell the window manager, and handle it locally.
3157 * @param inTouchMode Whether we want to be in touch mode.
3158 * @return True if the touch mode changed and focus changed was changed as a result
3160 boolean ensureTouchMode(boolean inTouchMode) {
3161 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3162 + "touch mode is " + mAttachInfo.mInTouchMode);
3163 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3165 // tell the window manager
3167 mWindowSession.setInTouchMode(inTouchMode);
3168 } catch (RemoteException e) {
3169 throw new RuntimeException(e);
3172 // handle the change
3173 return ensureTouchModeLocally(inTouchMode);
3177 * Ensure that the touch mode for this window is set, and if it is changing,
3178 * take the appropriate action.
3179 * @param inTouchMode Whether we want to be in touch mode.
3180 * @return True if the touch mode changed and focus changed was changed as a result
3182 private boolean ensureTouchModeLocally(boolean inTouchMode) {
3183 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3184 + "touch mode is " + mAttachInfo.mInTouchMode);
3186 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3188 mAttachInfo.mInTouchMode = inTouchMode;
3189 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3191 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3194 private boolean enterTouchMode() {
3195 if (mView != null) {
3196 if (mView.hasFocus()) {
3197 // note: not relying on mFocusedView here because this could
3198 // be when the window is first being added, and mFocused isn't
3200 final View focused = mView.findFocus();
3201 if (focused != null && !focused.isFocusableInTouchMode()) {
3203 final ViewGroup ancestorToTakeFocus =
3204 findAncestorToTakeFocusInTouchMode(focused);
3205 if (ancestorToTakeFocus != null) {
3206 // there is an ancestor that wants focus after its descendants that
3207 // is focusable in touch mode.. give it focus
3208 return ancestorToTakeFocus.requestFocus();
3210 // nothing appropriate to have focus in touch mode, clear it out
3212 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
3213 mFocusedView = null;
3214 mOldFocusedView = null;
3224 * Find an ancestor of focused that wants focus after its descendants and is
3225 * focusable in touch mode.
3226 * @param focused The currently focused view.
3227 * @return An appropriate view, or null if no such view exists.
3229 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3230 ViewParent parent = focused.getParent();
3231 while (parent instanceof ViewGroup) {
3232 final ViewGroup vgParent = (ViewGroup) parent;
3233 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3234 && vgParent.isFocusableInTouchMode()) {
3237 if (vgParent.isRootNamespace()) {
3240 parent = vgParent.getParent();
3246 private boolean leaveTouchMode() {
3247 if (mView != null) {
3248 if (mView.hasFocus()) {
3249 // i learned the hard way to not trust mFocusedView :)
3250 mFocusedView = mView.findFocus();
3251 if (!(mFocusedView instanceof ViewGroup)) {
3252 // some view has focus, let it keep it
3254 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
3255 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3256 // some view group has focus, and doesn't prefer its children
3257 // over itself for focus, so let them keep it.
3262 // find the best view to give focus to in this brave new non-touch-mode
3264 final View focused = focusSearch(null, View.FOCUS_DOWN);
3265 if (focused != null) {
3266 return focused.requestFocus(View.FOCUS_DOWN);
3272 private void deliverInputEvent(QueuedInputEvent q) {
3273 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
3275 if (q.mEvent instanceof KeyEvent) {
3278 final int source = q.mEvent.getSource();
3279 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3280 deliverPointerEvent(q);
3281 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3282 deliverTrackballEvent(q);
3284 deliverGenericMotionEvent(q);
3288 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3292 private void deliverPointerEvent(QueuedInputEvent q) {
3293 final MotionEvent event = (MotionEvent)q.mEvent;
3294 final boolean isTouchEvent = event.isTouchEvent();
3295 if (mInputEventConsistencyVerifier != null) {
3297 mInputEventConsistencyVerifier.onTouchEvent(event, 0);
3299 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3303 // If there is no view, then the event will not be handled.
3304 if (mView == null || !mAdded) {
3305 finishInputEvent(q, false);
3309 // Translate the pointer event for compatibility, if needed.
3310 if (mTranslator != null) {
3311 mTranslator.translateEventInScreenToAppWindow(event);
3314 // Enter touch mode on down or scroll.
3315 final int action = event.getAction();
3316 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
3317 ensureTouchMode(true);
3320 // Offset the scroll position.
3321 if (mCurScrollY != 0) {
3322 event.offsetLocation(0, mCurScrollY);
3324 if (MEASURE_LATENCY) {
3325 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
3328 // Remember the touch position for possible drag-initiation.
3330 mLastTouchPoint.x = event.getRawX();
3331 mLastTouchPoint.y = event.getRawY();
3334 // Dispatch touch to view hierarchy.
3335 boolean handled = mView.dispatchPointerEvent(event);
3336 if (MEASURE_LATENCY) {
3337 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
3340 finishInputEvent(q, true);
3344 // Pointer event was unhandled.
3345 finishInputEvent(q, false);
3348 private void deliverTrackballEvent(QueuedInputEvent q) {
3349 final MotionEvent event = (MotionEvent)q.mEvent;
3350 if (mInputEventConsistencyVerifier != null) {
3351 mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
3354 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3356 Log.v(TAG, "Dispatching trackball " + event + " to " + mView);
3358 // Dispatch to the IME before propagating down the view hierarchy.
3359 // The IME will eventually call back into handleImeFinishedEvent.
3360 if (mLastWasImTarget) {
3361 InputMethodManager imm = InputMethodManager.peekInstance();
3363 final int seq = event.getSequenceNumber();
3365 Log.v(TAG, "Sending trackball event to IME: seq="
3366 + seq + " event=" + event);
3367 imm.dispatchTrackballEvent(mView.getContext(), seq, event,
3368 mInputMethodCallback);
3374 // Not dispatching to IME, continue with post IME actions.
3375 deliverTrackballEventPostIme(q);
3378 private void deliverTrackballEventPostIme(QueuedInputEvent q) {
3379 final MotionEvent event = (MotionEvent) q.mEvent;
3381 // If there is no view, then the event will not be handled.
3382 if (mView == null || !mAdded) {
3383 finishInputEvent(q, false);
3387 // Deliver the trackball event to the view.
3388 if (mView.dispatchTrackballEvent(event)) {
3389 // If we reach this, we delivered a trackball event to mView and
3390 // mView consumed it. Because we will not translate the trackball
3391 // event into a key event, touch mode will not exit, so we exit
3393 ensureTouchMode(false);
3395 finishInputEvent(q, true);
3396 mLastTrackballTime = Integer.MIN_VALUE;
3400 // Translate the trackball event into DPAD keys and try to deliver those.
3401 final TrackballAxis x = mTrackballAxisX;
3402 final TrackballAxis y = mTrackballAxisY;
3404 long curTime = SystemClock.uptimeMillis();
3405 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
3406 // It has been too long since the last movement,
3407 // so restart at the beginning.
3410 mLastTrackballTime = curTime;
3413 final int action = event.getAction();
3414 final int metaState = event.getMetaState();
3416 case MotionEvent.ACTION_DOWN:
3419 enqueueInputEvent(new KeyEvent(curTime, curTime,
3420 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3421 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3422 InputDevice.SOURCE_KEYBOARD));
3424 case MotionEvent.ACTION_UP:
3427 enqueueInputEvent(new KeyEvent(curTime, curTime,
3428 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
3429 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3430 InputDevice.SOURCE_KEYBOARD));
3434 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
3435 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
3436 + " move=" + event.getX()
3437 + " / Y=" + y.position + " step="
3438 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
3439 + " move=" + event.getY());
3440 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
3441 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
3443 // Generate DPAD events based on the trackball movement.
3444 // We pick the axis that has moved the most as the direction of
3445 // the DPAD. When we generate DPAD events for one axis, then the
3446 // other axis is reset -- we don't want to perform DPAD jumps due
3447 // to slight movements in the trackball when making major movements
3448 // along the other axis.
3453 movement = x.generate((2/event.getXPrecision()));
3454 if (movement != 0) {
3455 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
3456 : KeyEvent.KEYCODE_DPAD_LEFT;
3457 accel = x.acceleration;
3460 } else if (yOff > 0) {
3461 movement = y.generate((2/event.getYPrecision()));
3462 if (movement != 0) {
3463 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
3464 : KeyEvent.KEYCODE_DPAD_UP;
3465 accel = y.acceleration;
3471 if (movement < 0) movement = -movement;
3472 int accelMovement = (int)(movement * accel);
3473 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
3474 + " accelMovement=" + accelMovement
3475 + " accel=" + accel);
3476 if (accelMovement > movement) {
3477 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3480 int repeatCount = accelMovement - movement;
3481 enqueueInputEvent(new KeyEvent(curTime, curTime,
3482 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
3483 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3484 InputDevice.SOURCE_KEYBOARD));
3486 while (movement > 0) {
3487 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
3490 curTime = SystemClock.uptimeMillis();
3491 enqueueInputEvent(new KeyEvent(curTime, curTime,
3492 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
3493 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3494 InputDevice.SOURCE_KEYBOARD));
3495 enqueueInputEvent(new KeyEvent(curTime, curTime,
3496 KeyEvent.ACTION_UP, keycode, 0, metaState,
3497 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
3498 InputDevice.SOURCE_KEYBOARD));
3500 mLastTrackballTime = curTime;
3503 // Unfortunately we can't tell whether the application consumed the keys, so
3504 // we always consider the trackball event handled.
3505 finishInputEvent(q, true);
3508 private void deliverGenericMotionEvent(QueuedInputEvent q) {
3509 final MotionEvent event = (MotionEvent)q.mEvent;
3510 if (mInputEventConsistencyVerifier != null) {
3511 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
3513 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3515 Log.v(TAG, "Dispatching generic motion " + event + " to " + mView);
3517 // Dispatch to the IME before propagating down the view hierarchy.
3518 // The IME will eventually call back into handleImeFinishedEvent.
3519 if (mLastWasImTarget) {
3520 InputMethodManager imm = InputMethodManager.peekInstance();
3522 final int seq = event.getSequenceNumber();
3524 Log.v(TAG, "Sending generic motion event to IME: seq="
3525 + seq + " event=" + event);
3526 imm.dispatchGenericMotionEvent(mView.getContext(), seq, event,
3527 mInputMethodCallback);
3533 // Not dispatching to IME, continue with post IME actions.
3534 deliverGenericMotionEventPostIme(q);
3537 private void deliverGenericMotionEventPostIme(QueuedInputEvent q) {
3538 final MotionEvent event = (MotionEvent) q.mEvent;
3539 final int source = event.getSource();
3540 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
3541 final boolean isTouchPad = (source & InputDevice.SOURCE_CLASS_POSITION) != 0;
3543 // If there is no view, then the event will not be handled.
3544 if (mView == null || !mAdded) {
3546 updateJoystickDirection(event, false);
3547 } else if (isTouchPad) {
3548 //Convert TouchPad motion into a TrackBall event
3549 mSimulatedTrackball.updateTrackballDirection(this, event);
3551 finishInputEvent(q, false);
3555 // Deliver the event to the view.
3556 if (mView.dispatchGenericMotionEvent(event)) {
3558 updateJoystickDirection(event, false);
3559 } else if (isTouchPad) {
3560 //Convert TouchPad motion into a TrackBall event
3561 mSimulatedTrackball.updateTrackballDirection(this, event);
3563 finishInputEvent(q, true);
3568 // Translate the joystick event into DPAD keys and try to deliver
3570 updateJoystickDirection(event, true);
3571 finishInputEvent(q, true);
3572 } else if (isTouchPad) {
3573 //Convert TouchPad motion into a TrackBall event
3574 mSimulatedTrackball.updateTrackballDirection(this, event);
3575 finishInputEvent(q, true);
3577 finishInputEvent(q, false);
3581 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
3582 final long time = event.getEventTime();
3583 final int metaState = event.getMetaState();
3584 final int deviceId = event.getDeviceId();
3585 final int source = event.getSource();
3587 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
3588 if (xDirection == 0) {
3589 xDirection = joystickAxisValueToDirection(event.getX());
3592 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
3593 if (yDirection == 0) {
3594 yDirection = joystickAxisValueToDirection(event.getY());
3597 if (xDirection != mLastJoystickXDirection) {
3598 if (mLastJoystickXKeyCode != 0) {
3599 enqueueInputEvent(new KeyEvent(time, time,
3600 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
3601 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3602 mLastJoystickXKeyCode = 0;
3605 mLastJoystickXDirection = xDirection;
3607 if (xDirection != 0 && synthesizeNewKeys) {
3608 mLastJoystickXKeyCode = xDirection > 0
3609 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
3610 enqueueInputEvent(new KeyEvent(time, time,
3611 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
3612 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3616 if (yDirection != mLastJoystickYDirection) {
3617 if (mLastJoystickYKeyCode != 0) {
3618 enqueueInputEvent(new KeyEvent(time, time,
3619 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
3620 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3621 mLastJoystickYKeyCode = 0;
3624 mLastJoystickYDirection = yDirection;
3626 if (yDirection != 0 && synthesizeNewKeys) {
3627 mLastJoystickYKeyCode = yDirection > 0
3628 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
3629 enqueueInputEvent(new KeyEvent(time, time,
3630 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
3631 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
3636 private static int joystickAxisValueToDirection(float value) {
3637 if (value >= 0.5f) {
3639 } else if (value <= -0.5f) {
3647 * Returns true if the key is used for keyboard navigation.
3648 * @param keyEvent The key event.
3649 * @return True if the key is used for keyboard navigation.
3651 private static boolean isNavigationKey(KeyEvent keyEvent) {
3652 switch (keyEvent.getKeyCode()) {
3653 case KeyEvent.KEYCODE_DPAD_LEFT:
3654 case KeyEvent.KEYCODE_DPAD_RIGHT:
3655 case KeyEvent.KEYCODE_DPAD_UP:
3656 case KeyEvent.KEYCODE_DPAD_DOWN:
3657 case KeyEvent.KEYCODE_DPAD_CENTER:
3658 case KeyEvent.KEYCODE_PAGE_UP:
3659 case KeyEvent.KEYCODE_PAGE_DOWN:
3660 case KeyEvent.KEYCODE_MOVE_HOME:
3661 case KeyEvent.KEYCODE_MOVE_END:
3662 case KeyEvent.KEYCODE_TAB:
3663 case KeyEvent.KEYCODE_SPACE:
3664 case KeyEvent.KEYCODE_ENTER:
3671 * Returns true if the key is used for typing.
3672 * @param keyEvent The key event.
3673 * @return True if the key is used for typing.
3675 private static boolean isTypingKey(KeyEvent keyEvent) {
3676 return keyEvent.getUnicodeChar() > 0;
3680 * See if the key event means we should leave touch mode (and leave touch mode if so).
3681 * @param event The key event.
3682 * @return Whether this key event should be consumed (meaning the act of
3683 * leaving touch mode alone is considered the event).
3685 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
3686 // Only relevant in touch mode.
3687 if (!mAttachInfo.mInTouchMode) {
3691 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
3692 final int action = event.getAction();
3693 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
3697 // Don't leave touch mode if the IME told us not to.
3698 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
3702 // If the key can be used for keyboard navigation then leave touch mode
3703 // and select a focused view if needed (in ensureTouchMode).
3704 // When a new focused view is selected, we consume the navigation key because
3705 // navigation doesn't make much sense unless a view already has focus so
3706 // the key's purpose is to set focus.
3707 if (isNavigationKey(event)) {
3708 return ensureTouchMode(false);
3711 // If the key can be used for typing then leave touch mode
3712 // and select a focused view if needed (in ensureTouchMode).
3713 // Always allow the view to process the typing key.
3714 if (isTypingKey(event)) {
3715 ensureTouchMode(false);
3722 private void deliverKeyEvent(QueuedInputEvent q) {
3723 final KeyEvent event = (KeyEvent)q.mEvent;
3724 if (mInputEventConsistencyVerifier != null) {
3725 mInputEventConsistencyVerifier.onKeyEvent(event, 0);
3728 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {
3729 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
3731 // Perform predispatching before the IME.
3732 if (mView.dispatchKeyEventPreIme(event)) {
3733 finishInputEvent(q, true);
3737 // Dispatch to the IME before propagating down the view hierarchy.
3738 // The IME will eventually call back into handleImeFinishedEvent.
3739 if (mLastWasImTarget) {
3740 InputMethodManager imm = InputMethodManager.peekInstance();
3742 final int seq = event.getSequenceNumber();
3743 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
3744 + seq + " event=" + event);
3745 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
3751 // Not dispatching to IME, continue with post IME actions.
3752 deliverKeyEventPostIme(q);
3755 void handleImeFinishedEvent(int seq, boolean handled) {
3756 final QueuedInputEvent q = mCurrentInputEvent;
3757 if (q != null && q.mEvent.getSequenceNumber() == seq) {
3759 Log.v(TAG, "IME finished event: seq=" + seq
3760 + " handled=" + handled + " event=" + q);
3763 finishInputEvent(q, true);
3765 if (q.mEvent instanceof KeyEvent) {
3766 KeyEvent event = (KeyEvent)q.mEvent;
3767 if (event.getAction() != KeyEvent.ACTION_UP) {
3768 // If the window doesn't currently have input focus, then drop
3769 // this event. This could be an event that came back from the
3770 // IME dispatch but the window has lost focus in the meantime.
3771 if (!mAttachInfo.mHasWindowFocus) {
3772 Slog.w(TAG, "Dropping event due to no window focus: " + event);
3773 finishInputEvent(q, true);
3777 deliverKeyEventPostIme(q);
3779 MotionEvent event = (MotionEvent)q.mEvent;
3780 if (event.getAction() != MotionEvent.ACTION_CANCEL
3781 && event.getAction() != MotionEvent.ACTION_UP) {
3782 // If the window doesn't currently have input focus, then drop
3783 // this event. This could be an event that came back from the
3784 // IME dispatch but the window has lost focus in the meantime.
3785 if (!mAttachInfo.mHasWindowFocus) {
3786 Slog.w(TAG, "Dropping event due to no window focus: " + event);
3787 finishInputEvent(q, true);
3791 final int source = q.mEvent.getSource();
3792 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
3793 deliverTrackballEventPostIme(q);
3795 deliverGenericMotionEventPostIme(q);
3801 Log.v(TAG, "IME finished event: seq=" + seq
3802 + " handled=" + handled + ", event not found!");
3807 private void deliverKeyEventPostIme(QueuedInputEvent q) {
3808 final KeyEvent event = (KeyEvent)q.mEvent;
3810 // If the view went away, then the event will not be handled.
3811 if (mView == null || !mAdded) {
3812 finishInputEvent(q, false);
3816 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
3817 if (checkForLeavingTouchModeAndConsume(event)) {
3818 finishInputEvent(q, true);
3822 // Make sure the fallback event policy sees all keys that will be delivered to the
3824 mFallbackEventHandler.preDispatchKeyEvent(event);
3826 // Deliver the key to the view hierarchy.
3827 if (mView.dispatchKeyEvent(event)) {
3828 finishInputEvent(q, true);
3832 // If the Control modifier is held, try to interpret the key as a shortcut.
3833 if (event.getAction() == KeyEvent.ACTION_DOWN
3834 && event.isCtrlPressed()
3835 && event.getRepeatCount() == 0
3836 && !KeyEvent.isModifierKey(event.getKeyCode())) {
3837 if (mView.dispatchKeyShortcutEvent(event)) {
3838 finishInputEvent(q, true);
3843 // Apply the fallback event policy.
3844 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3845 finishInputEvent(q, true);
3849 // Handle automatic focus changes.
3850 if (event.getAction() == KeyEvent.ACTION_DOWN) {
3852 switch (event.getKeyCode()) {
3853 case KeyEvent.KEYCODE_DPAD_LEFT:
3854 if (event.hasNoModifiers()) {
3855 direction = View.FOCUS_LEFT;
3858 case KeyEvent.KEYCODE_DPAD_RIGHT:
3859 if (event.hasNoModifiers()) {
3860 direction = View.FOCUS_RIGHT;
3863 case KeyEvent.KEYCODE_DPAD_UP:
3864 if (event.hasNoModifiers()) {
3865 direction = View.FOCUS_UP;
3868 case KeyEvent.KEYCODE_DPAD_DOWN:
3869 if (event.hasNoModifiers()) {
3870 direction = View.FOCUS_DOWN;
3873 case KeyEvent.KEYCODE_TAB:
3874 if (event.hasNoModifiers()) {
3875 direction = View.FOCUS_FORWARD;
3876 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3877 direction = View.FOCUS_BACKWARD;
3881 if (direction != 0) {
3882 View focused = mView.findFocus();
3883 if (focused != null) {
3884 View v = focused.focusSearch(direction);
3885 if (v != null && v != focused) {
3886 // do the math the get the interesting rect
3887 // of previous focused into the coord system of
3888 // newly focused view
3889 focused.getFocusedRect(mTempRect);
3890 if (mView instanceof ViewGroup) {
3891 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3892 focused, mTempRect);
3893 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3896 if (v.requestFocus(direction, mTempRect)) {
3897 playSoundEffect(SoundEffectConstants
3898 .getContantForFocusDirection(direction));
3899 finishInputEvent(q, true);
3904 // Give the focused view a last chance to handle the dpad key.
3905 if (mView.dispatchUnhandledMove(focused, direction)) {
3906 finishInputEvent(q, true);
3913 // Key was unhandled.
3914 finishInputEvent(q, false);
3918 void setLocalDragState(Object obj) {
3919 mLocalDragState = obj;
3922 private void handleDragEvent(DragEvent event) {
3923 // From the root, only drag start/end/location are dispatched. entered/exited
3924 // are determined and dispatched by the viewgroup hierarchy, who then report
3925 // that back here for ultimate reporting back to the framework.
3926 if (mView != null && mAdded) {
3927 final int what = event.mAction;
3929 if (what == DragEvent.ACTION_DRAG_EXITED) {
3930 // A direct EXITED event means that the window manager knows we've just crossed
3931 // a window boundary, so the current drag target within this one must have
3932 // just been exited. Send it the usual notifications and then we're done
3934 mView.dispatchDragEvent(event);
3936 // Cache the drag description when the operation starts, then fill it in
3937 // on subsequent calls as a convenience
3938 if (what == DragEvent.ACTION_DRAG_STARTED) {
3939 mCurrentDragView = null; // Start the current-recipient tracking
3940 mDragDescription = event.mClipDescription;
3942 event.mClipDescription = mDragDescription;
3945 // For events with a [screen] location, translate into window coordinates
3946 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3947 mDragPoint.set(event.mX, event.mY);
3948 if (mTranslator != null) {
3949 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3952 if (mCurScrollY != 0) {
3953 mDragPoint.offset(0, mCurScrollY);
3956 event.mX = mDragPoint.x;
3957 event.mY = mDragPoint.y;
3960 // Remember who the current drag target is pre-dispatch
3961 final View prevDragView = mCurrentDragView;
3963 // Now dispatch the drag/drop event
3964 boolean result = mView.dispatchDragEvent(event);
3966 // If we changed apparent drag target, tell the OS about it
3967 if (prevDragView != mCurrentDragView) {
3969 if (prevDragView != null) {
3970 mWindowSession.dragRecipientExited(mWindow);
3972 if (mCurrentDragView != null) {
3973 mWindowSession.dragRecipientEntered(mWindow);
3975 } catch (RemoteException e) {
3976 Slog.e(TAG, "Unable to note drag target change");
3980 // Report the drop result when we're done
3981 if (what == DragEvent.ACTION_DROP) {
3982 mDragDescription = null;
3984 Log.i(TAG, "Reporting drop result: " + result);
3985 mWindowSession.reportDropResult(mWindow, result);
3986 } catch (RemoteException e) {
3987 Log.e(TAG, "Unable to report drop result");
3991 // When the drag operation ends, release any local state object
3992 // that may have been in use
3993 if (what == DragEvent.ACTION_DRAG_ENDED) {
3994 setLocalDragState(null);
4001 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
4002 if (mSeq != args.seq) {
4003 // The sequence has changed, so we need to update our value and make
4004 // sure to do a traversal afterward so the window manager is given our
4005 // most recent data.
4007 mAttachInfo.mForceReportNewAttributes = true;
4008 scheduleTraversals();
4010 if (mView == null) return;
4011 if (args.localChanges != 0) {
4012 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
4014 if (mAttachInfo != null) {
4015 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
4016 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
4017 mAttachInfo.mGlobalSystemUiVisibility = visibility;
4018 mView.dispatchSystemUiVisibilityChanged(visibility);
4023 public void handleDispatchDoneAnimating() {
4024 if (mWindowsAnimating) {
4025 mWindowsAnimating = false;
4026 if (!mDirty.isEmpty() || mIsAnimating) {
4027 scheduleTraversals();
4032 public void getLastTouchPoint(Point outLocation) {
4033 outLocation.x = (int) mLastTouchPoint.x;
4034 outLocation.y = (int) mLastTouchPoint.y;
4037 public void setDragFocus(View newDragTarget) {
4038 if (mCurrentDragView != newDragTarget) {
4039 mCurrentDragView = newDragTarget;
4043 private AudioManager getAudioManager() {
4044 if (mView == null) {
4045 throw new IllegalStateException("getAudioManager called when there is no mView");
4047 if (mAudioManager == null) {
4048 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
4050 return mAudioManager;
4053 public AccessibilityInteractionController getAccessibilityInteractionController() {
4054 if (mView == null) {
4055 throw new IllegalStateException("getAccessibilityInteractionController"
4056 + " called when there is no mView");
4058 if (mAccessibilityInteractionController == null) {
4059 mAccessibilityInteractionController = new AccessibilityInteractionController(this);
4061 return mAccessibilityInteractionController;
4064 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
4065 boolean insetsPending) throws RemoteException {
4067 float appScale = mAttachInfo.mApplicationScale;
4068 boolean restore = false;
4069 if (params != null && mTranslator != null) {
4072 mTranslator.translateWindowLayout(params);
4074 if (params != null) {
4075 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
4077 mPendingConfiguration.seq = 0;
4078 //Log.d(TAG, ">>>>>> CALLING relayout");
4079 if (params != null && mOrigWindowType != params.type) {
4080 // For compatibility with old apps, don't crash here.
4081 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4082 Slog.w(TAG, "Window type can not be changed after "
4083 + "the window is added; ignoring change of " + mView);
4084 params.type = mOrigWindowType;
4087 int relayoutResult = mWindowSession.relayout(
4088 mWindow, mSeq, params,
4089 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
4090 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
4091 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
4092 mWinFrame, mPendingContentInsets, mPendingVisibleInsets,
4093 mPendingConfiguration, mSurface);
4094 //Log.d(TAG, "<<<<<< BACK FROM relayout");
4099 if (mTranslator != null) {
4100 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
4101 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
4102 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
4104 return relayoutResult;
4110 public void playSoundEffect(int effectId) {
4114 final AudioManager audioManager = getAudioManager();
4117 case SoundEffectConstants.CLICK:
4118 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
4120 case SoundEffectConstants.NAVIGATION_DOWN:
4121 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
4123 case SoundEffectConstants.NAVIGATION_LEFT:
4124 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
4126 case SoundEffectConstants.NAVIGATION_RIGHT:
4127 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
4129 case SoundEffectConstants.NAVIGATION_UP:
4130 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
4133 throw new IllegalArgumentException("unknown effect id " + effectId +
4134 " not defined in " + SoundEffectConstants.class.getCanonicalName());
4136 } catch (IllegalStateException e) {
4137 // Exception thrown by getAudioManager() when mView is null
4138 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
4139 e.printStackTrace();
4146 public boolean performHapticFeedback(int effectId, boolean always) {
4148 return mWindowSession.performHapticFeedback(mWindow, effectId, always);
4149 } catch (RemoteException e) {
4157 public View focusSearch(View focused, int direction) {
4159 if (!(mView instanceof ViewGroup)) {
4162 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
4165 public void debug() {
4169 public void dumpGfxInfo(int[] info) {
4170 info[0] = info[1] = 0;
4171 if (mView != null) {
4172 getGfxInfo(mView, info);
4176 private static void getGfxInfo(View view, int[] info) {
4177 DisplayList displayList = view.mDisplayList;
4179 if (displayList != null) {
4180 info[1] += displayList.getSize();
4183 if (view instanceof ViewGroup) {
4184 ViewGroup group = (ViewGroup) view;
4186 int count = group.getChildCount();
4187 for (int i = 0; i < count; i++) {
4188 getGfxInfo(group.getChildAt(i), info);
4193 public void die(boolean immediate) {
4194 // Make sure we do execute immediately if we are in the middle of a traversal or the damage
4195 // done by dispatchDetachedFromWindow will cause havoc on return.
4196 if (immediate && !mIsInTraversal) {
4200 destroyHardwareRenderer();
4202 Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
4203 " window=" + this + ", title=" + mWindowAttributes.getTitle());
4205 mHandler.sendEmptyMessage(MSG_DIE);
4211 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
4212 synchronized (this) {
4214 dispatchDetachedFromWindow();
4217 if (mAdded && !mFirst) {
4218 invalidateDisplayLists();
4219 destroyHardwareRenderer();
4221 if (mView != null) {
4222 int viewVisibility = mView.getVisibility();
4223 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
4224 if (mWindowAttributesChanged || viewVisibilityChanged) {
4225 // If layout params have been changed, first give them
4226 // to the window manager to make sure it has the correct
4229 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
4230 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
4231 mWindowSession.finishDrawing(mWindow);
4233 } catch (RemoteException e) {
4245 public void requestUpdateConfiguration(Configuration config) {
4246 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
4247 mHandler.sendMessage(msg);
4250 public void loadSystemProperties() {
4251 mHandler.post(new Runnable() {
4255 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
4256 profileRendering(mAttachInfo.mHasWindowFocus);
4258 // Hardware rendering
4259 if (mAttachInfo.mHardwareRenderer != null) {
4260 if (mAttachInfo.mHardwareRenderer.loadSystemProperties(mHolder.getSurface())) {
4266 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
4267 if (layout != mAttachInfo.mDebugLayout) {
4268 mAttachInfo.mDebugLayout = layout;
4269 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
4270 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
4277 private void destroyHardwareRenderer() {
4278 AttachInfo attachInfo = mAttachInfo;
4279 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer;
4281 if (hardwareRenderer != null) {
4282 if (mView != null) {
4283 hardwareRenderer.destroyHardwareResources(mView);
4285 hardwareRenderer.destroy(true);
4286 hardwareRenderer.setRequested(false);
4288 attachInfo.mHardwareRenderer = null;
4289 attachInfo.mHardwareAccelerated = false;
4293 void dispatchImeFinishedEvent(int seq, boolean handled) {
4294 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT);
4296 msg.arg2 = handled ? 1 : 0;
4297 msg.setAsynchronous(true);
4298 mHandler.sendMessage(msg);
4301 public void dispatchFinishInputConnection(InputConnection connection) {
4302 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
4303 mHandler.sendMessage(msg);
4306 public void dispatchResized(Rect frame, Rect contentInsets,
4307 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4308 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString()
4309 + " contentInsets=" + contentInsets.toShortString()
4310 + " visibleInsets=" + visibleInsets.toShortString()
4311 + " reportDraw=" + reportDraw);
4312 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
4313 if (mTranslator != null) {
4314 mTranslator.translateRectInScreenToAppWindow(frame);
4315 mTranslator.translateRectInScreenToAppWindow(contentInsets);
4316 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
4318 SomeArgs args = SomeArgs.obtain();
4319 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
4320 args.arg1 = sameProcessCall ? new Rect(frame) : frame;
4321 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
4322 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
4323 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
4325 mHandler.sendMessage(msg);
4328 public void dispatchMoved(int newX, int newY) {
4329 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
4330 if (mTranslator != null) {
4331 PointF point = new PointF(newX, newY);
4332 mTranslator.translatePointInScreenToAppWindow(point);
4333 newX = (int) (point.x + 0.5);
4334 newY = (int) (point.y + 0.5);
4336 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
4337 mHandler.sendMessage(msg);
4341 * Represents a pending input event that is waiting in a queue.
4343 * Input events are processed in serial order by the timestamp specified by
4344 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers
4345 * one input event to the application at a time and waits for the application
4346 * to finish handling it before delivering the next one.
4348 * However, because the application or IME can synthesize and inject multiple
4349 * key events at a time without going through the input dispatcher, we end up
4350 * needing a queue on the application's side.
4352 private static final class QueuedInputEvent {
4353 public static final int FLAG_DELIVER_POST_IME = 1;
4355 public QueuedInputEvent mNext;
4357 public InputEvent mEvent;
4358 public InputEventReceiver mReceiver;
4362 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
4363 InputEventReceiver receiver, int flags) {
4364 QueuedInputEvent q = mQueuedInputEventPool;
4366 mQueuedInputEventPoolSize -= 1;
4367 mQueuedInputEventPool = q.mNext;
4370 q = new QueuedInputEvent();
4374 q.mReceiver = receiver;
4379 private void recycleQueuedInputEvent(QueuedInputEvent q) {
4383 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
4384 mQueuedInputEventPoolSize += 1;
4385 q.mNext = mQueuedInputEventPool;
4386 mQueuedInputEventPool = q;
4390 void enqueueInputEvent(InputEvent event) {
4391 enqueueInputEvent(event, null, 0, false);
4394 void enqueueInputEvent(InputEvent event,
4395 InputEventReceiver receiver, int flags, boolean processImmediately) {
4396 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
4398 // Always enqueue the input event in order, regardless of its time stamp.
4399 // We do this because the application or the IME may inject key events
4400 // in response to touch events and we want to ensure that the injected keys
4401 // are processed in the order they were received and we cannot trust that
4402 // the time stamp of injected events are monotonic.
4403 QueuedInputEvent last = mFirstPendingInputEvent;
4405 mFirstPendingInputEvent = q;
4407 while (last.mNext != null) {
4413 if (processImmediately) {
4414 doProcessInputEvents();
4416 scheduleProcessInputEvents();
4420 private void scheduleProcessInputEvents() {
4421 if (!mProcessInputEventsScheduled) {
4422 mProcessInputEventsScheduled = true;
4423 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
4424 msg.setAsynchronous(true);
4425 mHandler.sendMessage(msg);
4429 void doProcessInputEvents() {
4430 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) {
4431 QueuedInputEvent q = mFirstPendingInputEvent;
4432 mFirstPendingInputEvent = q.mNext;
4434 mCurrentInputEvent = q;
4435 deliverInputEvent(q);
4438 // We are done processing all input events that we can process right now
4439 // so we can clear the pending flag immediately.
4440 if (mProcessInputEventsScheduled) {
4441 mProcessInputEventsScheduled = false;
4442 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
4446 private void finishInputEvent(QueuedInputEvent q, boolean handled) {
4447 if (q != mCurrentInputEvent) {
4448 throw new IllegalStateException("finished input event out of order");
4451 if (q.mReceiver != null) {
4452 q.mReceiver.finishInputEvent(q.mEvent, handled);
4454 q.mEvent.recycleIfNeededAfterDispatch();
4457 recycleQueuedInputEvent(q);
4459 mCurrentInputEvent = null;
4460 if (mFirstPendingInputEvent != null) {
4461 scheduleProcessInputEvents();
4465 void scheduleConsumeBatchedInput() {
4466 if (!mConsumeBatchedInputScheduled) {
4467 mConsumeBatchedInputScheduled = true;
4468 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
4469 mConsumedBatchedInputRunnable, null);
4473 void unscheduleConsumeBatchedInput() {
4474 if (mConsumeBatchedInputScheduled) {
4475 mConsumeBatchedInputScheduled = false;
4476 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
4477 mConsumedBatchedInputRunnable, null);
4481 void doConsumeBatchedInput(long frameTimeNanos) {
4482 if (mConsumeBatchedInputScheduled) {
4483 mConsumeBatchedInputScheduled = false;
4484 if (mInputEventReceiver != null) {
4485 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos);
4487 doProcessInputEvents();
4491 final class TraversalRunnable implements Runnable {
4497 final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
4499 final class WindowInputEventReceiver extends InputEventReceiver {
4500 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
4501 super(inputChannel, looper);
4505 public void onInputEvent(InputEvent event) {
4506 enqueueInputEvent(event, this, 0, true);
4510 public void onBatchedInputEventPending() {
4511 scheduleConsumeBatchedInput();
4515 public void dispose() {
4516 unscheduleConsumeBatchedInput();
4520 WindowInputEventReceiver mInputEventReceiver;
4522 final class ConsumeBatchedInputRunnable implements Runnable {
4525 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
4528 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
4529 new ConsumeBatchedInputRunnable();
4530 boolean mConsumeBatchedInputScheduled;
4532 final class InvalidateOnAnimationRunnable implements Runnable {
4533 private boolean mPosted;
4534 private ArrayList<View> mViews = new ArrayList<View>();
4535 private ArrayList<AttachInfo.InvalidateInfo> mViewRects =
4536 new ArrayList<AttachInfo.InvalidateInfo>();
4537 private View[] mTempViews;
4538 private AttachInfo.InvalidateInfo[] mTempViewRects;
4540 public void addView(View view) {
4541 synchronized (this) {
4543 postIfNeededLocked();
4547 public void addViewRect(AttachInfo.InvalidateInfo info) {
4548 synchronized (this) {
4549 mViewRects.add(info);
4550 postIfNeededLocked();
4554 public void removeView(View view) {
4555 synchronized (this) {
4556 mViews.remove(view);
4558 for (int i = mViewRects.size(); i-- > 0; ) {
4559 AttachInfo.InvalidateInfo info = mViewRects.get(i);
4560 if (info.target == view) {
4561 mViewRects.remove(i);
4566 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
4567 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
4575 final int viewCount;
4576 final int viewRectCount;
4577 synchronized (this) {
4580 viewCount = mViews.size();
4581 if (viewCount != 0) {
4582 mTempViews = mViews.toArray(mTempViews != null
4583 ? mTempViews : new View[viewCount]);
4587 viewRectCount = mViewRects.size();
4588 if (viewRectCount != 0) {
4589 mTempViewRects = mViewRects.toArray(mTempViewRects != null
4590 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
4595 for (int i = 0; i < viewCount; i++) {
4596 mTempViews[i].invalidate();
4597 mTempViews[i] = null;
4600 for (int i = 0; i < viewRectCount; i++) {
4601 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
4602 info.target.invalidate(info.left, info.top, info.right, info.bottom);
4607 private void postIfNeededLocked() {
4609 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
4614 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
4615 new InvalidateOnAnimationRunnable();
4617 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
4618 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
4619 mHandler.sendMessageDelayed(msg, delayMilliseconds);
4622 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
4623 long delayMilliseconds) {
4624 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
4625 mHandler.sendMessageDelayed(msg, delayMilliseconds);
4628 public void dispatchInvalidateOnAnimation(View view) {
4629 mInvalidateOnAnimationRunnable.addView(view);
4632 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
4633 mInvalidateOnAnimationRunnable.addViewRect(info);
4636 public void enqueueDisplayList(DisplayList displayList) {
4637 mDisplayLists.add(displayList);
4640 public void cancelInvalidate(View view) {
4641 mHandler.removeMessages(MSG_INVALIDATE, view);
4642 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
4644 mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
4645 mInvalidateOnAnimationRunnable.removeView(view);
4648 public void dispatchKey(KeyEvent event) {
4649 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event);
4650 msg.setAsynchronous(true);
4651 mHandler.sendMessage(msg);
4654 public void dispatchKeyFromIme(KeyEvent event) {
4655 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
4656 msg.setAsynchronous(true);
4657 mHandler.sendMessage(msg);
4660 public void dispatchUnhandledKey(KeyEvent event) {
4661 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4662 final KeyCharacterMap kcm = event.getKeyCharacterMap();
4663 final int keyCode = event.getKeyCode();
4664 final int metaState = event.getMetaState();
4666 // Check for fallback actions specified by the key character map.
4667 KeyCharacterMap.FallbackAction fallbackAction =
4668 kcm.getFallbackAction(keyCode, metaState);
4669 if (fallbackAction != null) {
4670 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
4671 KeyEvent fallbackEvent = KeyEvent.obtain(
4672 event.getDownTime(), event.getEventTime(),
4673 event.getAction(), fallbackAction.keyCode,
4674 event.getRepeatCount(), fallbackAction.metaState,
4675 event.getDeviceId(), event.getScanCode(),
4676 flags, event.getSource(), null);
4677 fallbackAction.recycle();
4679 dispatchKey(fallbackEvent);
4684 public void dispatchAppVisibility(boolean visible) {
4685 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
4686 msg.arg1 = visible ? 1 : 0;
4687 mHandler.sendMessage(msg);
4690 public void dispatchScreenStateChange(boolean on) {
4691 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE);
4692 msg.arg1 = on ? 1 : 0;
4693 mHandler.sendMessage(msg);
4696 public void dispatchGetNewSurface() {
4697 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
4698 mHandler.sendMessage(msg);
4701 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
4702 Message msg = Message.obtain();
4703 msg.what = MSG_WINDOW_FOCUS_CHANGED;
4704 msg.arg1 = hasFocus ? 1 : 0;
4705 msg.arg2 = inTouchMode ? 1 : 0;
4706 mHandler.sendMessage(msg);
4709 public void dispatchCloseSystemDialogs(String reason) {
4710 Message msg = Message.obtain();
4711 msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
4713 mHandler.sendMessage(msg);
4716 public void dispatchDragEvent(DragEvent event) {
4718 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
4719 what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
4720 mHandler.removeMessages(what);
4722 what = MSG_DISPATCH_DRAG_EVENT;
4724 Message msg = mHandler.obtainMessage(what, event);
4725 mHandler.sendMessage(msg);
4728 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
4729 int localValue, int localChanges) {
4730 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
4732 args.globalVisibility = globalVisibility;
4733 args.localValue = localValue;
4734 args.localChanges = localChanges;
4735 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
4738 public void dispatchDoneAnimating() {
4739 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING);
4742 public void dispatchCheckFocus() {
4743 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
4744 // This will result in a call to checkFocus() below.
4745 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
4750 * Post a callback to send a
4751 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4752 * This event is send at most once every
4753 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
4755 private void postSendWindowContentChangedCallback(View source) {
4756 if (mSendWindowContentChangedAccessibilityEvent == null) {
4757 mSendWindowContentChangedAccessibilityEvent =
4758 new SendWindowContentChangedAccessibilityEvent();
4760 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource;
4761 if (oldSource == null) {
4762 mSendWindowContentChangedAccessibilityEvent.mSource = source;
4763 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent,
4764 ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
4766 mSendWindowContentChangedAccessibilityEvent.mSource =
4767 getCommonPredecessor(oldSource, source);
4772 * Remove a posted callback to send a
4773 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
4775 private void removeSendWindowContentChangedCallback() {
4776 if (mSendWindowContentChangedAccessibilityEvent != null) {
4777 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
4781 public boolean showContextMenuForChild(View originalView) {
4785 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
4789 public void createContextMenu(ContextMenu menu) {
4792 public void childDrawableStateChanged(View child) {
4795 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
4796 if (mView == null) {
4799 // Intercept accessibility focus events fired by virtual nodes to keep
4800 // track of accessibility focus position in such nodes.
4801 final int eventType = event.getEventType();
4802 switch (eventType) {
4803 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4804 final long sourceNodeId = event.getSourceNodeId();
4805 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4807 View source = mView.findViewByAccessibilityId(accessibilityViewId);
4808 if (source != null) {
4809 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4810 if (provider != null) {
4811 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(
4812 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId));
4813 setAccessibilityFocus(source, node);
4817 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4818 final long sourceNodeId = event.getSourceNodeId();
4819 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
4821 View source = mView.findViewByAccessibilityId(accessibilityViewId);
4822 if (source != null) {
4823 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
4824 if (provider != null) {
4825 setAccessibilityFocus(null, null);
4830 mAccessibilityManager.sendAccessibilityEvent(event);
4835 public void childAccessibilityStateChanged(View child) {
4836 postSendWindowContentChangedCallback(child);
4839 private View getCommonPredecessor(View first, View second) {
4840 if (mAttachInfo != null) {
4841 if (mTempHashSet == null) {
4842 mTempHashSet = new HashSet<View>();
4844 HashSet<View> seen = mTempHashSet;
4846 View firstCurrent = first;
4847 while (firstCurrent != null) {
4848 seen.add(firstCurrent);
4849 ViewParent firstCurrentParent = firstCurrent.mParent;
4850 if (firstCurrentParent instanceof View) {
4851 firstCurrent = (View) firstCurrentParent;
4853 firstCurrent = null;
4856 View secondCurrent = second;
4857 while (secondCurrent != null) {
4858 if (seen.contains(secondCurrent)) {
4860 return secondCurrent;
4862 ViewParent secondCurrentParent = secondCurrent.mParent;
4863 if (secondCurrentParent instanceof View) {
4864 secondCurrent = (View) secondCurrentParent;
4866 secondCurrent = null;
4874 void checkThread() {
4875 if (mThread != Thread.currentThread()) {
4876 throw new CalledFromWrongThreadException(
4877 "Only the original thread that created a view hierarchy can touch its views.");
4881 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
4882 // ViewAncestor never intercepts touch event, so this can be a no-op
4885 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
4886 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
4887 if (rectangle != null) {
4888 mTempRect.set(rectangle);
4889 mTempRect.offset(0, -mCurScrollY);
4890 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4892 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate);
4893 } catch (RemoteException re) {
4900 public void childHasTransientStateChanged(View child, boolean hasTransientState) {
4904 class TakenSurfaceHolder extends BaseSurfaceHolder {
4906 public boolean onAllowLockCanvas() {
4907 return mDrawingAllowed;
4911 public void onRelayoutContainer() {
4912 // Not currently interesting -- from changing between fixed and layout size.
4915 public void setFormat(int format) {
4916 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
4919 public void setType(int type) {
4920 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
4924 public void onUpdateSurface() {
4925 // We take care of format and type changes on our own.
4926 throw new IllegalStateException("Shouldn't be here");
4929 public boolean isCreating() {
4934 public void setFixedSize(int width, int height) {
4935 throw new UnsupportedOperationException(
4936 "Currently only support sizing from layout");
4939 public void setKeepScreenOn(boolean screenOn) {
4940 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
4944 static final class InputMethodCallback implements InputMethodManager.FinishedEventCallback {
4945 private WeakReference<ViewRootImpl> mViewAncestor;
4947 public InputMethodCallback(ViewRootImpl viewAncestor) {
4948 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4952 public void finishedEvent(int seq, boolean handled) {
4953 final ViewRootImpl viewAncestor = mViewAncestor.get();
4954 if (viewAncestor != null) {
4955 viewAncestor.dispatchImeFinishedEvent(seq, handled);
4960 static class W extends IWindow.Stub {
4961 private final WeakReference<ViewRootImpl> mViewAncestor;
4962 private final IWindowSession mWindowSession;
4964 W(ViewRootImpl viewAncestor) {
4965 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
4966 mWindowSession = viewAncestor.mWindowSession;
4969 public void resized(Rect frame, Rect contentInsets,
4970 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
4971 final ViewRootImpl viewAncestor = mViewAncestor.get();
4972 if (viewAncestor != null) {
4973 viewAncestor.dispatchResized(frame, contentInsets,
4974 visibleInsets, reportDraw, newConfig);
4979 public void moved(int newX, int newY) {
4980 final ViewRootImpl viewAncestor = mViewAncestor.get();
4981 if (viewAncestor != null) {
4982 viewAncestor.dispatchMoved(newX, newY);
4986 public void dispatchAppVisibility(boolean visible) {
4987 final ViewRootImpl viewAncestor = mViewAncestor.get();
4988 if (viewAncestor != null) {
4989 viewAncestor.dispatchAppVisibility(visible);
4993 public void dispatchScreenState(boolean on) {
4994 final ViewRootImpl viewAncestor = mViewAncestor.get();
4995 if (viewAncestor != null) {
4996 viewAncestor.dispatchScreenStateChange(on);
5000 public void dispatchGetNewSurface() {
5001 final ViewRootImpl viewAncestor = mViewAncestor.get();
5002 if (viewAncestor != null) {
5003 viewAncestor.dispatchGetNewSurface();
5007 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
5008 final ViewRootImpl viewAncestor = mViewAncestor.get();
5009 if (viewAncestor != null) {
5010 viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
5014 private static int checkCallingPermission(String permission) {
5016 return ActivityManagerNative.getDefault().checkPermission(
5017 permission, Binder.getCallingPid(), Binder.getCallingUid());
5018 } catch (RemoteException e) {
5019 return PackageManager.PERMISSION_DENIED;
5023 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
5024 final ViewRootImpl viewAncestor = mViewAncestor.get();
5025 if (viewAncestor != null) {
5026 final View view = viewAncestor.mView;
5028 if (checkCallingPermission(Manifest.permission.DUMP) !=
5029 PackageManager.PERMISSION_GRANTED) {
5030 throw new SecurityException("Insufficient permissions to invoke"
5031 + " executeCommand() from pid=" + Binder.getCallingPid()
5032 + ", uid=" + Binder.getCallingUid());
5035 OutputStream clientStream = null;
5037 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
5038 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
5039 } catch (IOException e) {
5040 e.printStackTrace();
5042 if (clientStream != null) {
5044 clientStream.close();
5045 } catch (IOException e) {
5046 e.printStackTrace();
5054 public void closeSystemDialogs(String reason) {
5055 final ViewRootImpl viewAncestor = mViewAncestor.get();
5056 if (viewAncestor != null) {
5057 viewAncestor.dispatchCloseSystemDialogs(reason);
5061 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
5065 mWindowSession.wallpaperOffsetsComplete(asBinder());
5066 } catch (RemoteException e) {
5071 public void dispatchWallpaperCommand(String action, int x, int y,
5072 int z, Bundle extras, boolean sync) {
5075 mWindowSession.wallpaperCommandComplete(asBinder(), null);
5076 } catch (RemoteException e) {
5082 public void dispatchDragEvent(DragEvent event) {
5083 final ViewRootImpl viewAncestor = mViewAncestor.get();
5084 if (viewAncestor != null) {
5085 viewAncestor.dispatchDragEvent(event);
5089 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
5090 int localValue, int localChanges) {
5091 final ViewRootImpl viewAncestor = mViewAncestor.get();
5092 if (viewAncestor != null) {
5093 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
5094 localValue, localChanges);
5098 public void doneAnimating() {
5099 final ViewRootImpl viewAncestor = mViewAncestor.get();
5100 if (viewAncestor != null) {
5101 viewAncestor.dispatchDoneAnimating();
5107 * Maintains state information for a single trackball axis, generating
5108 * discrete (DPAD) movements based on raw trackball motion.
5110 static final class TrackballAxis {
5112 * The maximum amount of acceleration we will apply.
5114 static final float MAX_ACCELERATION = 20;
5117 * The maximum amount of time (in milliseconds) between events in order
5118 * for us to consider the user to be doing fast trackball movements,
5119 * and thus apply an acceleration.
5121 static final long FAST_MOVE_TIME = 150;
5124 * Scaling factor to the time (in milliseconds) between events to how
5125 * much to multiple/divide the current acceleration. When movement
5126 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
5127 * FAST_MOVE_TIME it divides it.
5129 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
5133 float acceleration = 1;
5134 long lastMoveTime = 0;
5137 int nonAccelMovement;
5139 void reset(int _step) {
5148 * Add trackball movement into the state. If the direction of movement
5149 * has been reversed, the state is reset before adding the
5150 * movement (so that you don't have to compensate for any previously
5151 * collected movement before see the result of the movement in the
5154 * @return Returns the absolute value of the amount of movement
5157 float collect(float off, long time, String axis) {
5160 normTime = (long)(off * FAST_MOVE_TIME);
5162 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
5169 } else if (off < 0) {
5170 normTime = (long)((-off) * FAST_MOVE_TIME);
5172 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
5183 // The number of milliseconds between each movement that is
5184 // considered "normal" and will not result in any acceleration
5185 // or deceleration, scaled by the offset we have here.
5187 long delta = time - lastMoveTime;
5188 lastMoveTime = time;
5189 float acc = acceleration;
5190 if (delta < normTime) {
5191 // The user is scrolling rapidly, so increase acceleration.
5192 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
5193 if (scale > 1) acc *= scale;
5194 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
5195 + off + " normTime=" + normTime + " delta=" + delta
5196 + " scale=" + scale + " acc=" + acc);
5197 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
5199 // The user is scrolling slowly, so decrease acceleration.
5200 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
5201 if (scale > 1) acc /= scale;
5202 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
5203 + off + " normTime=" + normTime + " delta=" + delta
5204 + " scale=" + scale + " acc=" + acc);
5205 acceleration = acc > 1 ? acc : 1;
5209 return (absPosition = Math.abs(position));
5213 * Generate the number of discrete movement events appropriate for
5214 * the currently collected trackball movement.
5216 * @param precision The minimum movement required to generate the
5217 * first discrete movement.
5219 * @return Returns the number of discrete movements, either positive
5220 * or negative, or 0 if there is not enough trackball movement yet
5221 * for a discrete movement.
5223 int generate(float precision) {
5225 nonAccelMovement = 0;
5227 final int dir = position >= 0 ? 1 : -1;
5229 // If we are going to execute the first step, then we want
5230 // to do this as soon as possible instead of waiting for
5231 // a full movement, in order to make things look responsive.
5233 if (absPosition < precision) {
5237 nonAccelMovement += dir;
5240 // If we have generated the first movement, then we need
5241 // to wait for the second complete trackball motion before
5242 // generating the second discrete movement.
5244 if (absPosition < 2) {
5248 nonAccelMovement += dir;
5249 position += dir > 0 ? -2 : 2;
5250 absPosition = Math.abs(position);
5253 // After the first two, we generate discrete movements
5254 // consistently with the trackball, applying an acceleration
5255 // if the trackball is moving quickly. This is a simple
5256 // acceleration on top of what we already compute based
5257 // on how quickly the wheel is being turned, to apply
5258 // a longer increasing acceleration to continuous movement
5259 // in one direction.
5261 if (absPosition < 1) {
5265 position += dir >= 0 ? -1 : 1;
5266 absPosition = Math.abs(position);
5267 float acc = acceleration;
5269 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
5276 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
5277 public CalledFromWrongThreadException(String msg) {
5282 private SurfaceHolder mHolder = new SurfaceHolder() {
5283 // we only need a SurfaceHolder for opengl. it would be nice
5284 // to implement everything else though, especially the callback
5285 // support (opengl doesn't make use of it right now, but eventually
5287 public Surface getSurface() {
5291 public boolean isCreating() {
5295 public void addCallback(Callback callback) {
5298 public void removeCallback(Callback callback) {
5301 public void setFixedSize(int width, int height) {
5304 public void setSizeFromLayout() {
5307 public void setFormat(int format) {
5310 public void setType(int type) {
5313 public void setKeepScreenOn(boolean screenOn) {
5316 public Canvas lockCanvas() {
5320 public Canvas lockCanvas(Rect dirty) {
5324 public void unlockCanvasAndPost(Canvas canvas) {
5326 public Rect getSurfaceFrame() {
5331 static RunQueue getRunQueue() {
5332 RunQueue rq = sRunQueues.get();
5336 rq = new RunQueue();
5342 * The run queue is used to enqueue pending work from Views when no Handler is
5343 * attached. The work is executed during the next call to performTraversals on
5347 static final class RunQueue {
5348 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
5350 void post(Runnable action) {
5351 postDelayed(action, 0);
5354 void postDelayed(Runnable action, long delayMillis) {
5355 HandlerAction handlerAction = new HandlerAction();
5356 handlerAction.action = action;
5357 handlerAction.delay = delayMillis;
5359 synchronized (mActions) {
5360 mActions.add(handlerAction);
5364 void removeCallbacks(Runnable action) {
5365 final HandlerAction handlerAction = new HandlerAction();
5366 handlerAction.action = action;
5368 synchronized (mActions) {
5369 final ArrayList<HandlerAction> actions = mActions;
5371 while (actions.remove(handlerAction)) {
5377 void executeActions(Handler handler) {
5378 synchronized (mActions) {
5379 final ArrayList<HandlerAction> actions = mActions;
5380 final int count = actions.size();
5382 for (int i = 0; i < count; i++) {
5383 final HandlerAction handlerAction = actions.get(i);
5384 handler.postDelayed(handlerAction.action, handlerAction.delay);
5391 private static class HandlerAction {
5396 public boolean equals(Object o) {
5397 if (this == o) return true;
5398 if (o == null || getClass() != o.getClass()) return false;
5400 HandlerAction that = (HandlerAction) o;
5401 return !(action != null ? !action.equals(that.action) : that.action != null);
5406 public int hashCode() {
5407 int result = action != null ? action.hashCode() : 0;
5408 result = 31 * result + (int) (delay ^ (delay >>> 32));
5415 * Class for managing the accessibility interaction connection
5416 * based on the global accessibility state.
5418 final class AccessibilityInteractionConnectionManager
5419 implements AccessibilityStateChangeListener {
5420 public void onAccessibilityStateChanged(boolean enabled) {
5423 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
5424 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
5425 View focusedView = mView.findFocus();
5426 if (focusedView != null && focusedView != mView) {
5427 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5431 ensureNoConnection();
5432 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
5436 public void ensureConnection() {
5437 if (mAttachInfo != null) {
5438 final boolean registered =
5439 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5441 mAttachInfo.mAccessibilityWindowId =
5442 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
5443 new AccessibilityInteractionConnection(ViewRootImpl.this));
5448 public void ensureNoConnection() {
5449 final boolean registered =
5450 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED;
5452 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED;
5453 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
5459 * This class is an interface this ViewAncestor provides to the
5460 * AccessibilityManagerService to the latter can interact with
5461 * the view hierarchy in this ViewAncestor.
5463 static final class AccessibilityInteractionConnection
5464 extends IAccessibilityInteractionConnection.Stub {
5465 private final WeakReference<ViewRootImpl> mViewRootImpl;
5467 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
5468 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
5472 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
5473 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5474 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5475 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5476 if (viewRootImpl != null && viewRootImpl.mView != null) {
5477 viewRootImpl.getAccessibilityInteractionController()
5478 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
5479 interactionId, callback, flags, interrogatingPid, interrogatingTid,
5482 // We cannot make the call and notify the caller so it does not wait.
5484 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5485 } catch (RemoteException re) {
5486 /* best effort - ignore */
5492 public void performAccessibilityAction(long accessibilityNodeId, int action,
5493 Bundle arguments, int interactionId,
5494 IAccessibilityInteractionConnectionCallback callback, int flags,
5495 int interogatingPid, long interrogatingTid) {
5496 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5497 if (viewRootImpl != null && viewRootImpl.mView != null) {
5498 viewRootImpl.getAccessibilityInteractionController()
5499 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
5500 interactionId, callback, flags, interogatingPid, interrogatingTid);
5502 // We cannot make the call and notify the caller so it does not wait.
5504 callback.setPerformAccessibilityActionResult(false, interactionId);
5505 } catch (RemoteException re) {
5506 /* best effort - ignore */
5512 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId,
5513 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5514 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5515 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5516 if (viewRootImpl != null && viewRootImpl.mView != null) {
5517 viewRootImpl.getAccessibilityInteractionController()
5518 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId,
5519 interactionId, callback, flags, interrogatingPid, interrogatingTid,
5522 // We cannot make the call and notify the caller so it does not wait.
5524 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5525 } catch (RemoteException re) {
5526 /* best effort - ignore */
5532 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
5533 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
5534 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5535 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5536 if (viewRootImpl != null && viewRootImpl.mView != null) {
5537 viewRootImpl.getAccessibilityInteractionController()
5538 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
5539 interactionId, callback, flags, interrogatingPid, interrogatingTid,
5542 // We cannot make the call and notify the caller so it does not wait.
5544 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
5545 } catch (RemoteException re) {
5546 /* best effort - ignore */
5552 public void findFocus(long accessibilityNodeId, int focusType, int interactionId,
5553 IAccessibilityInteractionConnectionCallback callback, int flags,
5554 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5555 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5556 if (viewRootImpl != null && viewRootImpl.mView != null) {
5557 viewRootImpl.getAccessibilityInteractionController()
5558 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback,
5559 flags, interrogatingPid, interrogatingTid, spec);
5561 // We cannot make the call and notify the caller so it does not wait.
5563 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5564 } catch (RemoteException re) {
5565 /* best effort - ignore */
5571 public void focusSearch(long accessibilityNodeId, int direction, int interactionId,
5572 IAccessibilityInteractionConnectionCallback callback, int flags,
5573 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
5574 ViewRootImpl viewRootImpl = mViewRootImpl.get();
5575 if (viewRootImpl != null && viewRootImpl.mView != null) {
5576 viewRootImpl.getAccessibilityInteractionController()
5577 .focusSearchClientThread(accessibilityNodeId, direction, interactionId,
5578 callback, flags, interrogatingPid, interrogatingTid, spec);
5580 // We cannot make the call and notify the caller so it does not wait.
5582 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
5583 } catch (RemoteException re) {
5584 /* best effort - ignore */
5590 private class SendWindowContentChangedAccessibilityEvent implements Runnable {
5591 public View mSource;
5594 if (mSource != null) {
5595 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
5596 mSource.resetAccessibilityStateChanged();