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