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