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