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