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