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