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