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