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