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