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