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