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