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