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