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