ViewRootImpl.java revision 250069bf6bf3d7e2ef85c49e0cd100e80c3c8b7d
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.animation.ValueAnimator; 22import android.app.ActivityManagerNative; 23import android.content.ClipDescription; 24import android.content.ComponentCallbacks; 25import android.content.ComponentCallbacks2; 26import android.content.Context; 27import android.content.pm.ApplicationInfo; 28import android.content.pm.PackageManager; 29import android.content.res.CompatibilityInfo; 30import android.content.res.Configuration; 31import android.content.res.Resources; 32import android.graphics.Canvas; 33import android.graphics.Paint; 34import android.graphics.PixelFormat; 35import android.graphics.Point; 36import android.graphics.PointF; 37import android.graphics.PorterDuff; 38import android.graphics.Rect; 39import android.graphics.Region; 40import android.media.AudioManager; 41import android.os.Binder; 42import android.os.Bundle; 43import android.os.Debug; 44import android.os.Handler; 45import android.os.LatencyTimer; 46import android.os.Looper; 47import android.os.Message; 48import android.os.ParcelFileDescriptor; 49import android.os.PowerManager; 50import android.os.Process; 51import android.os.RemoteException; 52import android.os.SystemClock; 53import android.os.SystemProperties; 54import android.util.AndroidRuntimeException; 55import android.util.DisplayMetrics; 56import android.util.EventLog; 57import android.util.Log; 58import android.util.Pool; 59import android.util.Poolable; 60import android.util.PoolableManager; 61import android.util.Pools; 62import android.util.Slog; 63import android.util.SparseLongArray; 64import android.util.TypedValue; 65import android.view.View.AttachInfo; 66import android.view.View.MeasureSpec; 67import android.view.accessibility.AccessibilityEvent; 68import android.view.accessibility.AccessibilityInteractionClient; 69import android.view.accessibility.AccessibilityManager; 70import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener; 71import android.view.accessibility.AccessibilityNodeInfo; 72import android.view.accessibility.AccessibilityNodeProvider; 73import android.view.accessibility.IAccessibilityInteractionConnection; 74import android.view.accessibility.IAccessibilityInteractionConnectionCallback; 75import android.view.animation.AccelerateDecelerateInterpolator; 76import android.view.animation.Interpolator; 77import android.view.inputmethod.InputConnection; 78import android.view.inputmethod.InputMethodManager; 79import android.widget.Scroller; 80 81import com.android.internal.policy.PolicyManager; 82import com.android.internal.view.BaseSurfaceHolder; 83import com.android.internal.view.IInputMethodCallback; 84import com.android.internal.view.IInputMethodSession; 85import com.android.internal.view.RootViewSurfaceTaker; 86 87import java.io.IOException; 88import java.io.OutputStream; 89import java.lang.ref.WeakReference; 90import java.util.ArrayList; 91import java.util.HashMap; 92import java.util.List; 93import java.util.Map; 94 95/** 96 * The top of a view hierarchy, implementing the needed protocol between View 97 * and the WindowManager. This is for the most part an internal implementation 98 * detail of {@link WindowManagerImpl}. 99 * 100 * {@hide} 101 */ 102@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"}) 103public final class ViewRootImpl implements ViewParent, 104 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks { 105 private static final String TAG = "ViewRootImpl"; 106 private static final boolean DBG = false; 107 private static final boolean LOCAL_LOGV = false; 108 /** @noinspection PointlessBooleanExpression*/ 109 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV; 110 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV; 111 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV; 112 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV; 113 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV; 114 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV; 115 private static final boolean DEBUG_IMF = false || LOCAL_LOGV; 116 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV; 117 private static final boolean DEBUG_FPS = false; 118 119 /** 120 * Set this system property to true to force the view hierarchy to render 121 * at 60 Hz. This can be used to measure the potential framerate. 122 */ 123 private static final String PROPERTY_PROFILE_RENDERING = "viewancestor.profile_rendering"; 124 125 private static final boolean MEASURE_LATENCY = false; 126 private static LatencyTimer lt; 127 128 /** 129 * Maximum time we allow the user to roll the trackball enough to generate 130 * a key event, before resetting the counters. 131 */ 132 static final int MAX_TRACKBALL_DELAY = 250; 133 134 static IWindowSession sWindowSession; 135 136 static final Object mStaticInit = new Object(); 137 static boolean mInitialized = false; 138 139 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>(); 140 141 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>(); 142 static boolean sFirstDrawComplete = false; 143 144 static final ArrayList<ComponentCallbacks> sConfigCallbacks 145 = new ArrayList<ComponentCallbacks>(); 146 147 private static boolean sUseRenderThread = false; 148 private static boolean sRenderThreadQueried = false; 149 private static final Object[] sRenderThreadQueryLock = new Object[0]; 150 151 long mLastTrackballTime = 0; 152 final TrackballAxis mTrackballAxisX = new TrackballAxis(); 153 final TrackballAxis mTrackballAxisY = new TrackballAxis(); 154 155 int mLastJoystickXDirection; 156 int mLastJoystickYDirection; 157 int mLastJoystickXKeyCode; 158 int mLastJoystickYKeyCode; 159 160 final int[] mTmpLocation = new int[2]; 161 162 final TypedValue mTmpValue = new TypedValue(); 163 164 final InputMethodCallback mInputMethodCallback; 165 final Thread mThread; 166 167 final WindowLeaked mLocation; 168 169 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams(); 170 171 final W mWindow; 172 173 final int mTargetSdkVersion; 174 175 int mSeq; 176 177 View mView; 178 View mFocusedView; 179 View mRealFocusedView; // this is not set to null in touch mode 180 View mOldFocusedView; 181 int mViewVisibility; 182 boolean mAppVisible = true; 183 int mOrigWindowType = -1; 184 185 // Set to true if the owner of this window is in the stopped state, 186 // so the window should no longer be active. 187 boolean mStopped = false; 188 189 boolean mLastInCompatMode = false; 190 191 SurfaceHolder.Callback2 mSurfaceHolderCallback; 192 BaseSurfaceHolder mSurfaceHolder; 193 boolean mIsCreating; 194 boolean mDrawingAllowed; 195 196 final Region mTransparentRegion; 197 final Region mPreviousTransparentRegion; 198 199 int mWidth; 200 int mHeight; 201 Rect mDirty; 202 final Rect mCurrentDirty = new Rect(); 203 final Rect mPreviousDirty = new Rect(); 204 boolean mIsAnimating; 205 206 CompatibilityInfo.Translator mTranslator; 207 208 final View.AttachInfo mAttachInfo; 209 InputChannel mInputChannel; 210 InputQueue.Callback mInputQueueCallback; 211 InputQueue mInputQueue; 212 FallbackEventHandler mFallbackEventHandler; 213 Choreographer mChoreographer; 214 215 final Rect mTempRect; // used in the transaction to not thrash the heap. 216 final Rect mVisRect; // used to retrieve visible rect of focused view. 217 218 boolean mTraversalScheduled; 219 int mTraversalBarrier; 220 long mLastTraversalFinishedTimeNanos; 221 long mLastDrawFinishedTimeNanos; 222 boolean mWillDrawSoon; 223 boolean mLayoutRequested; 224 boolean mFirst; 225 boolean mReportNextDraw; 226 boolean mFullRedrawNeeded; 227 boolean mNewSurfaceNeeded; 228 boolean mHasHadWindowFocus; 229 boolean mLastWasImTarget; 230 231 // Pool of queued input events. 232 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10; 233 private QueuedInputEvent mQueuedInputEventPool; 234 private int mQueuedInputEventPoolSize; 235 236 // Input event queue. 237 QueuedInputEvent mFirstPendingInputEvent; 238 QueuedInputEvent mCurrentInputEvent; 239 boolean mProcessInputEventsScheduled; 240 241 boolean mWindowAttributesChanged = false; 242 int mWindowAttributesChangesFlag = 0; 243 244 // These can be accessed by any thread, must be protected with a lock. 245 // Surface can never be reassigned or cleared (use Surface.clear()). 246 private final Surface mSurface = new Surface(); 247 248 boolean mAdded; 249 boolean mAddedTouchMode; 250 251 CompatibilityInfoHolder mCompatibilityInfo; 252 253 /*package*/ int mAddNesting; 254 255 // These are accessed by multiple threads. 256 final Rect mWinFrame; // frame given by window manager. 257 258 final Rect mPendingVisibleInsets = new Rect(); 259 final Rect mPendingContentInsets = new Rect(); 260 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets 261 = new ViewTreeObserver.InternalInsetsInfo(); 262 263 final Configuration mLastConfiguration = new Configuration(); 264 final Configuration mPendingConfiguration = new Configuration(); 265 266 class ResizedInfo { 267 Rect coveredInsets; 268 Rect visibleInsets; 269 Configuration newConfig; 270 } 271 272 boolean mScrollMayChange; 273 int mSoftInputMode; 274 View mLastScrolledFocus; 275 int mScrollY; 276 int mCurScrollY; 277 Scroller mScroller; 278 HardwareLayer mResizeBuffer; 279 long mResizeBufferStartTime; 280 int mResizeBufferDuration; 281 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator(); 282 private ArrayList<LayoutTransition> mPendingTransitions; 283 284 final ViewConfiguration mViewConfiguration; 285 286 /* Drag/drop */ 287 ClipDescription mDragDescription; 288 View mCurrentDragView; 289 volatile Object mLocalDragState; 290 final PointF mDragPoint = new PointF(); 291 final PointF mLastTouchPoint = new PointF(); 292 293 private boolean mProfileRendering; 294 private Thread mRenderProfiler; 295 private volatile boolean mRenderProfilingEnabled; 296 297 // Variables to track frames per second, enabled via DEBUG_FPS flag 298 private long mFpsStartTime = -1; 299 private long mFpsPrevTime = -1; 300 private int mFpsNumFrames; 301 302 /** 303 * see {@link #playSoundEffect(int)} 304 */ 305 AudioManager mAudioManager; 306 307 final AccessibilityManager mAccessibilityManager; 308 309 AccessibilityInteractionController mAccessibilityInteractionController; 310 311 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager; 312 313 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent; 314 315 AccessibilityNodePrefetcher mAccessibilityNodePrefetcher; 316 317 private final int mDensity; 318 319 /** 320 * Consistency verifier for debugging purposes. 321 */ 322 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 323 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 324 new InputEventConsistencyVerifier(this, 0) : null; 325 326 public static IWindowSession getWindowSession(Looper mainLooper) { 327 synchronized (mStaticInit) { 328 if (!mInitialized) { 329 try { 330 InputMethodManager imm = InputMethodManager.getInstance(mainLooper); 331 IWindowManager windowManager = Display.getWindowManager(); 332 sWindowSession = windowManager.openSession( 333 imm.getClient(), imm.getInputContext()); 334 float animatorScale = windowManager.getAnimationScale(2); 335 ValueAnimator.setDurationScale(animatorScale); 336 mInitialized = true; 337 } catch (RemoteException e) { 338 } 339 } 340 return sWindowSession; 341 } 342 } 343 344 static final class SystemUiVisibilityInfo { 345 int seq; 346 int globalVisibility; 347 int localValue; 348 int localChanges; 349 } 350 351 public ViewRootImpl(Context context) { 352 super(); 353 354 if (MEASURE_LATENCY) { 355 if (lt == null) { 356 lt = new LatencyTimer(100, 1000); 357 } 358 } 359 360 // Initialize the statics when this class is first instantiated. This is 361 // done here instead of in the static block because Zygote does not 362 // allow the spawning of threads. 363 getWindowSession(context.getMainLooper()); 364 365 mThread = Thread.currentThread(); 366 mLocation = new WindowLeaked(null); 367 mLocation.fillInStackTrace(); 368 mWidth = -1; 369 mHeight = -1; 370 mDirty = new Rect(); 371 mTempRect = new Rect(); 372 mVisRect = new Rect(); 373 mWinFrame = new Rect(); 374 mWindow = new W(this); 375 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion; 376 mInputMethodCallback = new InputMethodCallback(this); 377 mViewVisibility = View.GONE; 378 mTransparentRegion = new Region(); 379 mPreviousTransparentRegion = new Region(); 380 mFirst = true; // true for the first time the view is added 381 mAdded = false; 382 mAccessibilityManager = AccessibilityManager.getInstance(context); 383 mAccessibilityInteractionConnectionManager = 384 new AccessibilityInteractionConnectionManager(); 385 mAccessibilityManager.addAccessibilityStateChangeListener( 386 mAccessibilityInteractionConnectionManager); 387 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, mHandler, this); 388 mViewConfiguration = ViewConfiguration.get(context); 389 mDensity = context.getResources().getDisplayMetrics().densityDpi; 390 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context); 391 mProfileRendering = Boolean.parseBoolean( 392 SystemProperties.get(PROPERTY_PROFILE_RENDERING, "false")); 393 mChoreographer = Choreographer.getInstance(); 394 395 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 396 mAttachInfo.mScreenOn = powerManager.isScreenOn(); 397 } 398 399 /** 400 * @return True if the application requests the use of a separate render thread, 401 * false otherwise 402 */ 403 private static boolean isRenderThreadRequested(Context context) { 404 synchronized (sRenderThreadQueryLock) { 405 if (!sRenderThreadQueried) { 406 final PackageManager packageManager = context.getPackageManager(); 407 final String packageName = context.getApplicationInfo().packageName; 408 try { 409 ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 410 PackageManager.GET_META_DATA); 411 if (applicationInfo.metaData != null) { 412 sUseRenderThread = applicationInfo.metaData.getBoolean( 413 "android.graphics.renderThread", false); 414 } 415 } catch (PackageManager.NameNotFoundException e) { 416 } finally { 417 sRenderThreadQueried = true; 418 } 419 } 420 return sUseRenderThread; 421 } 422 } 423 424 public static void addFirstDrawHandler(Runnable callback) { 425 synchronized (sFirstDrawHandlers) { 426 if (!sFirstDrawComplete) { 427 sFirstDrawHandlers.add(callback); 428 } 429 } 430 } 431 432 public static void addConfigCallback(ComponentCallbacks callback) { 433 synchronized (sConfigCallbacks) { 434 sConfigCallbacks.add(callback); 435 } 436 } 437 438 // FIXME for perf testing only 439 private boolean mProfile = false; 440 441 /** 442 * Call this to profile the next traversal call. 443 * FIXME for perf testing only. Remove eventually 444 */ 445 public void profile() { 446 mProfile = true; 447 } 448 449 /** 450 * Indicates whether we are in touch mode. Calling this method triggers an IPC 451 * call and should be avoided whenever possible. 452 * 453 * @return True, if the device is in touch mode, false otherwise. 454 * 455 * @hide 456 */ 457 static boolean isInTouchMode() { 458 if (mInitialized) { 459 try { 460 return sWindowSession.getInTouchMode(); 461 } catch (RemoteException e) { 462 } 463 } 464 return false; 465 } 466 467 /** 468 * We have one child 469 */ 470 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) { 471 synchronized (this) { 472 if (mView == null) { 473 mView = view; 474 mFallbackEventHandler.setView(view); 475 mWindowAttributes.copyFrom(attrs); 476 attrs = mWindowAttributes; 477 478 if (view instanceof RootViewSurfaceTaker) { 479 mSurfaceHolderCallback = 480 ((RootViewSurfaceTaker)view).willYouTakeTheSurface(); 481 if (mSurfaceHolderCallback != null) { 482 mSurfaceHolder = new TakenSurfaceHolder(); 483 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN); 484 } 485 } 486 487 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 488 mTranslator = compatibilityInfo.getTranslator(); 489 490 // If the application owns the surface, don't enable hardware acceleration 491 if (mSurfaceHolder == null) { 492 enableHardwareAcceleration(mView.getContext(), attrs); 493 } 494 495 boolean restore = false; 496 if (mTranslator != null) { 497 mSurface.setCompatibilityTranslator(mTranslator); 498 restore = true; 499 attrs.backup(); 500 mTranslator.translateWindowLayout(attrs); 501 } 502 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs); 503 504 if (!compatibilityInfo.supportsScreen()) { 505 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 506 mLastInCompatMode = true; 507 } 508 509 mSoftInputMode = attrs.softInputMode; 510 mWindowAttributesChanged = true; 511 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED; 512 mAttachInfo.mRootView = view; 513 mAttachInfo.mScalingRequired = mTranslator != null; 514 mAttachInfo.mApplicationScale = 515 mTranslator == null ? 1.0f : mTranslator.applicationScale; 516 if (panelParentView != null) { 517 mAttachInfo.mPanelParentWindowToken 518 = panelParentView.getApplicationWindowToken(); 519 } 520 mAdded = true; 521 int res; /* = WindowManagerImpl.ADD_OKAY; */ 522 523 // Schedule the first layout -before- adding to the window 524 // manager, to make sure we do the relayout before receiving 525 // any other events from the system. 526 requestLayout(); 527 if ((mWindowAttributes.inputFeatures 528 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { 529 mInputChannel = new InputChannel(); 530 } 531 try { 532 mOrigWindowType = mWindowAttributes.type; 533 res = sWindowSession.add(mWindow, mSeq, mWindowAttributes, 534 getHostVisibility(), mAttachInfo.mContentInsets, 535 mInputChannel); 536 } catch (RemoteException e) { 537 mAdded = false; 538 mView = null; 539 mAttachInfo.mRootView = null; 540 mInputChannel = null; 541 mFallbackEventHandler.setView(null); 542 unscheduleTraversals(); 543 throw new RuntimeException("Adding window failed", e); 544 } finally { 545 if (restore) { 546 attrs.restore(); 547 } 548 } 549 550 if (mTranslator != null) { 551 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets); 552 } 553 mPendingContentInsets.set(mAttachInfo.mContentInsets); 554 mPendingVisibleInsets.set(0, 0, 0, 0); 555 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow); 556 if (res < WindowManagerImpl.ADD_OKAY) { 557 mView = null; 558 mAttachInfo.mRootView = null; 559 mAdded = false; 560 mFallbackEventHandler.setView(null); 561 unscheduleTraversals(); 562 switch (res) { 563 case WindowManagerImpl.ADD_BAD_APP_TOKEN: 564 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN: 565 throw new WindowManagerImpl.BadTokenException( 566 "Unable to add window -- token " + attrs.token 567 + " is not valid; is your activity running?"); 568 case WindowManagerImpl.ADD_NOT_APP_TOKEN: 569 throw new WindowManagerImpl.BadTokenException( 570 "Unable to add window -- token " + attrs.token 571 + " is not for an application"); 572 case WindowManagerImpl.ADD_APP_EXITING: 573 throw new WindowManagerImpl.BadTokenException( 574 "Unable to add window -- app for token " + attrs.token 575 + " is exiting"); 576 case WindowManagerImpl.ADD_DUPLICATE_ADD: 577 throw new WindowManagerImpl.BadTokenException( 578 "Unable to add window -- window " + mWindow 579 + " has already been added"); 580 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED: 581 // Silently ignore -- we would have just removed it 582 // right away, anyway. 583 return; 584 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON: 585 throw new WindowManagerImpl.BadTokenException( 586 "Unable to add window " + mWindow + 587 " -- another window of this type already exists"); 588 case WindowManagerImpl.ADD_PERMISSION_DENIED: 589 throw new WindowManagerImpl.BadTokenException( 590 "Unable to add window " + mWindow + 591 " -- permission denied for this window type"); 592 } 593 throw new RuntimeException( 594 "Unable to add window -- unknown error code " + res); 595 } 596 597 if (view instanceof RootViewSurfaceTaker) { 598 mInputQueueCallback = 599 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue(); 600 } 601 if (mInputChannel != null) { 602 if (mInputQueueCallback != null) { 603 mInputQueue = new InputQueue(mInputChannel); 604 mInputQueueCallback.onInputQueueCreated(mInputQueue); 605 } else { 606 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel, 607 Looper.myLooper()); 608 } 609 } 610 611 view.assignParent(this); 612 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0; 613 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0; 614 615 if (mAccessibilityManager.isEnabled()) { 616 mAccessibilityInteractionConnectionManager.ensureConnection(); 617 } 618 } 619 } 620 } 621 622 void destroyHardwareResources() { 623 if (mAttachInfo.mHardwareRenderer != null) { 624 if (mAttachInfo.mHardwareRenderer.isEnabled()) { 625 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 626 } 627 mAttachInfo.mHardwareRenderer.destroy(false); 628 } 629 } 630 631 void terminateHardwareResources() { 632 if (mAttachInfo.mHardwareRenderer != null) { 633 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView); 634 mAttachInfo.mHardwareRenderer.destroy(false); 635 } 636 } 637 638 void destroyHardwareLayers() { 639 if (mThread != Thread.currentThread()) { 640 if (mAttachInfo.mHardwareRenderer != null && 641 mAttachInfo.mHardwareRenderer.isEnabled()) { 642 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE); 643 } 644 } else { 645 if (mAttachInfo.mHardwareRenderer != null && 646 mAttachInfo.mHardwareRenderer.isEnabled()) { 647 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 648 } 649 } 650 } 651 652 private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) { 653 mAttachInfo.mHardwareAccelerated = false; 654 mAttachInfo.mHardwareAccelerationRequested = false; 655 656 // Don't enable hardware acceleration when the application is in compatibility mode 657 if (mTranslator != null) return; 658 659 // Try to enable hardware acceleration if requested 660 final boolean hardwareAccelerated = 661 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0; 662 663 if (hardwareAccelerated) { 664 if (!HardwareRenderer.isAvailable()) { 665 return; 666 } 667 668 // Persistent processes (including the system) should not do 669 // accelerated rendering on low-end devices. In that case, 670 // sRendererDisabled will be set. In addition, the system process 671 // itself should never do accelerated rendering. In that case, both 672 // sRendererDisabled and sSystemRendererDisabled are set. When 673 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED 674 // can be used by code on the system process to escape that and enable 675 // HW accelerated drawing. (This is basically for the lock screen.) 676 677 final boolean fakeHwAccelerated = (attrs.privateFlags & 678 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0; 679 final boolean forceHwAccelerated = (attrs.privateFlags & 680 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0; 681 682 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled 683 && forceHwAccelerated)) { 684 // Don't enable hardware acceleration when we're not on the main thread 685 if (!HardwareRenderer.sSystemRendererDisabled && 686 Looper.getMainLooper() != Looper.myLooper()) { 687 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware " 688 + "acceleration outside of the main thread, aborting"); 689 return; 690 } 691 692 boolean renderThread = isRenderThreadRequested(context); 693 if (renderThread) { 694 Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated"); 695 } 696 697 if (mAttachInfo.mHardwareRenderer != null) { 698 mAttachInfo.mHardwareRenderer.destroy(true); 699 } 700 701 final boolean translucent = attrs.format != PixelFormat.OPAQUE; 702 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent); 703 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested 704 = mAttachInfo.mHardwareRenderer != null; 705 706 } else if (fakeHwAccelerated) { 707 // The window had wanted to use hardware acceleration, but this 708 // is not allowed in its process. By setting this flag, it can 709 // still render as if it was accelerated. This is basically for 710 // the preview windows the window manager shows for launching 711 // applications, so they will look more like the app being launched. 712 mAttachInfo.mHardwareAccelerationRequested = true; 713 } 714 } 715 } 716 717 public View getView() { 718 return mView; 719 } 720 721 final WindowLeaked getLocation() { 722 return mLocation; 723 } 724 725 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) { 726 synchronized (this) { 727 int oldSoftInputMode = mWindowAttributes.softInputMode; 728 // preserve compatible window flag if exists. 729 int compatibleWindowFlag = 730 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 731 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs); 732 mWindowAttributes.flags |= compatibleWindowFlag; 733 734 if (newView) { 735 mSoftInputMode = attrs.softInputMode; 736 requestLayout(); 737 } 738 // Don't lose the mode we last auto-computed. 739 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 740 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 741 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode 742 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 743 | (oldSoftInputMode 744 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST); 745 } 746 mWindowAttributesChanged = true; 747 scheduleTraversals(); 748 } 749 } 750 751 void handleAppVisibility(boolean visible) { 752 if (mAppVisible != visible) { 753 mAppVisible = visible; 754 scheduleTraversals(); 755 } 756 } 757 758 void handleGetNewSurface() { 759 mNewSurfaceNeeded = true; 760 mFullRedrawNeeded = true; 761 scheduleTraversals(); 762 } 763 764 void handleScreenStatusChange(boolean on) { 765 if (on != mAttachInfo.mScreenOn) { 766 mAttachInfo.mScreenOn = on; 767 if (on) { 768 mFullRedrawNeeded = true; 769 scheduleTraversals(); 770 } 771 } 772 } 773 774 /** 775 * {@inheritDoc} 776 */ 777 public void requestLayout() { 778 checkThread(); 779 mLayoutRequested = true; 780 scheduleTraversals(); 781 } 782 783 /** 784 * {@inheritDoc} 785 */ 786 public boolean isLayoutRequested() { 787 return mLayoutRequested; 788 } 789 790 void invalidate() { 791 mDirty.set(0, 0, mWidth, mHeight); 792 scheduleTraversals(); 793 } 794 795 public void invalidateChild(View child, Rect dirty) { 796 invalidateChildInParent(null, dirty); 797 } 798 799 public ViewParent invalidateChildInParent(int[] location, Rect dirty) { 800 checkThread(); 801 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty); 802 803 if (dirty == null) { 804 invalidate(); 805 return null; 806 } 807 808 if (mCurScrollY != 0 || mTranslator != null) { 809 mTempRect.set(dirty); 810 dirty = mTempRect; 811 if (mCurScrollY != 0) { 812 dirty.offset(0, -mCurScrollY); 813 } 814 if (mTranslator != null) { 815 mTranslator.translateRectInAppWindowToScreen(dirty); 816 } 817 if (mAttachInfo.mScalingRequired) { 818 dirty.inset(-1, -1); 819 } 820 } 821 822 final Rect localDirty = mDirty; 823 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) { 824 mAttachInfo.mSetIgnoreDirtyState = true; 825 mAttachInfo.mIgnoreDirtyState = true; 826 } 827 828 // Add the new dirty rect to the current one 829 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom); 830 // Intersect with the bounds of the window to skip 831 // updates that lie outside of the visible region 832 localDirty.intersect(0, 0, mWidth, mHeight); 833 834 if (!mWillDrawSoon) { 835 scheduleTraversals(); 836 } 837 838 return null; 839 } 840 841 void setStopped(boolean stopped) { 842 if (mStopped != stopped) { 843 mStopped = stopped; 844 if (!stopped) { 845 scheduleTraversals(); 846 } 847 } 848 } 849 850 public ViewParent getParent() { 851 return null; 852 } 853 854 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 855 if (child != mView) { 856 throw new RuntimeException("child is not mine, honest!"); 857 } 858 // Note: don't apply scroll offset, because we want to know its 859 // visibility in the virtual canvas being given to the view hierarchy. 860 return r.intersect(0, 0, mWidth, mHeight); 861 } 862 863 public void bringChildToFront(View child) { 864 } 865 866 public void scheduleTraversals() { 867 if (!mTraversalScheduled) { 868 mTraversalScheduled = true; 869 mTraversalBarrier = mHandler.getLooper().postSyncBarrier(); 870 scheduleFrame(); 871 } 872 } 873 874 public void unscheduleTraversals() { 875 if (mTraversalScheduled) { 876 mTraversalScheduled = false; 877 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 878 } 879 } 880 881 void scheduleFrame() { 882 if (!mFrameScheduled) { 883 mFrameScheduled = true; 884 mChoreographer.postDrawCallback(mFrameRunnable); 885 } 886 } 887 888 void unscheduleFrame() { 889 unscheduleTraversals(); 890 891 if (mFrameScheduled) { 892 mFrameScheduled = false; 893 mChoreographer.removeDrawCallbacks(mFrameRunnable); 894 } 895 } 896 897 void doFrame() { 898 if (mInputEventReceiver != null) { 899 mInputEventReceiver.consumeBatchedInputEvents(); 900 } 901 doProcessInputEvents(); 902 903 if (mTraversalScheduled) { 904 mTraversalScheduled = false; 905 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 906 doTraversal(); 907 } 908 } 909 910 int getHostVisibility() { 911 return mAppVisible ? mView.getVisibility() : View.GONE; 912 } 913 914 void disposeResizeBuffer() { 915 if (mResizeBuffer != null) { 916 mResizeBuffer.destroy(); 917 mResizeBuffer = null; 918 } 919 } 920 921 /** 922 * Add LayoutTransition to the list of transitions to be started in the next traversal. 923 * This list will be cleared after the transitions on the list are start()'ed. These 924 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup 925 * happens during the layout phase of traversal, which we want to complete before any of the 926 * animations are started (because those animations may side-effect properties that layout 927 * depends upon, like the bounding rectangles of the affected views). So we add the transition 928 * to the list and it is started just prior to starting the drawing phase of traversal. 929 * 930 * @param transition The LayoutTransition to be started on the next traversal. 931 * 932 * @hide 933 */ 934 public void requestTransitionStart(LayoutTransition transition) { 935 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) { 936 if (mPendingTransitions == null) { 937 mPendingTransitions = new ArrayList<LayoutTransition>(); 938 } 939 mPendingTransitions.add(transition); 940 } 941 } 942 943 private void doTraversal() { 944 if (mProfile) { 945 Debug.startMethodTracing("ViewAncestor"); 946 } 947 948 final long traversalStartTime; 949 if (ViewDebug.DEBUG_LATENCY) { 950 traversalStartTime = System.nanoTime(); 951 if (mLastTraversalFinishedTimeNanos != 0) { 952 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting performTraversals(); it has been " 953 + ((traversalStartTime - mLastTraversalFinishedTimeNanos) * 0.000001f) 954 + "ms since the last traversals finished."); 955 } else { 956 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting performTraversals()."); 957 } 958 } 959 960 performTraversals(); 961 962 if (ViewDebug.DEBUG_LATENCY) { 963 long now = System.nanoTime(); 964 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "performTraversals() took " 965 + ((now - traversalStartTime) * 0.000001f) 966 + "ms."); 967 mLastTraversalFinishedTimeNanos = now; 968 } 969 970 if (mProfile) { 971 Debug.stopMethodTracing(); 972 mProfile = false; 973 } 974 } 975 976 private void performTraversals() { 977 // cache mView since it is used so much below... 978 final View host = mView; 979 980 if (DBG) { 981 System.out.println("======================================"); 982 System.out.println("performTraversals"); 983 host.debug(); 984 } 985 986 if (host == null || !mAdded) 987 return; 988 989 mWillDrawSoon = true; 990 boolean windowSizeMayChange = false; 991 boolean newSurface = false; 992 boolean surfaceChanged = false; 993 WindowManager.LayoutParams lp = mWindowAttributes; 994 995 int desiredWindowWidth; 996 int desiredWindowHeight; 997 int childWidthMeasureSpec; 998 int childHeightMeasureSpec; 999 1000 final View.AttachInfo attachInfo = mAttachInfo; 1001 1002 final int viewVisibility = getHostVisibility(); 1003 boolean viewVisibilityChanged = mViewVisibility != viewVisibility 1004 || mNewSurfaceNeeded; 1005 1006 WindowManager.LayoutParams params = null; 1007 if (mWindowAttributesChanged) { 1008 mWindowAttributesChanged = false; 1009 surfaceChanged = true; 1010 params = lp; 1011 } 1012 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 1013 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) { 1014 params = lp; 1015 mFullRedrawNeeded = true; 1016 mLayoutRequested = true; 1017 if (mLastInCompatMode) { 1018 params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1019 mLastInCompatMode = false; 1020 } else { 1021 params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1022 mLastInCompatMode = true; 1023 } 1024 } 1025 1026 mWindowAttributesChangesFlag = 0; 1027 1028 Rect frame = mWinFrame; 1029 if (mFirst) { 1030 mFullRedrawNeeded = true; 1031 mLayoutRequested = true; 1032 1033 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1034 // NOTE -- system code, won't try to do compat mode. 1035 Display disp = WindowManagerImpl.getDefault().getDefaultDisplay(); 1036 Point size = new Point(); 1037 disp.getRealSize(size); 1038 desiredWindowWidth = size.x; 1039 desiredWindowHeight = size.y; 1040 } else { 1041 DisplayMetrics packageMetrics = 1042 mView.getContext().getResources().getDisplayMetrics(); 1043 desiredWindowWidth = packageMetrics.widthPixels; 1044 desiredWindowHeight = packageMetrics.heightPixels; 1045 } 1046 1047 // For the very first time, tell the view hierarchy that it 1048 // is attached to the window. Note that at this point the surface 1049 // object is not initialized to its backing store, but soon it 1050 // will be (assuming the window is visible). 1051 attachInfo.mSurface = mSurface; 1052 // We used to use the following condition to choose 32 bits drawing caches: 1053 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888 1054 // However, windows are now always 32 bits by default, so choose 32 bits 1055 attachInfo.mUse32BitDrawingCache = true; 1056 attachInfo.mHasWindowFocus = false; 1057 attachInfo.mWindowVisibility = viewVisibility; 1058 attachInfo.mRecomputeGlobalAttributes = false; 1059 attachInfo.mKeepScreenOn = false; 1060 attachInfo.mSystemUiVisibility = 0; 1061 viewVisibilityChanged = false; 1062 mLastConfiguration.setTo(host.getResources().getConfiguration()); 1063 host.dispatchAttachedToWindow(attachInfo, 0); 1064 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn); 1065 1066 host.fitSystemWindows(mAttachInfo.mContentInsets); 1067 1068 } else { 1069 desiredWindowWidth = frame.width(); 1070 desiredWindowHeight = frame.height(); 1071 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) { 1072 if (DEBUG_ORIENTATION) Log.v(TAG, 1073 "View " + host + " resized to: " + frame); 1074 mFullRedrawNeeded = true; 1075 mLayoutRequested = true; 1076 windowSizeMayChange = true; 1077 } 1078 } 1079 1080 if (viewVisibilityChanged) { 1081 attachInfo.mWindowVisibility = viewVisibility; 1082 host.dispatchWindowVisibilityChanged(viewVisibility); 1083 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) { 1084 destroyHardwareResources(); 1085 } 1086 if (viewVisibility == View.GONE) { 1087 // After making a window gone, we will count it as being 1088 // shown for the first time the next time it gets focus. 1089 mHasHadWindowFocus = false; 1090 } 1091 } 1092 1093 boolean insetsChanged = false; 1094 1095 if (mLayoutRequested && !mStopped) { 1096 // Execute enqueued actions on every layout in case a view that was detached 1097 // enqueued an action after being detached 1098 getRunQueue().executeActions(attachInfo.mHandler); 1099 1100 final Resources res = mView.getContext().getResources(); 1101 1102 if (mFirst) { 1103 // make sure touch mode code executes by setting cached value 1104 // to opposite of the added touch mode. 1105 mAttachInfo.mInTouchMode = !mAddedTouchMode; 1106 ensureTouchModeLocally(mAddedTouchMode); 1107 } else { 1108 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) { 1109 insetsChanged = true; 1110 } 1111 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) { 1112 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1113 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1114 + mAttachInfo.mVisibleInsets); 1115 } 1116 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT 1117 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) { 1118 windowSizeMayChange = true; 1119 1120 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1121 // NOTE -- system code, won't try to do compat mode. 1122 Display disp = WindowManagerImpl.getDefault().getDefaultDisplay(); 1123 Point size = new Point(); 1124 disp.getRealSize(size); 1125 desiredWindowWidth = size.x; 1126 desiredWindowHeight = size.y; 1127 } else { 1128 DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1129 desiredWindowWidth = packageMetrics.widthPixels; 1130 desiredWindowHeight = packageMetrics.heightPixels; 1131 } 1132 } 1133 } 1134 1135 // Ask host how big it wants to be 1136 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG, 1137 "Measuring " + host + " in display " + desiredWindowWidth 1138 + "x" + desiredWindowHeight + "..."); 1139 1140 boolean goodMeasure = false; 1141 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) { 1142 // On large screens, we don't want to allow dialogs to just 1143 // stretch to fill the entire width of the screen to display 1144 // one line of text. First try doing the layout at a smaller 1145 // size to see if it will fit. 1146 final DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1147 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true); 1148 int baseSize = 0; 1149 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) { 1150 baseSize = (int)mTmpValue.getDimension(packageMetrics); 1151 } 1152 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize); 1153 if (baseSize != 0 && desiredWindowWidth > baseSize) { 1154 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1155 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1156 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1157 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1158 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1159 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1160 goodMeasure = true; 1161 } else { 1162 // Didn't fit in that size... try expanding a bit. 1163 baseSize = (baseSize+desiredWindowWidth)/2; 1164 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize=" 1165 + baseSize); 1166 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1167 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1168 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1169 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1170 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1171 if (DEBUG_DIALOG) Log.v(TAG, "Good!"); 1172 goodMeasure = true; 1173 } 1174 } 1175 } 1176 } 1177 1178 if (!goodMeasure) { 1179 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); 1180 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1181 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1182 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) { 1183 windowSizeMayChange = true; 1184 } 1185 } 1186 1187 if (DBG) { 1188 System.out.println("======================================"); 1189 System.out.println("performTraversals -- after measure"); 1190 host.debug(); 1191 } 1192 } 1193 1194 if (attachInfo.mRecomputeGlobalAttributes && host.mAttachInfo != null) { 1195 //Log.i(TAG, "Computing view hierarchy attributes!"); 1196 attachInfo.mRecomputeGlobalAttributes = false; 1197 boolean oldScreenOn = attachInfo.mKeepScreenOn; 1198 int oldVis = attachInfo.mSystemUiVisibility; 1199 boolean oldHasSystemUiListeners = attachInfo.mHasSystemUiListeners; 1200 attachInfo.mKeepScreenOn = false; 1201 attachInfo.mSystemUiVisibility = 0; 1202 attachInfo.mHasSystemUiListeners = false; 1203 host.dispatchCollectViewAttributes(0); 1204 if (attachInfo.mKeepScreenOn != oldScreenOn 1205 || attachInfo.mSystemUiVisibility != oldVis 1206 || attachInfo.mHasSystemUiListeners != oldHasSystemUiListeners) { 1207 params = lp; 1208 } 1209 } 1210 if (attachInfo.mForceReportNewAttributes) { 1211 attachInfo.mForceReportNewAttributes = false; 1212 params = lp; 1213 } 1214 1215 if (mFirst || attachInfo.mViewVisibilityChanged) { 1216 attachInfo.mViewVisibilityChanged = false; 1217 int resizeMode = mSoftInputMode & 1218 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST; 1219 // If we are in auto resize mode, then we need to determine 1220 // what mode to use now. 1221 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 1222 final int N = attachInfo.mScrollContainers.size(); 1223 for (int i=0; i<N; i++) { 1224 if (attachInfo.mScrollContainers.get(i).isShown()) { 1225 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; 1226 } 1227 } 1228 if (resizeMode == 0) { 1229 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN; 1230 } 1231 if ((lp.softInputMode & 1232 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) { 1233 lp.softInputMode = (lp.softInputMode & 1234 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) | 1235 resizeMode; 1236 params = lp; 1237 } 1238 } 1239 } 1240 1241 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) { 1242 if (!PixelFormat.formatHasAlpha(params.format)) { 1243 params.format = PixelFormat.TRANSLUCENT; 1244 } 1245 } 1246 1247 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange 1248 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) 1249 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT && 1250 frame.width() < desiredWindowWidth && frame.width() != mWidth) 1251 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT && 1252 frame.height() < desiredWindowHeight && frame.height() != mHeight)); 1253 1254 final boolean computesInternalInsets = 1255 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners(); 1256 1257 boolean insetsPending = false; 1258 int relayoutResult = 0; 1259 1260 if (mFirst || windowShouldResize || insetsChanged || 1261 viewVisibilityChanged || params != null) { 1262 1263 if (viewVisibility == View.VISIBLE) { 1264 // If this window is giving internal insets to the window 1265 // manager, and it is being added or changing its visibility, 1266 // then we want to first give the window manager "fake" 1267 // insets to cause it to effectively ignore the content of 1268 // the window during layout. This avoids it briefly causing 1269 // other windows to resize/move based on the raw frame of the 1270 // window, waiting until we can finish laying out this window 1271 // and get back to the window manager with the ultimately 1272 // computed insets. 1273 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged); 1274 } 1275 1276 if (mSurfaceHolder != null) { 1277 mSurfaceHolder.mSurfaceLock.lock(); 1278 mDrawingAllowed = true; 1279 } 1280 1281 boolean hwInitialized = false; 1282 boolean contentInsetsChanged = false; 1283 boolean visibleInsetsChanged; 1284 boolean hadSurface = mSurface.isValid(); 1285 1286 try { 1287 int fl = 0; 1288 if (params != null) { 1289 fl = params.flags; 1290 if (attachInfo.mKeepScreenOn) { 1291 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 1292 } 1293 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility; 1294 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners; 1295 } 1296 if (DEBUG_LAYOUT) { 1297 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" + 1298 host.getMeasuredHeight() + ", params=" + params); 1299 } 1300 1301 final int surfaceGenerationId = mSurface.getGenerationId(); 1302 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending); 1303 1304 if (params != null) { 1305 params.flags = fl; 1306 } 1307 1308 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString() 1309 + " content=" + mPendingContentInsets.toShortString() 1310 + " visible=" + mPendingVisibleInsets.toShortString() 1311 + " surface=" + mSurface); 1312 1313 if (mPendingConfiguration.seq != 0) { 1314 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: " 1315 + mPendingConfiguration); 1316 updateConfiguration(mPendingConfiguration, !mFirst); 1317 mPendingConfiguration.seq = 0; 1318 } 1319 1320 contentInsetsChanged = !mPendingContentInsets.equals( 1321 mAttachInfo.mContentInsets); 1322 visibleInsetsChanged = !mPendingVisibleInsets.equals( 1323 mAttachInfo.mVisibleInsets); 1324 if (contentInsetsChanged) { 1325 if (mWidth > 0 && mHeight > 0 && 1326 mSurface != null && mSurface.isValid() && 1327 !mAttachInfo.mTurnOffWindowResizeAnim && 1328 mAttachInfo.mHardwareRenderer != null && 1329 mAttachInfo.mHardwareRenderer.isEnabled() && 1330 mAttachInfo.mHardwareRenderer.validate() && 1331 lp != null && !PixelFormat.formatHasAlpha(lp.format)) { 1332 1333 disposeResizeBuffer(); 1334 1335 boolean completed = false; 1336 HardwareCanvas hwRendererCanvas = mAttachInfo.mHardwareRenderer.getCanvas(); 1337 HardwareCanvas layerCanvas = null; 1338 try { 1339 if (mResizeBuffer == null) { 1340 mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 1341 mWidth, mHeight, false); 1342 } else if (mResizeBuffer.getWidth() != mWidth || 1343 mResizeBuffer.getHeight() != mHeight) { 1344 mResizeBuffer.resize(mWidth, mHeight); 1345 } 1346 layerCanvas = mResizeBuffer.start(hwRendererCanvas); 1347 layerCanvas.setViewport(mWidth, mHeight); 1348 layerCanvas.onPreDraw(null); 1349 final int restoreCount = layerCanvas.save(); 1350 1351 layerCanvas.drawColor(0xff000000, PorterDuff.Mode.SRC); 1352 1353 int yoff; 1354 final boolean scrolling = mScroller != null 1355 && mScroller.computeScrollOffset(); 1356 if (scrolling) { 1357 yoff = mScroller.getCurrY(); 1358 mScroller.abortAnimation(); 1359 } else { 1360 yoff = mScrollY; 1361 } 1362 1363 layerCanvas.translate(0, -yoff); 1364 if (mTranslator != null) { 1365 mTranslator.translateCanvas(layerCanvas); 1366 } 1367 1368 mView.draw(layerCanvas); 1369 1370 mResizeBufferStartTime = SystemClock.uptimeMillis(); 1371 mResizeBufferDuration = mView.getResources().getInteger( 1372 com.android.internal.R.integer.config_mediumAnimTime); 1373 completed = true; 1374 1375 layerCanvas.restoreToCount(restoreCount); 1376 } catch (OutOfMemoryError e) { 1377 Log.w(TAG, "Not enough memory for content change anim buffer", e); 1378 } finally { 1379 if (layerCanvas != null) { 1380 layerCanvas.onPostDraw(); 1381 } 1382 if (mResizeBuffer != null) { 1383 mResizeBuffer.end(hwRendererCanvas); 1384 if (!completed) { 1385 mResizeBuffer.destroy(); 1386 mResizeBuffer = null; 1387 } 1388 } 1389 } 1390 } 1391 mAttachInfo.mContentInsets.set(mPendingContentInsets); 1392 host.fitSystemWindows(mAttachInfo.mContentInsets); 1393 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: " 1394 + mAttachInfo.mContentInsets); 1395 } 1396 if (visibleInsetsChanged) { 1397 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1398 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1399 + mAttachInfo.mVisibleInsets); 1400 } 1401 1402 if (!hadSurface) { 1403 if (mSurface.isValid()) { 1404 // If we are creating a new surface, then we need to 1405 // completely redraw it. Also, when we get to the 1406 // point of drawing it we will hold off and schedule 1407 // a new traversal instead. This is so we can tell the 1408 // window manager about all of the windows being displayed 1409 // before actually drawing them, so it can display then 1410 // all at once. 1411 newSurface = true; 1412 mFullRedrawNeeded = true; 1413 mPreviousTransparentRegion.setEmpty(); 1414 1415 if (mAttachInfo.mHardwareRenderer != null) { 1416 try { 1417 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder); 1418 } catch (Surface.OutOfResourcesException e) { 1419 Log.e(TAG, "OutOfResourcesException initializing HW surface", e); 1420 try { 1421 if (!sWindowSession.outOfMemory(mWindow)) { 1422 Slog.w(TAG, "No processes killed for memory; killing self"); 1423 Process.killProcess(Process.myPid()); 1424 } 1425 } catch (RemoteException ex) { 1426 } 1427 mLayoutRequested = true; // ask wm for a new surface next time. 1428 return; 1429 } 1430 } 1431 } 1432 } else if (!mSurface.isValid()) { 1433 // If the surface has been removed, then reset the scroll 1434 // positions. 1435 mLastScrolledFocus = null; 1436 mScrollY = mCurScrollY = 0; 1437 if (mScroller != null) { 1438 mScroller.abortAnimation(); 1439 } 1440 disposeResizeBuffer(); 1441 // Our surface is gone 1442 if (mAttachInfo.mHardwareRenderer != null && 1443 mAttachInfo.mHardwareRenderer.isEnabled()) { 1444 mAttachInfo.mHardwareRenderer.destroy(true); 1445 } 1446 } else if (surfaceGenerationId != mSurface.getGenerationId() && 1447 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) { 1448 mFullRedrawNeeded = true; 1449 try { 1450 mAttachInfo.mHardwareRenderer.updateSurface(mHolder); 1451 } catch (Surface.OutOfResourcesException e) { 1452 Log.e(TAG, "OutOfResourcesException updating HW surface", e); 1453 try { 1454 if (!sWindowSession.outOfMemory(mWindow)) { 1455 Slog.w(TAG, "No processes killed for memory; killing self"); 1456 Process.killProcess(Process.myPid()); 1457 } 1458 } catch (RemoteException ex) { 1459 } 1460 mLayoutRequested = true; // ask wm for a new surface next time. 1461 return; 1462 } 1463 } 1464 } catch (RemoteException e) { 1465 } 1466 1467 if (DEBUG_ORIENTATION) Log.v( 1468 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface); 1469 1470 attachInfo.mWindowLeft = frame.left; 1471 attachInfo.mWindowTop = frame.top; 1472 1473 // !!FIXME!! This next section handles the case where we did not get the 1474 // window size we asked for. We should avoid this by getting a maximum size from 1475 // the window session beforehand. 1476 mWidth = frame.width(); 1477 mHeight = frame.height(); 1478 1479 if (mSurfaceHolder != null) { 1480 // The app owns the surface; tell it about what is going on. 1481 if (mSurface.isValid()) { 1482 // XXX .copyFrom() doesn't work! 1483 //mSurfaceHolder.mSurface.copyFrom(mSurface); 1484 mSurfaceHolder.mSurface = mSurface; 1485 } 1486 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight); 1487 mSurfaceHolder.mSurfaceLock.unlock(); 1488 if (mSurface.isValid()) { 1489 if (!hadSurface) { 1490 mSurfaceHolder.ungetCallbacks(); 1491 1492 mIsCreating = true; 1493 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder); 1494 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1495 if (callbacks != null) { 1496 for (SurfaceHolder.Callback c : callbacks) { 1497 c.surfaceCreated(mSurfaceHolder); 1498 } 1499 } 1500 surfaceChanged = true; 1501 } 1502 if (surfaceChanged) { 1503 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder, 1504 lp.format, mWidth, mHeight); 1505 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1506 if (callbacks != null) { 1507 for (SurfaceHolder.Callback c : callbacks) { 1508 c.surfaceChanged(mSurfaceHolder, lp.format, 1509 mWidth, mHeight); 1510 } 1511 } 1512 } 1513 mIsCreating = false; 1514 } else if (hadSurface) { 1515 mSurfaceHolder.ungetCallbacks(); 1516 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1517 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder); 1518 if (callbacks != null) { 1519 for (SurfaceHolder.Callback c : callbacks) { 1520 c.surfaceDestroyed(mSurfaceHolder); 1521 } 1522 } 1523 mSurfaceHolder.mSurfaceLock.lock(); 1524 try { 1525 mSurfaceHolder.mSurface = new Surface(); 1526 } finally { 1527 mSurfaceHolder.mSurfaceLock.unlock(); 1528 } 1529 } 1530 } 1531 1532 if (mAttachInfo.mHardwareRenderer != null && 1533 mAttachInfo.mHardwareRenderer.isEnabled()) { 1534 if (hwInitialized || windowShouldResize || 1535 mWidth != mAttachInfo.mHardwareRenderer.getWidth() || 1536 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) { 1537 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight); 1538 if (!hwInitialized) { 1539 mAttachInfo.mHardwareRenderer.invalidate(mHolder); 1540 } 1541 } 1542 } 1543 1544 if (!mStopped) { 1545 boolean focusChangedDueToTouchMode = ensureTouchModeLocally( 1546 (relayoutResult&WindowManagerImpl.RELAYOUT_RES_IN_TOUCH_MODE) != 0); 1547 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth() 1548 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) { 1549 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); 1550 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height); 1551 1552 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth=" 1553 + mWidth + " measuredWidth=" + host.getMeasuredWidth() 1554 + " mHeight=" + mHeight 1555 + " measuredHeight=" + host.getMeasuredHeight() 1556 + " coveredInsetsChanged=" + contentInsetsChanged); 1557 1558 // Ask host how big it wants to be 1559 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1560 1561 // Implementation of weights from WindowManager.LayoutParams 1562 // We just grow the dimensions as needed and re-measure if 1563 // needs be 1564 int width = host.getMeasuredWidth(); 1565 int height = host.getMeasuredHeight(); 1566 boolean measureAgain = false; 1567 1568 if (lp.horizontalWeight > 0.0f) { 1569 width += (int) ((mWidth - width) * lp.horizontalWeight); 1570 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, 1571 MeasureSpec.EXACTLY); 1572 measureAgain = true; 1573 } 1574 if (lp.verticalWeight > 0.0f) { 1575 height += (int) ((mHeight - height) * lp.verticalWeight); 1576 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, 1577 MeasureSpec.EXACTLY); 1578 measureAgain = true; 1579 } 1580 1581 if (measureAgain) { 1582 if (DEBUG_LAYOUT) Log.v(TAG, 1583 "And hey let's measure once more: width=" + width 1584 + " height=" + height); 1585 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1586 } 1587 1588 mLayoutRequested = true; 1589 } 1590 } 1591 } 1592 1593 final boolean didLayout = mLayoutRequested && !mStopped; 1594 boolean triggerGlobalLayoutListener = didLayout 1595 || attachInfo.mRecomputeGlobalAttributes; 1596 if (didLayout) { 1597 mLayoutRequested = false; 1598 mScrollMayChange = true; 1599 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v( 1600 TAG, "Laying out " + host + " to (" + 1601 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")"); 1602 long startTime = 0L; 1603 if (ViewDebug.DEBUG_PROFILE_LAYOUT) { 1604 startTime = SystemClock.elapsedRealtime(); 1605 } 1606 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 1607 1608 if (false && ViewDebug.consistencyCheckEnabled) { 1609 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) { 1610 throw new IllegalStateException("The view hierarchy is an inconsistent state," 1611 + "please refer to the logs with the tag " 1612 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation."); 1613 } 1614 } 1615 1616 if (ViewDebug.DEBUG_PROFILE_LAYOUT) { 1617 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime); 1618 } 1619 1620 // By this point all views have been sized and positionned 1621 // We can compute the transparent area 1622 1623 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) { 1624 // start out transparent 1625 // TODO: AVOID THAT CALL BY CACHING THE RESULT? 1626 host.getLocationInWindow(mTmpLocation); 1627 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1], 1628 mTmpLocation[0] + host.mRight - host.mLeft, 1629 mTmpLocation[1] + host.mBottom - host.mTop); 1630 1631 host.gatherTransparentRegion(mTransparentRegion); 1632 if (mTranslator != null) { 1633 mTranslator.translateRegionInWindowToScreen(mTransparentRegion); 1634 } 1635 1636 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) { 1637 mPreviousTransparentRegion.set(mTransparentRegion); 1638 // reconfigure window manager 1639 try { 1640 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion); 1641 } catch (RemoteException e) { 1642 } 1643 } 1644 } 1645 1646 if (DBG) { 1647 System.out.println("======================================"); 1648 System.out.println("performTraversals -- after setFrame"); 1649 host.debug(); 1650 } 1651 } 1652 1653 if (triggerGlobalLayoutListener) { 1654 attachInfo.mRecomputeGlobalAttributes = false; 1655 attachInfo.mTreeObserver.dispatchOnGlobalLayout(); 1656 1657 if (AccessibilityManager.getInstance(host.mContext).isEnabled()) { 1658 postSendWindowContentChangedCallback(); 1659 } 1660 } 1661 1662 if (computesInternalInsets) { 1663 // Clear the original insets. 1664 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets; 1665 insets.reset(); 1666 1667 // Compute new insets in place. 1668 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets); 1669 1670 // Tell the window manager. 1671 if (insetsPending || !mLastGivenInsets.equals(insets)) { 1672 mLastGivenInsets.set(insets); 1673 1674 // Translate insets to screen coordinates if needed. 1675 final Rect contentInsets; 1676 final Rect visibleInsets; 1677 final Region touchableRegion; 1678 if (mTranslator != null) { 1679 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets); 1680 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets); 1681 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion); 1682 } else { 1683 contentInsets = insets.contentInsets; 1684 visibleInsets = insets.visibleInsets; 1685 touchableRegion = insets.touchableRegion; 1686 } 1687 1688 try { 1689 sWindowSession.setInsets(mWindow, insets.mTouchableInsets, 1690 contentInsets, visibleInsets, touchableRegion); 1691 } catch (RemoteException e) { 1692 } 1693 } 1694 } 1695 1696 if (mFirst) { 1697 // handle first focus request 1698 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()=" 1699 + mView.hasFocus()); 1700 if (mView != null) { 1701 if (!mView.hasFocus()) { 1702 mView.requestFocus(View.FOCUS_FORWARD); 1703 mFocusedView = mRealFocusedView = mView.findFocus(); 1704 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view=" 1705 + mFocusedView); 1706 } else { 1707 mRealFocusedView = mView.findFocus(); 1708 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view=" 1709 + mRealFocusedView); 1710 } 1711 } 1712 } 1713 1714 mFirst = false; 1715 mWillDrawSoon = false; 1716 mNewSurfaceNeeded = false; 1717 mViewVisibility = viewVisibility; 1718 1719 if (mAttachInfo.mHasWindowFocus) { 1720 final boolean imTarget = WindowManager.LayoutParams 1721 .mayUseInputMethod(mWindowAttributes.flags); 1722 if (imTarget != mLastWasImTarget) { 1723 mLastWasImTarget = imTarget; 1724 InputMethodManager imm = InputMethodManager.peekInstance(); 1725 if (imm != null && imTarget) { 1726 imm.startGettingWindowFocus(mView); 1727 imm.onWindowFocus(mView, mView.findFocus(), 1728 mWindowAttributes.softInputMode, 1729 !mHasHadWindowFocus, mWindowAttributes.flags); 1730 } 1731 } 1732 } 1733 1734 // Remember if we must report the next draw. 1735 if ((relayoutResult & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) { 1736 mReportNextDraw = true; 1737 } 1738 1739 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() || 1740 viewVisibility != View.VISIBLE; 1741 1742 if (!cancelDraw && !newSurface) { 1743 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1744 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1745 mPendingTransitions.get(i).startChangingAnimations(); 1746 } 1747 mPendingTransitions.clear(); 1748 } 1749 1750 performDraw(); 1751 } else { 1752 // End any pending transitions on this non-visible window 1753 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1754 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1755 mPendingTransitions.get(i).endChangingAnimations(); 1756 } 1757 mPendingTransitions.clear(); 1758 } 1759 1760 if (viewVisibility == View.VISIBLE) { 1761 // Try again 1762 scheduleTraversals(); 1763 } 1764 } 1765 } 1766 1767 public void requestTransparentRegion(View child) { 1768 // the test below should not fail unless someone is messing with us 1769 checkThread(); 1770 if (mView == child) { 1771 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS; 1772 // Need to make sure we re-evaluate the window attributes next 1773 // time around, to ensure the window has the correct format. 1774 mWindowAttributesChanged = true; 1775 mWindowAttributesChangesFlag = 0; 1776 requestLayout(); 1777 } 1778 } 1779 1780 /** 1781 * Figures out the measure spec for the root view in a window based on it's 1782 * layout params. 1783 * 1784 * @param windowSize 1785 * The available width or height of the window 1786 * 1787 * @param rootDimension 1788 * The layout params for one dimension (width or height) of the 1789 * window. 1790 * 1791 * @return The measure spec to use to measure the root view. 1792 */ 1793 private int getRootMeasureSpec(int windowSize, int rootDimension) { 1794 int measureSpec; 1795 switch (rootDimension) { 1796 1797 case ViewGroup.LayoutParams.MATCH_PARENT: 1798 // Window can't resize. Force root view to be windowSize. 1799 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); 1800 break; 1801 case ViewGroup.LayoutParams.WRAP_CONTENT: 1802 // Window can resize. Set max size for root view. 1803 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST); 1804 break; 1805 default: 1806 // Window wants to be an exact size. Force root view to be that size. 1807 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY); 1808 break; 1809 } 1810 return measureSpec; 1811 } 1812 1813 int mHardwareYOffset; 1814 int mResizeAlpha; 1815 final Paint mResizePaint = new Paint(); 1816 1817 public void onHardwarePreDraw(HardwareCanvas canvas) { 1818 canvas.translate(0, -mHardwareYOffset); 1819 } 1820 1821 public void onHardwarePostDraw(HardwareCanvas canvas) { 1822 if (mResizeBuffer != null) { 1823 mResizePaint.setAlpha(mResizeAlpha); 1824 canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint); 1825 } 1826 } 1827 1828 /** 1829 * @hide 1830 */ 1831 void outputDisplayList(View view) { 1832 if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) { 1833 DisplayList displayList = view.getDisplayList(); 1834 if (displayList != null) { 1835 mAttachInfo.mHardwareCanvas.outputDisplayList(displayList); 1836 } 1837 } 1838 } 1839 1840 /** 1841 * @see #PROPERTY_PROFILE_RENDERING 1842 */ 1843 private void profileRendering(boolean enabled) { 1844 if (mProfileRendering) { 1845 mRenderProfilingEnabled = enabled; 1846 if (mRenderProfiler == null) { 1847 mRenderProfiler = new Thread(new Runnable() { 1848 @Override 1849 public void run() { 1850 Log.d(TAG, "Starting profiling thread"); 1851 while (mRenderProfilingEnabled) { 1852 mAttachInfo.mHandler.post(new Runnable() { 1853 @Override 1854 public void run() { 1855 mDirty.set(0, 0, mWidth, mHeight); 1856 scheduleTraversals(); 1857 } 1858 }); 1859 try { 1860 // TODO: This should use vsync when we get an API 1861 Thread.sleep(15); 1862 } catch (InterruptedException e) { 1863 Log.d(TAG, "Exiting profiling thread"); 1864 } 1865 } 1866 } 1867 }, "Rendering Profiler"); 1868 mRenderProfiler.start(); 1869 } else { 1870 mRenderProfiler.interrupt(); 1871 mRenderProfiler = null; 1872 } 1873 } 1874 } 1875 1876 /** 1877 * Called from draw() when DEBUG_FPS is enabled 1878 */ 1879 private void trackFPS() { 1880 // Tracks frames per second drawn. First value in a series of draws may be bogus 1881 // because it down not account for the intervening idle time 1882 long nowTime = System.currentTimeMillis(); 1883 if (mFpsStartTime < 0) { 1884 mFpsStartTime = mFpsPrevTime = nowTime; 1885 mFpsNumFrames = 0; 1886 } else { 1887 ++mFpsNumFrames; 1888 String thisHash = Integer.toHexString(System.identityHashCode(this)); 1889 long frameTime = nowTime - mFpsPrevTime; 1890 long totalTime = nowTime - mFpsStartTime; 1891 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime); 1892 mFpsPrevTime = nowTime; 1893 if (totalTime > 1000) { 1894 float fps = (float) mFpsNumFrames * 1000 / totalTime; 1895 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps); 1896 mFpsStartTime = nowTime; 1897 mFpsNumFrames = 0; 1898 } 1899 } 1900 } 1901 1902 private void performDraw() { 1903 if (!mAttachInfo.mScreenOn) return; 1904 1905 final long drawStartTime; 1906 if (ViewDebug.DEBUG_LATENCY) { 1907 drawStartTime = System.nanoTime(); 1908 if (mLastDrawFinishedTimeNanos != 0) { 1909 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting draw(); it has been " 1910 + ((drawStartTime - mLastDrawFinishedTimeNanos) * 0.000001f) 1911 + "ms since the last draw finished."); 1912 } else { 1913 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting draw()."); 1914 } 1915 } 1916 1917 final boolean fullRedrawNeeded = mFullRedrawNeeded; 1918 mFullRedrawNeeded = false; 1919 draw(fullRedrawNeeded); 1920 1921 if (ViewDebug.DEBUG_LATENCY) { 1922 long now = System.nanoTime(); 1923 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "performDraw() took " 1924 + ((now - drawStartTime) * 0.000001f) 1925 + "ms."); 1926 mLastDrawFinishedTimeNanos = now; 1927 } 1928 1929 if (mReportNextDraw) { 1930 mReportNextDraw = false; 1931 1932 if (LOCAL_LOGV) { 1933 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle()); 1934 } 1935 if (mSurfaceHolder != null && mSurface.isValid()) { 1936 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder); 1937 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1938 if (callbacks != null) { 1939 for (SurfaceHolder.Callback c : callbacks) { 1940 if (c instanceof SurfaceHolder.Callback2) { 1941 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 1942 mSurfaceHolder); 1943 } 1944 } 1945 } 1946 } 1947 try { 1948 sWindowSession.finishDrawing(mWindow); 1949 } catch (RemoteException e) { 1950 } 1951 } 1952 } 1953 1954 private void draw(boolean fullRedrawNeeded) { 1955 Surface surface = mSurface; 1956 if (surface == null || !surface.isValid()) { 1957 return; 1958 } 1959 1960 if (DEBUG_FPS) { 1961 trackFPS(); 1962 } 1963 1964 if (!sFirstDrawComplete) { 1965 synchronized (sFirstDrawHandlers) { 1966 sFirstDrawComplete = true; 1967 final int count = sFirstDrawHandlers.size(); 1968 for (int i = 0; i< count; i++) { 1969 mHandler.post(sFirstDrawHandlers.get(i)); 1970 } 1971 } 1972 } 1973 1974 scrollToRectOrFocus(null, false); 1975 1976 if (mAttachInfo.mViewScrollChanged) { 1977 mAttachInfo.mViewScrollChanged = false; 1978 mAttachInfo.mTreeObserver.dispatchOnScrollChanged(); 1979 } 1980 1981 int yoff; 1982 boolean animating = mScroller != null && mScroller.computeScrollOffset(); 1983 if (animating) { 1984 yoff = mScroller.getCurrY(); 1985 } else { 1986 yoff = mScrollY; 1987 } 1988 if (mCurScrollY != yoff) { 1989 mCurScrollY = yoff; 1990 fullRedrawNeeded = true; 1991 } 1992 1993 final float appScale = mAttachInfo.mApplicationScale; 1994 final boolean scalingRequired = mAttachInfo.mScalingRequired; 1995 1996 int resizeAlpha = 0; 1997 if (mResizeBuffer != null) { 1998 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime; 1999 if (deltaTime < mResizeBufferDuration) { 2000 float amt = deltaTime/(float) mResizeBufferDuration; 2001 amt = mResizeInterpolator.getInterpolation(amt); 2002 animating = true; 2003 resizeAlpha = 255 - (int)(amt*255); 2004 } else { 2005 disposeResizeBuffer(); 2006 } 2007 } 2008 2009 final Rect dirty = mDirty; 2010 if (mSurfaceHolder != null) { 2011 // The app owns the surface, we won't draw. 2012 dirty.setEmpty(); 2013 if (animating) { 2014 if (mScroller != null) { 2015 mScroller.abortAnimation(); 2016 } 2017 disposeResizeBuffer(); 2018 } 2019 return; 2020 } 2021 2022 if (fullRedrawNeeded) { 2023 mAttachInfo.mIgnoreDirtyState = true; 2024 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 2025 } 2026 2027 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2028 Log.v(TAG, "Draw " + mView + "/" 2029 + mWindowAttributes.getTitle() 2030 + ": dirty={" + dirty.left + "," + dirty.top 2031 + "," + dirty.right + "," + dirty.bottom + "} surface=" 2032 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" + 2033 appScale + ", width=" + mWidth + ", height=" + mHeight); 2034 } 2035 2036 if (!dirty.isEmpty() || mIsAnimating) { 2037 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 2038 // Draw with hardware renderer. 2039 mIsAnimating = false; 2040 mHardwareYOffset = yoff; 2041 mResizeAlpha = resizeAlpha; 2042 2043 mCurrentDirty.set(dirty); 2044 mCurrentDirty.union(mPreviousDirty); 2045 mPreviousDirty.set(dirty); 2046 dirty.setEmpty(); 2047 2048 if (mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, 2049 animating ? null : mCurrentDirty)) { 2050 mPreviousDirty.set(0, 0, mWidth, mHeight); 2051 } 2052 } else { 2053 // Draw with software renderer. 2054 Canvas canvas; 2055 try { 2056 int left = dirty.left; 2057 int top = dirty.top; 2058 int right = dirty.right; 2059 int bottom = dirty.bottom; 2060 2061 final long lockCanvasStartTime; 2062 if (ViewDebug.DEBUG_LATENCY) { 2063 lockCanvasStartTime = System.nanoTime(); 2064 } 2065 2066 canvas = mSurface.lockCanvas(dirty); 2067 2068 if (ViewDebug.DEBUG_LATENCY) { 2069 long now = System.nanoTime(); 2070 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- lockCanvas() took " 2071 + ((now - lockCanvasStartTime) * 0.000001f) + "ms"); 2072 } 2073 2074 if (left != dirty.left || top != dirty.top || right != dirty.right || 2075 bottom != dirty.bottom) { 2076 mAttachInfo.mIgnoreDirtyState = true; 2077 } 2078 2079 // TODO: Do this in native 2080 canvas.setDensity(mDensity); 2081 } catch (Surface.OutOfResourcesException e) { 2082 Log.e(TAG, "OutOfResourcesException locking surface", e); 2083 try { 2084 if (!sWindowSession.outOfMemory(mWindow)) { 2085 Slog.w(TAG, "No processes killed for memory; killing self"); 2086 Process.killProcess(Process.myPid()); 2087 } 2088 } catch (RemoteException ex) { 2089 } 2090 mLayoutRequested = true; // ask wm for a new surface next time. 2091 return; 2092 } catch (IllegalArgumentException e) { 2093 Log.e(TAG, "IllegalArgumentException locking surface", e); 2094 // Don't assume this is due to out of memory, it could be 2095 // something else, and if it is something else then we could 2096 // kill stuff (or ourself) for no reason. 2097 mLayoutRequested = true; // ask wm for a new surface next time. 2098 return; 2099 } 2100 2101 try { 2102 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2103 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2104 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2105 //canvas.drawARGB(255, 255, 0, 0); 2106 } 2107 2108 long startTime = 0L; 2109 if (ViewDebug.DEBUG_PROFILE_DRAWING) { 2110 startTime = SystemClock.elapsedRealtime(); 2111 } 2112 2113 // If this bitmap's format includes an alpha channel, we 2114 // need to clear it before drawing so that the child will 2115 // properly re-composite its drawing on a transparent 2116 // background. This automatically respects the clip/dirty region 2117 // or 2118 // If we are applying an offset, we need to clear the area 2119 // where the offset doesn't appear to avoid having garbage 2120 // left in the blank areas. 2121 if (!canvas.isOpaque() || yoff != 0) { 2122 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2123 } 2124 2125 dirty.setEmpty(); 2126 mIsAnimating = false; 2127 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis(); 2128 mView.mPrivateFlags |= View.DRAWN; 2129 2130 if (DEBUG_DRAW) { 2131 Context cxt = mView.getContext(); 2132 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2133 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2134 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2135 } 2136 try { 2137 canvas.translate(0, -yoff); 2138 if (mTranslator != null) { 2139 mTranslator.translateCanvas(canvas); 2140 } 2141 canvas.setScreenDensity(scalingRequired 2142 ? DisplayMetrics.DENSITY_DEVICE : 0); 2143 mAttachInfo.mSetIgnoreDirtyState = false; 2144 2145 final long drawStartTime; 2146 if (ViewDebug.DEBUG_LATENCY) { 2147 drawStartTime = System.nanoTime(); 2148 } 2149 2150 mView.draw(canvas); 2151 2152 if (ViewDebug.DEBUG_LATENCY) { 2153 long now = System.nanoTime(); 2154 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- draw() took " 2155 + ((now - drawStartTime) * 0.000001f) + "ms"); 2156 } 2157 } finally { 2158 if (!mAttachInfo.mSetIgnoreDirtyState) { 2159 // Only clear the flag if it was not set during the mView.draw() call 2160 mAttachInfo.mIgnoreDirtyState = false; 2161 } 2162 } 2163 2164 if (false && ViewDebug.consistencyCheckEnabled) { 2165 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING); 2166 } 2167 2168 if (ViewDebug.DEBUG_PROFILE_DRAWING) { 2169 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime); 2170 } 2171 } finally { 2172 final long unlockCanvasAndPostStartTime; 2173 if (ViewDebug.DEBUG_LATENCY) { 2174 unlockCanvasAndPostStartTime = System.nanoTime(); 2175 } 2176 2177 surface.unlockCanvasAndPost(canvas); 2178 2179 if (ViewDebug.DEBUG_LATENCY) { 2180 long now = System.nanoTime(); 2181 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- unlockCanvasAndPost() took " 2182 + ((now - unlockCanvasAndPostStartTime) * 0.000001f) + "ms"); 2183 } 2184 2185 if (LOCAL_LOGV) { 2186 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2187 } 2188 } 2189 } 2190 } 2191 2192 if (animating) { 2193 mFullRedrawNeeded = true; 2194 scheduleTraversals(); 2195 } 2196 } 2197 2198 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2199 final View.AttachInfo attachInfo = mAttachInfo; 2200 final Rect ci = attachInfo.mContentInsets; 2201 final Rect vi = attachInfo.mVisibleInsets; 2202 int scrollY = 0; 2203 boolean handled = false; 2204 2205 if (vi.left > ci.left || vi.top > ci.top 2206 || vi.right > ci.right || vi.bottom > ci.bottom) { 2207 // We'll assume that we aren't going to change the scroll 2208 // offset, since we want to avoid that unless it is actually 2209 // going to make the focus visible... otherwise we scroll 2210 // all over the place. 2211 scrollY = mScrollY; 2212 // We can be called for two different situations: during a draw, 2213 // to update the scroll position if the focus has changed (in which 2214 // case 'rectangle' is null), or in response to a 2215 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2216 // is non-null and we just want to scroll to whatever that 2217 // rectangle is). 2218 View focus = mRealFocusedView; 2219 2220 // When in touch mode, focus points to the previously focused view, 2221 // which may have been removed from the view hierarchy. The following 2222 // line checks whether the view is still in our hierarchy. 2223 if (focus == null || focus.mAttachInfo != mAttachInfo) { 2224 mRealFocusedView = null; 2225 return false; 2226 } 2227 2228 if (focus != mLastScrolledFocus) { 2229 // If the focus has changed, then ignore any requests to scroll 2230 // to a rectangle; first we want to make sure the entire focus 2231 // view is visible. 2232 rectangle = null; 2233 } 2234 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2235 + " rectangle=" + rectangle + " ci=" + ci 2236 + " vi=" + vi); 2237 if (focus == mLastScrolledFocus && !mScrollMayChange 2238 && rectangle == null) { 2239 // Optimization: if the focus hasn't changed since last 2240 // time, and no layout has happened, then just leave things 2241 // as they are. 2242 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2243 + mScrollY + " vi=" + vi.toShortString()); 2244 } else if (focus != null) { 2245 // We need to determine if the currently focused view is 2246 // within the visible part of the window and, if not, apply 2247 // a pan so it can be seen. 2248 mLastScrolledFocus = focus; 2249 mScrollMayChange = false; 2250 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2251 // Try to find the rectangle from the focus view. 2252 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2253 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2254 + mView.getWidth() + " h=" + mView.getHeight() 2255 + " ci=" + ci.toShortString() 2256 + " vi=" + vi.toShortString()); 2257 if (rectangle == null) { 2258 focus.getFocusedRect(mTempRect); 2259 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2260 + ": focusRect=" + mTempRect.toShortString()); 2261 if (mView instanceof ViewGroup) { 2262 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2263 focus, mTempRect); 2264 } 2265 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2266 "Focus in window: focusRect=" 2267 + mTempRect.toShortString() 2268 + " visRect=" + mVisRect.toShortString()); 2269 } else { 2270 mTempRect.set(rectangle); 2271 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2272 "Request scroll to rect: " 2273 + mTempRect.toShortString() 2274 + " visRect=" + mVisRect.toShortString()); 2275 } 2276 if (mTempRect.intersect(mVisRect)) { 2277 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2278 "Focus window visible rect: " 2279 + mTempRect.toShortString()); 2280 if (mTempRect.height() > 2281 (mView.getHeight()-vi.top-vi.bottom)) { 2282 // If the focus simply is not going to fit, then 2283 // best is probably just to leave things as-is. 2284 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2285 "Too tall; leaving scrollY=" + scrollY); 2286 } else if ((mTempRect.top-scrollY) < vi.top) { 2287 scrollY -= vi.top - (mTempRect.top-scrollY); 2288 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2289 "Top covered; scrollY=" + scrollY); 2290 } else if ((mTempRect.bottom-scrollY) 2291 > (mView.getHeight()-vi.bottom)) { 2292 scrollY += (mTempRect.bottom-scrollY) 2293 - (mView.getHeight()-vi.bottom); 2294 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2295 "Bottom covered; scrollY=" + scrollY); 2296 } 2297 handled = true; 2298 } 2299 } 2300 } 2301 } 2302 2303 if (scrollY != mScrollY) { 2304 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2305 + mScrollY + " , new=" + scrollY); 2306 if (!immediate && mResizeBuffer == null) { 2307 if (mScroller == null) { 2308 mScroller = new Scroller(mView.getContext()); 2309 } 2310 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2311 } else if (mScroller != null) { 2312 mScroller.abortAnimation(); 2313 } 2314 mScrollY = scrollY; 2315 } 2316 2317 return handled; 2318 } 2319 2320 public void requestChildFocus(View child, View focused) { 2321 checkThread(); 2322 2323 if (DEBUG_INPUT_RESIZE) { 2324 Log.v(TAG, "Request child focus: focus now " + focused); 2325 } 2326 2327 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused); 2328 scheduleTraversals(); 2329 2330 mFocusedView = mRealFocusedView = focused; 2331 } 2332 2333 public void clearChildFocus(View child) { 2334 checkThread(); 2335 2336 if (DEBUG_INPUT_RESIZE) { 2337 Log.v(TAG, "Clearing child focus"); 2338 } 2339 2340 mOldFocusedView = mFocusedView; 2341 2342 // Invoke the listener only if there is no view to take focus 2343 if (focusSearch(null, View.FOCUS_FORWARD) == null) { 2344 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null); 2345 } 2346 2347 mFocusedView = mRealFocusedView = null; 2348 } 2349 2350 public void focusableViewAvailable(View v) { 2351 checkThread(); 2352 2353 if (mView != null) { 2354 if (!mView.hasFocus()) { 2355 v.requestFocus(); 2356 } else { 2357 // the one case where will transfer focus away from the current one 2358 // is if the current view is a view group that prefers to give focus 2359 // to its children first AND the view is a descendant of it. 2360 mFocusedView = mView.findFocus(); 2361 boolean descendantsHaveDibsOnFocus = 2362 (mFocusedView instanceof ViewGroup) && 2363 (((ViewGroup) mFocusedView).getDescendantFocusability() == 2364 ViewGroup.FOCUS_AFTER_DESCENDANTS); 2365 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) { 2366 // If a view gets the focus, the listener will be invoked from requestChildFocus() 2367 v.requestFocus(); 2368 } 2369 } 2370 } 2371 } 2372 2373 public void recomputeViewAttributes(View child) { 2374 checkThread(); 2375 if (mView == child) { 2376 mAttachInfo.mRecomputeGlobalAttributes = true; 2377 if (!mWillDrawSoon) { 2378 scheduleTraversals(); 2379 } 2380 } 2381 } 2382 2383 void dispatchDetachedFromWindow() { 2384 if (mView != null && mView.mAttachInfo != null) { 2385 if (mAttachInfo.mHardwareRenderer != null && 2386 mAttachInfo.mHardwareRenderer.isEnabled()) { 2387 mAttachInfo.mHardwareRenderer.validate(); 2388 } 2389 mView.dispatchDetachedFromWindow(); 2390 } 2391 2392 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2393 mAccessibilityManager.removeAccessibilityStateChangeListener( 2394 mAccessibilityInteractionConnectionManager); 2395 removeSendWindowContentChangedCallback(); 2396 2397 mView = null; 2398 mAttachInfo.mRootView = null; 2399 mAttachInfo.mSurface = null; 2400 2401 destroyHardwareRenderer(); 2402 2403 mSurface.release(); 2404 2405 if (mInputQueueCallback != null && mInputQueue != null) { 2406 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2407 mInputQueueCallback = null; 2408 mInputQueue = null; 2409 } else if (mInputEventReceiver != null) { 2410 mInputEventReceiver.dispose(); 2411 mInputEventReceiver = null; 2412 } 2413 try { 2414 sWindowSession.remove(mWindow); 2415 } catch (RemoteException e) { 2416 } 2417 2418 // Dispose the input channel after removing the window so the Window Manager 2419 // doesn't interpret the input channel being closed as an abnormal termination. 2420 if (mInputChannel != null) { 2421 mInputChannel.dispose(); 2422 mInputChannel = null; 2423 } 2424 2425 unscheduleFrame(); 2426 } 2427 2428 void updateConfiguration(Configuration config, boolean force) { 2429 if (DEBUG_CONFIGURATION) Log.v(TAG, 2430 "Applying new config to window " 2431 + mWindowAttributes.getTitle() 2432 + ": " + config); 2433 2434 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded(); 2435 if (ci != null) { 2436 config = new Configuration(config); 2437 ci.applyToConfiguration(config); 2438 } 2439 2440 synchronized (sConfigCallbacks) { 2441 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2442 sConfigCallbacks.get(i).onConfigurationChanged(config); 2443 } 2444 } 2445 if (mView != null) { 2446 // At this point the resources have been updated to 2447 // have the most recent config, whatever that is. Use 2448 // the on in them which may be newer. 2449 config = mView.getResources().getConfiguration(); 2450 if (force || mLastConfiguration.diff(config) != 0) { 2451 mLastConfiguration.setTo(config); 2452 mView.dispatchConfigurationChanged(config); 2453 } 2454 } 2455 } 2456 2457 /** 2458 * Return true if child is an ancestor of parent, (or equal to the parent). 2459 */ 2460 private static boolean isViewDescendantOf(View child, View parent) { 2461 if (child == parent) { 2462 return true; 2463 } 2464 2465 final ViewParent theParent = child.getParent(); 2466 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2467 } 2468 2469 private static void forceLayout(View view) { 2470 view.forceLayout(); 2471 if (view instanceof ViewGroup) { 2472 ViewGroup group = (ViewGroup) view; 2473 final int count = group.getChildCount(); 2474 for (int i = 0; i < count; i++) { 2475 forceLayout(group.getChildAt(i)); 2476 } 2477 } 2478 } 2479 2480 private final static int MSG_INVALIDATE = 1; 2481 private final static int MSG_INVALIDATE_RECT = 2; 2482 private final static int MSG_DIE = 3; 2483 private final static int MSG_RESIZED = 4; 2484 private final static int MSG_RESIZED_REPORT = 5; 2485 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 2486 private final static int MSG_DISPATCH_KEY = 7; 2487 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 2488 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 2489 private final static int MSG_IME_FINISHED_EVENT = 10; 2490 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 2491 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 2492 private final static int MSG_CHECK_FOCUS = 13; 2493 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 2494 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 2495 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 2496 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 2497 private final static int MSG_UPDATE_CONFIGURATION = 18; 2498 private final static int MSG_PERFORM_ACCESSIBILITY_ACTION = 19; 2499 private final static int MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID = 20; 2500 private final static int MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID = 21; 2501 private final static int MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT = 22; 2502 private final static int MSG_PROCESS_INPUT_EVENTS = 23; 2503 private final static int MSG_DISPATCH_SCREEN_STATUS = 24; 2504 2505 final class ViewRootHandler extends Handler { 2506 @Override 2507 public String getMessageName(Message message) { 2508 switch (message.what) { 2509 case MSG_INVALIDATE: 2510 return "MSG_INVALIDATE"; 2511 case MSG_INVALIDATE_RECT: 2512 return "MSG_INVALIDATE_RECT"; 2513 case MSG_DIE: 2514 return "MSG_DIE"; 2515 case MSG_RESIZED: 2516 return "MSG_RESIZED"; 2517 case MSG_RESIZED_REPORT: 2518 return "MSG_RESIZED_REPORT"; 2519 case MSG_WINDOW_FOCUS_CHANGED: 2520 return "MSG_WINDOW_FOCUS_CHANGED"; 2521 case MSG_DISPATCH_KEY: 2522 return "MSG_DISPATCH_KEY"; 2523 case MSG_DISPATCH_APP_VISIBILITY: 2524 return "MSG_DISPATCH_APP_VISIBILITY"; 2525 case MSG_DISPATCH_GET_NEW_SURFACE: 2526 return "MSG_DISPATCH_GET_NEW_SURFACE"; 2527 case MSG_IME_FINISHED_EVENT: 2528 return "MSG_IME_FINISHED_EVENT"; 2529 case MSG_DISPATCH_KEY_FROM_IME: 2530 return "MSG_DISPATCH_KEY_FROM_IME"; 2531 case MSG_FINISH_INPUT_CONNECTION: 2532 return "MSG_FINISH_INPUT_CONNECTION"; 2533 case MSG_CHECK_FOCUS: 2534 return "MSG_CHECK_FOCUS"; 2535 case MSG_CLOSE_SYSTEM_DIALOGS: 2536 return "MSG_CLOSE_SYSTEM_DIALOGS"; 2537 case MSG_DISPATCH_DRAG_EVENT: 2538 return "MSG_DISPATCH_DRAG_EVENT"; 2539 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 2540 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 2541 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 2542 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 2543 case MSG_UPDATE_CONFIGURATION: 2544 return "MSG_UPDATE_CONFIGURATION"; 2545 case MSG_PERFORM_ACCESSIBILITY_ACTION: 2546 return "MSG_PERFORM_ACCESSIBILITY_ACTION"; 2547 case MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID: 2548 return "MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID"; 2549 case MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID: 2550 return "MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID"; 2551 case MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT: 2552 return "MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT"; 2553 case MSG_PROCESS_INPUT_EVENTS: 2554 return "MSG_PROCESS_INPUT_EVENTS"; 2555 } 2556 return super.getMessageName(message); 2557 } 2558 2559 @Override 2560 public void handleMessage(Message msg) { 2561 switch (msg.what) { 2562 case MSG_INVALIDATE: 2563 ((View) msg.obj).invalidate(); 2564 break; 2565 case MSG_INVALIDATE_RECT: 2566 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 2567 info.target.invalidate(info.left, info.top, info.right, info.bottom); 2568 info.release(); 2569 break; 2570 case MSG_IME_FINISHED_EVENT: 2571 handleImeFinishedEvent(msg.arg1, msg.arg2 != 0); 2572 break; 2573 case MSG_PROCESS_INPUT_EVENTS: 2574 mProcessInputEventsScheduled = false; 2575 doProcessInputEvents(); 2576 break; 2577 case MSG_DISPATCH_APP_VISIBILITY: 2578 handleAppVisibility(msg.arg1 != 0); 2579 break; 2580 case MSG_DISPATCH_GET_NEW_SURFACE: 2581 handleGetNewSurface(); 2582 break; 2583 case MSG_RESIZED: 2584 ResizedInfo ri = (ResizedInfo)msg.obj; 2585 2586 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2 2587 && mPendingContentInsets.equals(ri.coveredInsets) 2588 && mPendingVisibleInsets.equals(ri.visibleInsets) 2589 && ((ResizedInfo)msg.obj).newConfig == null) { 2590 break; 2591 } 2592 // fall through... 2593 case MSG_RESIZED_REPORT: 2594 if (mAdded) { 2595 Configuration config = ((ResizedInfo)msg.obj).newConfig; 2596 if (config != null) { 2597 updateConfiguration(config, false); 2598 } 2599 mWinFrame.left = 0; 2600 mWinFrame.right = msg.arg1; 2601 mWinFrame.top = 0; 2602 mWinFrame.bottom = msg.arg2; 2603 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets); 2604 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets); 2605 if (msg.what == MSG_RESIZED_REPORT) { 2606 mReportNextDraw = true; 2607 } 2608 2609 if (mView != null) { 2610 forceLayout(mView); 2611 } 2612 requestLayout(); 2613 } 2614 break; 2615 case MSG_WINDOW_FOCUS_CHANGED: { 2616 if (mAdded) { 2617 boolean hasWindowFocus = msg.arg1 != 0; 2618 mAttachInfo.mHasWindowFocus = hasWindowFocus; 2619 2620 profileRendering(hasWindowFocus); 2621 2622 if (hasWindowFocus) { 2623 boolean inTouchMode = msg.arg2 != 0; 2624 ensureTouchModeLocally(inTouchMode); 2625 2626 if (mAttachInfo.mHardwareRenderer != null && 2627 mSurface != null && mSurface.isValid()) { 2628 mFullRedrawNeeded = true; 2629 try { 2630 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2631 mHolder); 2632 } catch (Surface.OutOfResourcesException e) { 2633 Log.e(TAG, "OutOfResourcesException locking surface", e); 2634 try { 2635 if (!sWindowSession.outOfMemory(mWindow)) { 2636 Slog.w(TAG, "No processes killed for memory; killing self"); 2637 Process.killProcess(Process.myPid()); 2638 } 2639 } catch (RemoteException ex) { 2640 } 2641 // Retry in a bit. 2642 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 2643 return; 2644 } 2645 } 2646 } 2647 2648 mLastWasImTarget = WindowManager.LayoutParams 2649 .mayUseInputMethod(mWindowAttributes.flags); 2650 2651 InputMethodManager imm = InputMethodManager.peekInstance(); 2652 if (mView != null) { 2653 if (hasWindowFocus && imm != null && mLastWasImTarget) { 2654 imm.startGettingWindowFocus(mView); 2655 } 2656 mAttachInfo.mKeyDispatchState.reset(); 2657 mView.dispatchWindowFocusChanged(hasWindowFocus); 2658 } 2659 2660 // Note: must be done after the focus change callbacks, 2661 // so all of the view state is set up correctly. 2662 if (hasWindowFocus) { 2663 if (imm != null && mLastWasImTarget) { 2664 imm.onWindowFocus(mView, mView.findFocus(), 2665 mWindowAttributes.softInputMode, 2666 !mHasHadWindowFocus, mWindowAttributes.flags); 2667 } 2668 // Clear the forward bit. We can just do this directly, since 2669 // the window manager doesn't care about it. 2670 mWindowAttributes.softInputMode &= 2671 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2672 ((WindowManager.LayoutParams)mView.getLayoutParams()) 2673 .softInputMode &= 2674 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2675 mHasHadWindowFocus = true; 2676 } 2677 2678 if (hasWindowFocus && mView != null && mAccessibilityManager.isEnabled()) { 2679 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 2680 } 2681 } 2682 } break; 2683 case MSG_DIE: 2684 doDie(); 2685 break; 2686 case MSG_DISPATCH_KEY: { 2687 KeyEvent event = (KeyEvent)msg.obj; 2688 enqueueInputEvent(event, null, 0, true); 2689 } break; 2690 case MSG_DISPATCH_KEY_FROM_IME: { 2691 if (LOCAL_LOGV) Log.v( 2692 TAG, "Dispatching key " 2693 + msg.obj + " from IME to " + mView); 2694 KeyEvent event = (KeyEvent)msg.obj; 2695 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 2696 // The IME is trying to say this event is from the 2697 // system! Bad bad bad! 2698 //noinspection UnusedAssignment 2699 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 2700 } 2701 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 2702 } break; 2703 case MSG_FINISH_INPUT_CONNECTION: { 2704 InputMethodManager imm = InputMethodManager.peekInstance(); 2705 if (imm != null) { 2706 imm.reportFinishInputConnection((InputConnection)msg.obj); 2707 } 2708 } break; 2709 case MSG_CHECK_FOCUS: { 2710 InputMethodManager imm = InputMethodManager.peekInstance(); 2711 if (imm != null) { 2712 imm.checkFocus(); 2713 } 2714 } break; 2715 case MSG_CLOSE_SYSTEM_DIALOGS: { 2716 if (mView != null) { 2717 mView.onCloseSystemDialogs((String)msg.obj); 2718 } 2719 } break; 2720 case MSG_DISPATCH_DRAG_EVENT: 2721 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 2722 DragEvent event = (DragEvent)msg.obj; 2723 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 2724 handleDragEvent(event); 2725 } break; 2726 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 2727 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj); 2728 } break; 2729 case MSG_UPDATE_CONFIGURATION: { 2730 Configuration config = (Configuration)msg.obj; 2731 if (config.isOtherSeqNewer(mLastConfiguration)) { 2732 config = mLastConfiguration; 2733 } 2734 updateConfiguration(config, false); 2735 } break; 2736 case MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID: { 2737 if (mView != null) { 2738 getAccessibilityInteractionController() 2739 .findAccessibilityNodeInfoByAccessibilityIdUiThread(msg); 2740 } 2741 } break; 2742 case MSG_PERFORM_ACCESSIBILITY_ACTION: { 2743 if (mView != null) { 2744 getAccessibilityInteractionController() 2745 .perfromAccessibilityActionUiThread(msg); 2746 } 2747 } break; 2748 case MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID: { 2749 if (mView != null) { 2750 getAccessibilityInteractionController() 2751 .findAccessibilityNodeInfoByViewIdUiThread(msg); 2752 } 2753 } break; 2754 case MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT: { 2755 if (mView != null) { 2756 getAccessibilityInteractionController() 2757 .findAccessibilityNodeInfosByTextUiThread(msg); 2758 } 2759 } break; 2760 case MSG_DISPATCH_SCREEN_STATUS: { 2761 if (mView != null) { 2762 handleScreenStatusChange(msg.arg1 == 1); 2763 } 2764 } break; 2765 } 2766 } 2767 } 2768 final ViewRootHandler mHandler = new ViewRootHandler(); 2769 2770 /** 2771 * Something in the current window tells us we need to change the touch mode. For 2772 * example, we are not in touch mode, and the user touches the screen. 2773 * 2774 * If the touch mode has changed, tell the window manager, and handle it locally. 2775 * 2776 * @param inTouchMode Whether we want to be in touch mode. 2777 * @return True if the touch mode changed and focus changed was changed as a result 2778 */ 2779 boolean ensureTouchMode(boolean inTouchMode) { 2780 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 2781 + "touch mode is " + mAttachInfo.mInTouchMode); 2782 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 2783 2784 // tell the window manager 2785 try { 2786 sWindowSession.setInTouchMode(inTouchMode); 2787 } catch (RemoteException e) { 2788 throw new RuntimeException(e); 2789 } 2790 2791 // handle the change 2792 return ensureTouchModeLocally(inTouchMode); 2793 } 2794 2795 /** 2796 * Ensure that the touch mode for this window is set, and if it is changing, 2797 * take the appropriate action. 2798 * @param inTouchMode Whether we want to be in touch mode. 2799 * @return True if the touch mode changed and focus changed was changed as a result 2800 */ 2801 private boolean ensureTouchModeLocally(boolean inTouchMode) { 2802 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 2803 + "touch mode is " + mAttachInfo.mInTouchMode); 2804 2805 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 2806 2807 mAttachInfo.mInTouchMode = inTouchMode; 2808 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 2809 2810 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 2811 } 2812 2813 private boolean enterTouchMode() { 2814 if (mView != null) { 2815 if (mView.hasFocus()) { 2816 // note: not relying on mFocusedView here because this could 2817 // be when the window is first being added, and mFocused isn't 2818 // set yet. 2819 final View focused = mView.findFocus(); 2820 if (focused != null && !focused.isFocusableInTouchMode()) { 2821 2822 final ViewGroup ancestorToTakeFocus = 2823 findAncestorToTakeFocusInTouchMode(focused); 2824 if (ancestorToTakeFocus != null) { 2825 // there is an ancestor that wants focus after its descendants that 2826 // is focusable in touch mode.. give it focus 2827 return ancestorToTakeFocus.requestFocus(); 2828 } else { 2829 // nothing appropriate to have focus in touch mode, clear it out 2830 mView.unFocus(); 2831 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null); 2832 mFocusedView = null; 2833 mOldFocusedView = null; 2834 return true; 2835 } 2836 } 2837 } 2838 } 2839 return false; 2840 } 2841 2842 2843 /** 2844 * Find an ancestor of focused that wants focus after its descendants and is 2845 * focusable in touch mode. 2846 * @param focused The currently focused view. 2847 * @return An appropriate view, or null if no such view exists. 2848 */ 2849 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 2850 ViewParent parent = focused.getParent(); 2851 while (parent instanceof ViewGroup) { 2852 final ViewGroup vgParent = (ViewGroup) parent; 2853 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 2854 && vgParent.isFocusableInTouchMode()) { 2855 return vgParent; 2856 } 2857 if (vgParent.isRootNamespace()) { 2858 return null; 2859 } else { 2860 parent = vgParent.getParent(); 2861 } 2862 } 2863 return null; 2864 } 2865 2866 private boolean leaveTouchMode() { 2867 if (mView != null) { 2868 if (mView.hasFocus()) { 2869 // i learned the hard way to not trust mFocusedView :) 2870 mFocusedView = mView.findFocus(); 2871 if (!(mFocusedView instanceof ViewGroup)) { 2872 // some view has focus, let it keep it 2873 return false; 2874 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() != 2875 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 2876 // some view group has focus, and doesn't prefer its children 2877 // over itself for focus, so let them keep it. 2878 return false; 2879 } 2880 } 2881 2882 // find the best view to give focus to in this brave new non-touch-mode 2883 // world 2884 final View focused = focusSearch(null, View.FOCUS_DOWN); 2885 if (focused != null) { 2886 return focused.requestFocus(View.FOCUS_DOWN); 2887 } 2888 } 2889 return false; 2890 } 2891 2892 private void deliverInputEvent(QueuedInputEvent q) { 2893 if (ViewDebug.DEBUG_LATENCY) { 2894 q.mDeliverTimeNanos = System.nanoTime(); 2895 } 2896 2897 if (q.mEvent instanceof KeyEvent) { 2898 deliverKeyEvent(q); 2899 } else { 2900 final int source = q.mEvent.getSource(); 2901 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 2902 deliverPointerEvent(q); 2903 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 2904 deliverTrackballEvent(q); 2905 } else { 2906 deliverGenericMotionEvent(q); 2907 } 2908 } 2909 } 2910 2911 private void deliverPointerEvent(QueuedInputEvent q) { 2912 final MotionEvent event = (MotionEvent)q.mEvent; 2913 final boolean isTouchEvent = event.isTouchEvent(); 2914 if (mInputEventConsistencyVerifier != null) { 2915 if (isTouchEvent) { 2916 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 2917 } else { 2918 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 2919 } 2920 } 2921 2922 // If there is no view, then the event will not be handled. 2923 if (mView == null || !mAdded) { 2924 finishInputEvent(q, false); 2925 return; 2926 } 2927 2928 // Translate the pointer event for compatibility, if needed. 2929 if (mTranslator != null) { 2930 mTranslator.translateEventInScreenToAppWindow(event); 2931 } 2932 2933 // Enter touch mode on down or scroll. 2934 final int action = event.getAction(); 2935 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 2936 ensureTouchMode(true); 2937 } 2938 2939 // Offset the scroll position. 2940 if (mCurScrollY != 0) { 2941 event.offsetLocation(0, mCurScrollY); 2942 } 2943 if (MEASURE_LATENCY) { 2944 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano()); 2945 } 2946 2947 // Remember the touch position for possible drag-initiation. 2948 if (isTouchEvent) { 2949 mLastTouchPoint.x = event.getRawX(); 2950 mLastTouchPoint.y = event.getRawY(); 2951 } 2952 2953 // Dispatch touch to view hierarchy. 2954 boolean handled = mView.dispatchPointerEvent(event); 2955 if (MEASURE_LATENCY) { 2956 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano()); 2957 } 2958 if (handled) { 2959 finishInputEvent(q, true); 2960 return; 2961 } 2962 2963 // Pointer event was unhandled. 2964 finishInputEvent(q, false); 2965 } 2966 2967 private void deliverTrackballEvent(QueuedInputEvent q) { 2968 final MotionEvent event = (MotionEvent)q.mEvent; 2969 if (mInputEventConsistencyVerifier != null) { 2970 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 2971 } 2972 2973 // If there is no view, then the event will not be handled. 2974 if (mView == null || !mAdded) { 2975 finishInputEvent(q, false); 2976 return; 2977 } 2978 2979 // Deliver the trackball event to the view. 2980 if (mView.dispatchTrackballEvent(event)) { 2981 // If we reach this, we delivered a trackball event to mView and 2982 // mView consumed it. Because we will not translate the trackball 2983 // event into a key event, touch mode will not exit, so we exit 2984 // touch mode here. 2985 ensureTouchMode(false); 2986 2987 finishInputEvent(q, true); 2988 mLastTrackballTime = Integer.MIN_VALUE; 2989 return; 2990 } 2991 2992 // Translate the trackball event into DPAD keys and try to deliver those. 2993 final TrackballAxis x = mTrackballAxisX; 2994 final TrackballAxis y = mTrackballAxisY; 2995 2996 long curTime = SystemClock.uptimeMillis(); 2997 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) { 2998 // It has been too long since the last movement, 2999 // so restart at the beginning. 3000 x.reset(0); 3001 y.reset(0); 3002 mLastTrackballTime = curTime; 3003 } 3004 3005 final int action = event.getAction(); 3006 final int metaState = event.getMetaState(); 3007 switch (action) { 3008 case MotionEvent.ACTION_DOWN: 3009 x.reset(2); 3010 y.reset(2); 3011 enqueueInputEvent(new KeyEvent(curTime, curTime, 3012 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3013 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3014 InputDevice.SOURCE_KEYBOARD)); 3015 break; 3016 case MotionEvent.ACTION_UP: 3017 x.reset(2); 3018 y.reset(2); 3019 enqueueInputEvent(new KeyEvent(curTime, curTime, 3020 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3021 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3022 InputDevice.SOURCE_KEYBOARD)); 3023 break; 3024 } 3025 3026 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step=" 3027 + x.step + " dir=" + x.dir + " acc=" + x.acceleration 3028 + " move=" + event.getX() 3029 + " / Y=" + y.position + " step=" 3030 + y.step + " dir=" + y.dir + " acc=" + y.acceleration 3031 + " move=" + event.getY()); 3032 final float xOff = x.collect(event.getX(), event.getEventTime(), "X"); 3033 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y"); 3034 3035 // Generate DPAD events based on the trackball movement. 3036 // We pick the axis that has moved the most as the direction of 3037 // the DPAD. When we generate DPAD events for one axis, then the 3038 // other axis is reset -- we don't want to perform DPAD jumps due 3039 // to slight movements in the trackball when making major movements 3040 // along the other axis. 3041 int keycode = 0; 3042 int movement = 0; 3043 float accel = 1; 3044 if (xOff > yOff) { 3045 movement = x.generate((2/event.getXPrecision())); 3046 if (movement != 0) { 3047 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3048 : KeyEvent.KEYCODE_DPAD_LEFT; 3049 accel = x.acceleration; 3050 y.reset(2); 3051 } 3052 } else if (yOff > 0) { 3053 movement = y.generate((2/event.getYPrecision())); 3054 if (movement != 0) { 3055 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3056 : KeyEvent.KEYCODE_DPAD_UP; 3057 accel = y.acceleration; 3058 x.reset(2); 3059 } 3060 } 3061 3062 if (keycode != 0) { 3063 if (movement < 0) movement = -movement; 3064 int accelMovement = (int)(movement * accel); 3065 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 3066 + " accelMovement=" + accelMovement 3067 + " accel=" + accel); 3068 if (accelMovement > movement) { 3069 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3070 + keycode); 3071 movement--; 3072 int repeatCount = accelMovement - movement; 3073 enqueueInputEvent(new KeyEvent(curTime, curTime, 3074 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 3075 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3076 InputDevice.SOURCE_KEYBOARD)); 3077 } 3078 while (movement > 0) { 3079 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3080 + keycode); 3081 movement--; 3082 curTime = SystemClock.uptimeMillis(); 3083 enqueueInputEvent(new KeyEvent(curTime, curTime, 3084 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 3085 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3086 InputDevice.SOURCE_KEYBOARD)); 3087 enqueueInputEvent(new KeyEvent(curTime, curTime, 3088 KeyEvent.ACTION_UP, keycode, 0, metaState, 3089 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3090 InputDevice.SOURCE_KEYBOARD)); 3091 } 3092 mLastTrackballTime = curTime; 3093 } 3094 3095 // Unfortunately we can't tell whether the application consumed the keys, so 3096 // we always consider the trackball event handled. 3097 finishInputEvent(q, true); 3098 } 3099 3100 private void deliverGenericMotionEvent(QueuedInputEvent q) { 3101 final MotionEvent event = (MotionEvent)q.mEvent; 3102 if (mInputEventConsistencyVerifier != null) { 3103 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3104 } 3105 3106 final int source = event.getSource(); 3107 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0; 3108 3109 // If there is no view, then the event will not be handled. 3110 if (mView == null || !mAdded) { 3111 if (isJoystick) { 3112 updateJoystickDirection(event, false); 3113 } 3114 finishInputEvent(q, false); 3115 return; 3116 } 3117 3118 // Deliver the event to the view. 3119 if (mView.dispatchGenericMotionEvent(event)) { 3120 if (isJoystick) { 3121 updateJoystickDirection(event, false); 3122 } 3123 finishInputEvent(q, true); 3124 return; 3125 } 3126 3127 if (isJoystick) { 3128 // Translate the joystick event into DPAD keys and try to deliver those. 3129 updateJoystickDirection(event, true); 3130 finishInputEvent(q, true); 3131 } else { 3132 finishInputEvent(q, false); 3133 } 3134 } 3135 3136 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) { 3137 final long time = event.getEventTime(); 3138 final int metaState = event.getMetaState(); 3139 final int deviceId = event.getDeviceId(); 3140 final int source = event.getSource(); 3141 3142 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X)); 3143 if (xDirection == 0) { 3144 xDirection = joystickAxisValueToDirection(event.getX()); 3145 } 3146 3147 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 3148 if (yDirection == 0) { 3149 yDirection = joystickAxisValueToDirection(event.getY()); 3150 } 3151 3152 if (xDirection != mLastJoystickXDirection) { 3153 if (mLastJoystickXKeyCode != 0) { 3154 enqueueInputEvent(new KeyEvent(time, time, 3155 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState, 3156 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3157 mLastJoystickXKeyCode = 0; 3158 } 3159 3160 mLastJoystickXDirection = xDirection; 3161 3162 if (xDirection != 0 && synthesizeNewKeys) { 3163 mLastJoystickXKeyCode = xDirection > 0 3164 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 3165 enqueueInputEvent(new KeyEvent(time, time, 3166 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState, 3167 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3168 } 3169 } 3170 3171 if (yDirection != mLastJoystickYDirection) { 3172 if (mLastJoystickYKeyCode != 0) { 3173 enqueueInputEvent(new KeyEvent(time, time, 3174 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState, 3175 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3176 mLastJoystickYKeyCode = 0; 3177 } 3178 3179 mLastJoystickYDirection = yDirection; 3180 3181 if (yDirection != 0 && synthesizeNewKeys) { 3182 mLastJoystickYKeyCode = yDirection > 0 3183 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 3184 enqueueInputEvent(new KeyEvent(time, time, 3185 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState, 3186 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3187 } 3188 } 3189 } 3190 3191 private static int joystickAxisValueToDirection(float value) { 3192 if (value >= 0.5f) { 3193 return 1; 3194 } else if (value <= -0.5f) { 3195 return -1; 3196 } else { 3197 return 0; 3198 } 3199 } 3200 3201 /** 3202 * Returns true if the key is used for keyboard navigation. 3203 * @param keyEvent The key event. 3204 * @return True if the key is used for keyboard navigation. 3205 */ 3206 private static boolean isNavigationKey(KeyEvent keyEvent) { 3207 switch (keyEvent.getKeyCode()) { 3208 case KeyEvent.KEYCODE_DPAD_LEFT: 3209 case KeyEvent.KEYCODE_DPAD_RIGHT: 3210 case KeyEvent.KEYCODE_DPAD_UP: 3211 case KeyEvent.KEYCODE_DPAD_DOWN: 3212 case KeyEvent.KEYCODE_DPAD_CENTER: 3213 case KeyEvent.KEYCODE_PAGE_UP: 3214 case KeyEvent.KEYCODE_PAGE_DOWN: 3215 case KeyEvent.KEYCODE_MOVE_HOME: 3216 case KeyEvent.KEYCODE_MOVE_END: 3217 case KeyEvent.KEYCODE_TAB: 3218 case KeyEvent.KEYCODE_SPACE: 3219 case KeyEvent.KEYCODE_ENTER: 3220 return true; 3221 } 3222 return false; 3223 } 3224 3225 /** 3226 * Returns true if the key is used for typing. 3227 * @param keyEvent The key event. 3228 * @return True if the key is used for typing. 3229 */ 3230 private static boolean isTypingKey(KeyEvent keyEvent) { 3231 return keyEvent.getUnicodeChar() > 0; 3232 } 3233 3234 /** 3235 * See if the key event means we should leave touch mode (and leave touch mode if so). 3236 * @param event The key event. 3237 * @return Whether this key event should be consumed (meaning the act of 3238 * leaving touch mode alone is considered the event). 3239 */ 3240 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 3241 // Only relevant in touch mode. 3242 if (!mAttachInfo.mInTouchMode) { 3243 return false; 3244 } 3245 3246 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 3247 final int action = event.getAction(); 3248 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 3249 return false; 3250 } 3251 3252 // Don't leave touch mode if the IME told us not to. 3253 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 3254 return false; 3255 } 3256 3257 // If the key can be used for keyboard navigation then leave touch mode 3258 // and select a focused view if needed (in ensureTouchMode). 3259 // When a new focused view is selected, we consume the navigation key because 3260 // navigation doesn't make much sense unless a view already has focus so 3261 // the key's purpose is to set focus. 3262 if (isNavigationKey(event)) { 3263 return ensureTouchMode(false); 3264 } 3265 3266 // If the key can be used for typing then leave touch mode 3267 // and select a focused view if needed (in ensureTouchMode). 3268 // Always allow the view to process the typing key. 3269 if (isTypingKey(event)) { 3270 ensureTouchMode(false); 3271 return false; 3272 } 3273 3274 return false; 3275 } 3276 3277 private void deliverKeyEvent(QueuedInputEvent q) { 3278 final KeyEvent event = (KeyEvent)q.mEvent; 3279 if (mInputEventConsistencyVerifier != null) { 3280 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 3281 } 3282 3283 if ((q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3284 // If there is no view, then the event will not be handled. 3285 if (mView == null || !mAdded) { 3286 finishInputEvent(q, false); 3287 return; 3288 } 3289 3290 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView); 3291 3292 // Perform predispatching before the IME. 3293 if (mView.dispatchKeyEventPreIme(event)) { 3294 finishInputEvent(q, true); 3295 return; 3296 } 3297 3298 // Dispatch to the IME before propagating down the view hierarchy. 3299 // The IME will eventually call back into handleImeFinishedEvent. 3300 if (mLastWasImTarget) { 3301 InputMethodManager imm = InputMethodManager.peekInstance(); 3302 if (imm != null) { 3303 final int seq = event.getSequenceNumber(); 3304 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq=" 3305 + seq + " event=" + event); 3306 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback); 3307 return; 3308 } 3309 } 3310 } 3311 3312 // Not dispatching to IME, continue with post IME actions. 3313 deliverKeyEventPostIme(q); 3314 } 3315 3316 void handleImeFinishedEvent(int seq, boolean handled) { 3317 final QueuedInputEvent q = mCurrentInputEvent; 3318 if (q != null && q.mEvent.getSequenceNumber() == seq) { 3319 final KeyEvent event = (KeyEvent)q.mEvent; 3320 if (DEBUG_IMF) { 3321 Log.v(TAG, "IME finished event: seq=" + seq 3322 + " handled=" + handled + " event=" + event); 3323 } 3324 if (handled) { 3325 finishInputEvent(q, true); 3326 } else { 3327 deliverKeyEventPostIme(q); 3328 } 3329 } else { 3330 if (DEBUG_IMF) { 3331 Log.v(TAG, "IME finished event: seq=" + seq 3332 + " handled=" + handled + ", event not found!"); 3333 } 3334 } 3335 } 3336 3337 private void deliverKeyEventPostIme(QueuedInputEvent q) { 3338 final KeyEvent event = (KeyEvent)q.mEvent; 3339 if (ViewDebug.DEBUG_LATENCY) { 3340 q.mDeliverPostImeTimeNanos = System.nanoTime(); 3341 } 3342 3343 // If the view went away, then the event will not be handled. 3344 if (mView == null || !mAdded) { 3345 finishInputEvent(q, false); 3346 return; 3347 } 3348 3349 // If the key's purpose is to exit touch mode then we consume it and consider it handled. 3350 if (checkForLeavingTouchModeAndConsume(event)) { 3351 finishInputEvent(q, true); 3352 return; 3353 } 3354 3355 // Make sure the fallback event policy sees all keys that will be delivered to the 3356 // view hierarchy. 3357 mFallbackEventHandler.preDispatchKeyEvent(event); 3358 3359 // Deliver the key to the view hierarchy. 3360 if (mView.dispatchKeyEvent(event)) { 3361 finishInputEvent(q, true); 3362 return; 3363 } 3364 3365 // If the Control modifier is held, try to interpret the key as a shortcut. 3366 if (event.getAction() == KeyEvent.ACTION_DOWN 3367 && event.isCtrlPressed() 3368 && event.getRepeatCount() == 0 3369 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3370 if (mView.dispatchKeyShortcutEvent(event)) { 3371 finishInputEvent(q, true); 3372 return; 3373 } 3374 } 3375 3376 // Apply the fallback event policy. 3377 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3378 finishInputEvent(q, true); 3379 return; 3380 } 3381 3382 // Handle automatic focus changes. 3383 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3384 int direction = 0; 3385 switch (event.getKeyCode()) { 3386 case KeyEvent.KEYCODE_DPAD_LEFT: 3387 if (event.hasNoModifiers()) { 3388 direction = View.FOCUS_LEFT; 3389 } 3390 break; 3391 case KeyEvent.KEYCODE_DPAD_RIGHT: 3392 if (event.hasNoModifiers()) { 3393 direction = View.FOCUS_RIGHT; 3394 } 3395 break; 3396 case KeyEvent.KEYCODE_DPAD_UP: 3397 if (event.hasNoModifiers()) { 3398 direction = View.FOCUS_UP; 3399 } 3400 break; 3401 case KeyEvent.KEYCODE_DPAD_DOWN: 3402 if (event.hasNoModifiers()) { 3403 direction = View.FOCUS_DOWN; 3404 } 3405 break; 3406 case KeyEvent.KEYCODE_TAB: 3407 if (event.hasNoModifiers()) { 3408 direction = View.FOCUS_FORWARD; 3409 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3410 direction = View.FOCUS_BACKWARD; 3411 } 3412 break; 3413 } 3414 3415 if (direction != 0) { 3416 View focused = mView != null ? mView.findFocus() : null; 3417 if (focused != null) { 3418 View v = focused.focusSearch(direction); 3419 if (v != null && v != focused) { 3420 // do the math the get the interesting rect 3421 // of previous focused into the coord system of 3422 // newly focused view 3423 focused.getFocusedRect(mTempRect); 3424 if (mView instanceof ViewGroup) { 3425 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3426 focused, mTempRect); 3427 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3428 v, mTempRect); 3429 } 3430 if (v.requestFocus(direction, mTempRect)) { 3431 playSoundEffect( 3432 SoundEffectConstants.getContantForFocusDirection(direction)); 3433 finishInputEvent(q, true); 3434 return; 3435 } 3436 } 3437 3438 // Give the focused view a last chance to handle the dpad key. 3439 if (mView.dispatchUnhandledMove(focused, direction)) { 3440 finishInputEvent(q, true); 3441 return; 3442 } 3443 } 3444 } 3445 } 3446 3447 // Key was unhandled. 3448 finishInputEvent(q, false); 3449 } 3450 3451 /* drag/drop */ 3452 void setLocalDragState(Object obj) { 3453 mLocalDragState = obj; 3454 } 3455 3456 private void handleDragEvent(DragEvent event) { 3457 // From the root, only drag start/end/location are dispatched. entered/exited 3458 // are determined and dispatched by the viewgroup hierarchy, who then report 3459 // that back here for ultimate reporting back to the framework. 3460 if (mView != null && mAdded) { 3461 final int what = event.mAction; 3462 3463 if (what == DragEvent.ACTION_DRAG_EXITED) { 3464 // A direct EXITED event means that the window manager knows we've just crossed 3465 // a window boundary, so the current drag target within this one must have 3466 // just been exited. Send it the usual notifications and then we're done 3467 // for now. 3468 mView.dispatchDragEvent(event); 3469 } else { 3470 // Cache the drag description when the operation starts, then fill it in 3471 // on subsequent calls as a convenience 3472 if (what == DragEvent.ACTION_DRAG_STARTED) { 3473 mCurrentDragView = null; // Start the current-recipient tracking 3474 mDragDescription = event.mClipDescription; 3475 } else { 3476 event.mClipDescription = mDragDescription; 3477 } 3478 3479 // For events with a [screen] location, translate into window coordinates 3480 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 3481 mDragPoint.set(event.mX, event.mY); 3482 if (mTranslator != null) { 3483 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 3484 } 3485 3486 if (mCurScrollY != 0) { 3487 mDragPoint.offset(0, mCurScrollY); 3488 } 3489 3490 event.mX = mDragPoint.x; 3491 event.mY = mDragPoint.y; 3492 } 3493 3494 // Remember who the current drag target is pre-dispatch 3495 final View prevDragView = mCurrentDragView; 3496 3497 // Now dispatch the drag/drop event 3498 boolean result = mView.dispatchDragEvent(event); 3499 3500 // If we changed apparent drag target, tell the OS about it 3501 if (prevDragView != mCurrentDragView) { 3502 try { 3503 if (prevDragView != null) { 3504 sWindowSession.dragRecipientExited(mWindow); 3505 } 3506 if (mCurrentDragView != null) { 3507 sWindowSession.dragRecipientEntered(mWindow); 3508 } 3509 } catch (RemoteException e) { 3510 Slog.e(TAG, "Unable to note drag target change"); 3511 } 3512 } 3513 3514 // Report the drop result when we're done 3515 if (what == DragEvent.ACTION_DROP) { 3516 mDragDescription = null; 3517 try { 3518 Log.i(TAG, "Reporting drop result: " + result); 3519 sWindowSession.reportDropResult(mWindow, result); 3520 } catch (RemoteException e) { 3521 Log.e(TAG, "Unable to report drop result"); 3522 } 3523 } 3524 3525 // When the drag operation ends, release any local state object 3526 // that may have been in use 3527 if (what == DragEvent.ACTION_DRAG_ENDED) { 3528 setLocalDragState(null); 3529 } 3530 } 3531 } 3532 event.recycle(); 3533 } 3534 3535 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 3536 if (mSeq != args.seq) { 3537 // The sequence has changed, so we need to update our value and make 3538 // sure to do a traversal afterward so the window manager is given our 3539 // most recent data. 3540 mSeq = args.seq; 3541 mAttachInfo.mForceReportNewAttributes = true; 3542 scheduleTraversals(); 3543 } 3544 if (mView == null) return; 3545 if (args.localChanges != 0) { 3546 if (mAttachInfo != null) { 3547 mAttachInfo.mSystemUiVisibility = 3548 (mAttachInfo.mSystemUiVisibility & ~args.localChanges) | 3549 (args.localValue & args.localChanges); 3550 mAttachInfo.mRecomputeGlobalAttributes = true; 3551 } 3552 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 3553 scheduleTraversals(); 3554 } 3555 mView.dispatchSystemUiVisibilityChanged(args.globalVisibility); 3556 } 3557 3558 public void getLastTouchPoint(Point outLocation) { 3559 outLocation.x = (int) mLastTouchPoint.x; 3560 outLocation.y = (int) mLastTouchPoint.y; 3561 } 3562 3563 public void setDragFocus(View newDragTarget) { 3564 if (mCurrentDragView != newDragTarget) { 3565 mCurrentDragView = newDragTarget; 3566 } 3567 } 3568 3569 private AudioManager getAudioManager() { 3570 if (mView == null) { 3571 throw new IllegalStateException("getAudioManager called when there is no mView"); 3572 } 3573 if (mAudioManager == null) { 3574 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 3575 } 3576 return mAudioManager; 3577 } 3578 3579 public AccessibilityInteractionController getAccessibilityInteractionController() { 3580 if (mView == null) { 3581 throw new IllegalStateException("getAccessibilityInteractionController" 3582 + " called when there is no mView"); 3583 } 3584 if (mAccessibilityInteractionController == null) { 3585 mAccessibilityInteractionController = new AccessibilityInteractionController(); 3586 } 3587 return mAccessibilityInteractionController; 3588 } 3589 3590 public AccessibilityNodePrefetcher getAccessibilityNodePrefetcher() { 3591 if (mView == null) { 3592 throw new IllegalStateException("getAccessibilityNodePrefetcher" 3593 + " called when there is no mView"); 3594 } 3595 if (mAccessibilityNodePrefetcher == null) { 3596 mAccessibilityNodePrefetcher = new AccessibilityNodePrefetcher(); 3597 } 3598 return mAccessibilityNodePrefetcher; 3599 } 3600 3601 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 3602 boolean insetsPending) throws RemoteException { 3603 3604 float appScale = mAttachInfo.mApplicationScale; 3605 boolean restore = false; 3606 if (params != null && mTranslator != null) { 3607 restore = true; 3608 params.backup(); 3609 mTranslator.translateWindowLayout(params); 3610 } 3611 if (params != null) { 3612 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 3613 } 3614 mPendingConfiguration.seq = 0; 3615 //Log.d(TAG, ">>>>>> CALLING relayout"); 3616 if (params != null && mOrigWindowType != params.type) { 3617 // For compatibility with old apps, don't crash here. 3618 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 3619 Slog.w(TAG, "Window type can not be changed after " 3620 + "the window is added; ignoring change of " + mView); 3621 params.type = mOrigWindowType; 3622 } 3623 } 3624 int relayoutResult = sWindowSession.relayout( 3625 mWindow, mSeq, params, 3626 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 3627 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 3628 viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0, 3629 mWinFrame, mPendingContentInsets, mPendingVisibleInsets, 3630 mPendingConfiguration, mSurface); 3631 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 3632 if (restore) { 3633 params.restore(); 3634 } 3635 3636 if (mTranslator != null) { 3637 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 3638 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 3639 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 3640 } 3641 return relayoutResult; 3642 } 3643 3644 /** 3645 * {@inheritDoc} 3646 */ 3647 public void playSoundEffect(int effectId) { 3648 checkThread(); 3649 3650 try { 3651 final AudioManager audioManager = getAudioManager(); 3652 3653 switch (effectId) { 3654 case SoundEffectConstants.CLICK: 3655 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 3656 return; 3657 case SoundEffectConstants.NAVIGATION_DOWN: 3658 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 3659 return; 3660 case SoundEffectConstants.NAVIGATION_LEFT: 3661 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 3662 return; 3663 case SoundEffectConstants.NAVIGATION_RIGHT: 3664 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 3665 return; 3666 case SoundEffectConstants.NAVIGATION_UP: 3667 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 3668 return; 3669 default: 3670 throw new IllegalArgumentException("unknown effect id " + effectId + 3671 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 3672 } 3673 } catch (IllegalStateException e) { 3674 // Exception thrown by getAudioManager() when mView is null 3675 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 3676 e.printStackTrace(); 3677 } 3678 } 3679 3680 /** 3681 * {@inheritDoc} 3682 */ 3683 public boolean performHapticFeedback(int effectId, boolean always) { 3684 try { 3685 return sWindowSession.performHapticFeedback(mWindow, effectId, always); 3686 } catch (RemoteException e) { 3687 return false; 3688 } 3689 } 3690 3691 /** 3692 * {@inheritDoc} 3693 */ 3694 public View focusSearch(View focused, int direction) { 3695 checkThread(); 3696 if (!(mView instanceof ViewGroup)) { 3697 return null; 3698 } 3699 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 3700 } 3701 3702 public void debug() { 3703 mView.debug(); 3704 } 3705 3706 public void dumpGfxInfo(int[] info) { 3707 if (mView != null) { 3708 getGfxInfo(mView, info); 3709 } else { 3710 info[0] = info[1] = 0; 3711 } 3712 } 3713 3714 private void getGfxInfo(View view, int[] info) { 3715 DisplayList displayList = view.mDisplayList; 3716 info[0]++; 3717 if (displayList != null) { 3718 info[1] += displayList.getSize(); 3719 } 3720 3721 if (view instanceof ViewGroup) { 3722 ViewGroup group = (ViewGroup) view; 3723 3724 int count = group.getChildCount(); 3725 for (int i = 0; i < count; i++) { 3726 getGfxInfo(group.getChildAt(i), info); 3727 } 3728 } 3729 } 3730 3731 public void die(boolean immediate) { 3732 if (immediate) { 3733 doDie(); 3734 } else { 3735 mHandler.sendEmptyMessage(MSG_DIE); 3736 } 3737 } 3738 3739 void doDie() { 3740 checkThread(); 3741 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 3742 synchronized (this) { 3743 if (mAdded) { 3744 mAdded = false; 3745 dispatchDetachedFromWindow(); 3746 } 3747 3748 if (mAdded && !mFirst) { 3749 destroyHardwareRenderer(); 3750 3751 int viewVisibility = mView.getVisibility(); 3752 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 3753 if (mWindowAttributesChanged || viewVisibilityChanged) { 3754 // If layout params have been changed, first give them 3755 // to the window manager to make sure it has the correct 3756 // animation info. 3757 try { 3758 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 3759 & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) { 3760 sWindowSession.finishDrawing(mWindow); 3761 } 3762 } catch (RemoteException e) { 3763 } 3764 } 3765 3766 mSurface.release(); 3767 } 3768 } 3769 } 3770 3771 public void requestUpdateConfiguration(Configuration config) { 3772 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 3773 mHandler.sendMessage(msg); 3774 } 3775 3776 private void destroyHardwareRenderer() { 3777 if (mAttachInfo.mHardwareRenderer != null) { 3778 mAttachInfo.mHardwareRenderer.destroy(true); 3779 mAttachInfo.mHardwareRenderer = null; 3780 mAttachInfo.mHardwareAccelerated = false; 3781 } 3782 } 3783 3784 void dispatchImeFinishedEvent(int seq, boolean handled) { 3785 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT); 3786 msg.arg1 = seq; 3787 msg.arg2 = handled ? 1 : 0; 3788 mHandler.sendMessage(msg); 3789 } 3790 3791 public void dispatchFinishInputConnection(InputConnection connection) { 3792 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 3793 mHandler.sendMessage(msg); 3794 } 3795 3796 public void dispatchResized(int w, int h, Rect coveredInsets, 3797 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 3798 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w 3799 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString() 3800 + " visibleInsets=" + visibleInsets.toShortString() 3801 + " reportDraw=" + reportDraw); 3802 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED); 3803 if (mTranslator != null) { 3804 mTranslator.translateRectInScreenToAppWindow(coveredInsets); 3805 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 3806 w *= mTranslator.applicationInvertedScale; 3807 h *= mTranslator.applicationInvertedScale; 3808 } 3809 msg.arg1 = w; 3810 msg.arg2 = h; 3811 ResizedInfo ri = new ResizedInfo(); 3812 ri.coveredInsets = new Rect(coveredInsets); 3813 ri.visibleInsets = new Rect(visibleInsets); 3814 ri.newConfig = newConfig; 3815 msg.obj = ri; 3816 mHandler.sendMessage(msg); 3817 } 3818 3819 /** 3820 * Represents a pending input event that is waiting in a queue. 3821 * 3822 * Input events are processed in serial order by the timestamp specified by 3823 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 3824 * one input event to the application at a time and waits for the application 3825 * to finish handling it before delivering the next one. 3826 * 3827 * However, because the application or IME can synthesize and inject multiple 3828 * key events at a time without going through the input dispatcher, we end up 3829 * needing a queue on the application's side. 3830 */ 3831 private static final class QueuedInputEvent { 3832 public static final int FLAG_DELIVER_POST_IME = 1; 3833 3834 public QueuedInputEvent mNext; 3835 3836 public InputEvent mEvent; 3837 public InputEventReceiver mReceiver; 3838 public int mFlags; 3839 3840 // Used for latency calculations. 3841 public long mReceiveTimeNanos; 3842 public long mDeliverTimeNanos; 3843 public long mDeliverPostImeTimeNanos; 3844 } 3845 3846 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 3847 InputEventReceiver receiver, int flags) { 3848 QueuedInputEvent q = mQueuedInputEventPool; 3849 if (q != null) { 3850 mQueuedInputEventPoolSize -= 1; 3851 mQueuedInputEventPool = q.mNext; 3852 q.mNext = null; 3853 } else { 3854 q = new QueuedInputEvent(); 3855 } 3856 3857 q.mEvent = event; 3858 q.mReceiver = receiver; 3859 q.mFlags = flags; 3860 return q; 3861 } 3862 3863 private void recycleQueuedInputEvent(QueuedInputEvent q) { 3864 q.mEvent = null; 3865 q.mReceiver = null; 3866 3867 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 3868 mQueuedInputEventPoolSize += 1; 3869 q.mNext = mQueuedInputEventPool; 3870 mQueuedInputEventPool = q; 3871 } 3872 } 3873 3874 void enqueueInputEvent(InputEvent event) { 3875 enqueueInputEvent(event, null, 0, false); 3876 } 3877 3878 void enqueueInputEvent(InputEvent event, 3879 InputEventReceiver receiver, int flags, boolean processImmediately) { 3880 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 3881 3882 if (ViewDebug.DEBUG_LATENCY) { 3883 q.mReceiveTimeNanos = System.nanoTime(); 3884 q.mDeliverTimeNanos = 0; 3885 q.mDeliverPostImeTimeNanos = 0; 3886 } 3887 3888 // Always enqueue the input event in order, regardless of its time stamp. 3889 // We do this because the application or the IME may inject key events 3890 // in response to touch events and we want to ensure that the injected keys 3891 // are processed in the order they were received and we cannot trust that 3892 // the time stamp of injected events are monotonic. 3893 QueuedInputEvent last = mFirstPendingInputEvent; 3894 if (last == null) { 3895 mFirstPendingInputEvent = q; 3896 } else { 3897 while (last.mNext != null) { 3898 last = last.mNext; 3899 } 3900 last.mNext = q; 3901 } 3902 3903 if (processImmediately) { 3904 doProcessInputEvents(); 3905 } else { 3906 scheduleProcessInputEvents(); 3907 } 3908 } 3909 3910 private void scheduleProcessInputEvents() { 3911 if (!mProcessInputEventsScheduled) { 3912 mProcessInputEventsScheduled = true; 3913 mHandler.sendEmptyMessage(MSG_PROCESS_INPUT_EVENTS); 3914 } 3915 } 3916 3917 private void doProcessInputEvents() { 3918 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 3919 QueuedInputEvent q = mFirstPendingInputEvent; 3920 mFirstPendingInputEvent = q.mNext; 3921 q.mNext = null; 3922 mCurrentInputEvent = q; 3923 deliverInputEvent(q); 3924 } 3925 3926 // We are done processing all input events that we can process right now 3927 // so we can clear the pending flag immediately. 3928 if (mProcessInputEventsScheduled) { 3929 mProcessInputEventsScheduled = false; 3930 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 3931 } 3932 } 3933 3934 private void finishInputEvent(QueuedInputEvent q, boolean handled) { 3935 if (q != mCurrentInputEvent) { 3936 throw new IllegalStateException("finished input event out of order"); 3937 } 3938 3939 if (ViewDebug.DEBUG_LATENCY) { 3940 final long now = System.nanoTime(); 3941 final long eventTime = q.mEvent.getEventTimeNano(); 3942 final StringBuilder msg = new StringBuilder(); 3943 msg.append("Spent "); 3944 msg.append((now - q.mReceiveTimeNanos) * 0.000001f); 3945 msg.append("ms processing "); 3946 if (q.mEvent instanceof KeyEvent) { 3947 final KeyEvent keyEvent = (KeyEvent)q.mEvent; 3948 msg.append("key event, action="); 3949 msg.append(KeyEvent.actionToString(keyEvent.getAction())); 3950 } else { 3951 final MotionEvent motionEvent = (MotionEvent)q.mEvent; 3952 msg.append("motion event, action="); 3953 msg.append(MotionEvent.actionToString(motionEvent.getAction())); 3954 msg.append(", historySize="); 3955 msg.append(motionEvent.getHistorySize()); 3956 } 3957 msg.append(", handled="); 3958 msg.append(handled); 3959 msg.append(", received at +"); 3960 msg.append((q.mReceiveTimeNanos - eventTime) * 0.000001f); 3961 if (q.mDeliverTimeNanos != 0) { 3962 msg.append("ms, delivered at +"); 3963 msg.append((q.mDeliverTimeNanos - eventTime) * 0.000001f); 3964 } 3965 if (q.mDeliverPostImeTimeNanos != 0) { 3966 msg.append("ms, delivered post IME at +"); 3967 msg.append((q.mDeliverPostImeTimeNanos - eventTime) * 0.000001f); 3968 } 3969 msg.append("ms, finished at +"); 3970 msg.append((now - eventTime) * 0.000001f); 3971 msg.append("ms."); 3972 Log.d(ViewDebug.DEBUG_LATENCY_TAG, msg.toString()); 3973 } 3974 3975 if (q.mReceiver != null) { 3976 q.mReceiver.finishInputEvent(q.mEvent, handled); 3977 } else { 3978 q.mEvent.recycleIfNeededAfterDispatch(); 3979 } 3980 3981 recycleQueuedInputEvent(q); 3982 3983 mCurrentInputEvent = null; 3984 if (mFirstPendingInputEvent != null) { 3985 scheduleProcessInputEvents(); 3986 } 3987 } 3988 3989 final class FrameRunnable implements Runnable { 3990 @Override 3991 public void run() { 3992 mFrameScheduled = false; 3993 doFrame(); 3994 } 3995 } 3996 final FrameRunnable mFrameRunnable = new FrameRunnable(); 3997 boolean mFrameScheduled; 3998 3999 final class WindowInputEventReceiver extends InputEventReceiver { 4000 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 4001 super(inputChannel, looper); 4002 } 4003 4004 @Override 4005 public void onInputEvent(InputEvent event) { 4006 enqueueInputEvent(event, this, 0, true); 4007 } 4008 4009 @Override 4010 public void onBatchedInputEventPending() { 4011 scheduleFrame(); 4012 } 4013 } 4014 WindowInputEventReceiver mInputEventReceiver; 4015 4016 final class InvalidateOnAnimationRunnable implements Runnable { 4017 private boolean mPosted; 4018 private ArrayList<View> mViews = new ArrayList<View>(); 4019 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 4020 new ArrayList<AttachInfo.InvalidateInfo>(); 4021 private View[] mTempViews; 4022 private AttachInfo.InvalidateInfo[] mTempViewRects; 4023 4024 public void addView(View view) { 4025 synchronized (this) { 4026 mViews.add(view); 4027 postIfNeededLocked(); 4028 } 4029 } 4030 4031 public void addViewRect(AttachInfo.InvalidateInfo info) { 4032 synchronized (this) { 4033 mViewRects.add(info); 4034 postIfNeededLocked(); 4035 } 4036 } 4037 4038 public void removeView(View view) { 4039 synchronized (this) { 4040 mViews.remove(view); 4041 4042 for (int i = mViewRects.size(); i-- > 0; ) { 4043 AttachInfo.InvalidateInfo info = mViewRects.get(i); 4044 if (info.target == view) { 4045 mViewRects.remove(i); 4046 info.release(); 4047 } 4048 } 4049 4050 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 4051 mChoreographer.removeAnimationCallbacks(this); 4052 mPosted = false; 4053 } 4054 } 4055 } 4056 4057 @Override 4058 public void run() { 4059 final int viewCount; 4060 final int viewRectCount; 4061 synchronized (this) { 4062 mPosted = false; 4063 4064 viewCount = mViews.size(); 4065 if (viewCount != 0) { 4066 mTempViews = mViews.toArray(mTempViews != null 4067 ? mTempViews : new View[viewCount]); 4068 mViews.clear(); 4069 } 4070 4071 viewRectCount = mViewRects.size(); 4072 if (viewRectCount != 0) { 4073 mTempViewRects = mViewRects.toArray(mTempViewRects != null 4074 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 4075 mViewRects.clear(); 4076 } 4077 } 4078 4079 for (int i = 0; i < viewCount; i++) { 4080 mTempViews[i].invalidate(); 4081 } 4082 4083 for (int i = 0; i < viewRectCount; i++) { 4084 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 4085 info.target.invalidate(info.left, info.top, info.right, info.bottom); 4086 info.release(); 4087 } 4088 } 4089 4090 private void postIfNeededLocked() { 4091 if (!mPosted) { 4092 mChoreographer.postAnimationCallback(this); 4093 mPosted = true; 4094 } 4095 } 4096 } 4097 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 4098 new InvalidateOnAnimationRunnable(); 4099 4100 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 4101 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 4102 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4103 } 4104 4105 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 4106 long delayMilliseconds) { 4107 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 4108 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4109 } 4110 4111 public void dispatchInvalidateOnAnimation(View view) { 4112 mInvalidateOnAnimationRunnable.addView(view); 4113 } 4114 4115 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 4116 mInvalidateOnAnimationRunnable.addViewRect(info); 4117 } 4118 4119 public void cancelInvalidate(View view) { 4120 mHandler.removeMessages(MSG_INVALIDATE, view); 4121 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 4122 // them to the pool 4123 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 4124 mInvalidateOnAnimationRunnable.removeView(view); 4125 } 4126 4127 public void dispatchKey(KeyEvent event) { 4128 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 4129 msg.setAsynchronous(true); 4130 mHandler.sendMessage(msg); 4131 } 4132 4133 public void dispatchKeyFromIme(KeyEvent event) { 4134 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 4135 msg.setAsynchronous(true); 4136 mHandler.sendMessage(msg); 4137 } 4138 4139 public void dispatchAppVisibility(boolean visible) { 4140 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 4141 msg.arg1 = visible ? 1 : 0; 4142 mHandler.sendMessage(msg); 4143 } 4144 4145 public void dispatchScreenStatusChange(boolean on) { 4146 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATUS); 4147 msg.arg1 = on ? 1 : 0; 4148 mHandler.sendMessage(msg); 4149 } 4150 4151 public void dispatchGetNewSurface() { 4152 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 4153 mHandler.sendMessage(msg); 4154 } 4155 4156 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4157 Message msg = Message.obtain(); 4158 msg.what = MSG_WINDOW_FOCUS_CHANGED; 4159 msg.arg1 = hasFocus ? 1 : 0; 4160 msg.arg2 = inTouchMode ? 1 : 0; 4161 mHandler.sendMessage(msg); 4162 } 4163 4164 public void dispatchCloseSystemDialogs(String reason) { 4165 Message msg = Message.obtain(); 4166 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 4167 msg.obj = reason; 4168 mHandler.sendMessage(msg); 4169 } 4170 4171 public void dispatchDragEvent(DragEvent event) { 4172 final int what; 4173 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 4174 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 4175 mHandler.removeMessages(what); 4176 } else { 4177 what = MSG_DISPATCH_DRAG_EVENT; 4178 } 4179 Message msg = mHandler.obtainMessage(what, event); 4180 mHandler.sendMessage(msg); 4181 } 4182 4183 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4184 int localValue, int localChanges) { 4185 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 4186 args.seq = seq; 4187 args.globalVisibility = globalVisibility; 4188 args.localValue = localValue; 4189 args.localChanges = localChanges; 4190 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 4191 } 4192 4193 public void dispatchCheckFocus() { 4194 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 4195 // This will result in a call to checkFocus() below. 4196 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 4197 } 4198 } 4199 4200 /** 4201 * Post a callback to send a 4202 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4203 * This event is send at most once every 4204 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 4205 */ 4206 private void postSendWindowContentChangedCallback() { 4207 if (mSendWindowContentChangedAccessibilityEvent == null) { 4208 mSendWindowContentChangedAccessibilityEvent = 4209 new SendWindowContentChangedAccessibilityEvent(); 4210 } 4211 if (!mSendWindowContentChangedAccessibilityEvent.mIsPending) { 4212 mSendWindowContentChangedAccessibilityEvent.mIsPending = true; 4213 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 4214 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 4215 } 4216 } 4217 4218 /** 4219 * Remove a posted callback to send a 4220 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4221 */ 4222 private void removeSendWindowContentChangedCallback() { 4223 if (mSendWindowContentChangedAccessibilityEvent != null) { 4224 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 4225 } 4226 } 4227 4228 public boolean showContextMenuForChild(View originalView) { 4229 return false; 4230 } 4231 4232 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 4233 return null; 4234 } 4235 4236 public void createContextMenu(ContextMenu menu) { 4237 } 4238 4239 public void childDrawableStateChanged(View child) { 4240 } 4241 4242 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 4243 if (mView == null) { 4244 return false; 4245 } 4246 mAccessibilityManager.sendAccessibilityEvent(event); 4247 return true; 4248 } 4249 4250 void checkThread() { 4251 if (mThread != Thread.currentThread()) { 4252 throw new CalledFromWrongThreadException( 4253 "Only the original thread that created a view hierarchy can touch its views."); 4254 } 4255 } 4256 4257 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4258 // ViewAncestor never intercepts touch event, so this can be a no-op 4259 } 4260 4261 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 4262 boolean immediate) { 4263 return scrollToRectOrFocus(rectangle, immediate); 4264 } 4265 4266 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 4267 // Do nothing. 4268 } 4269 4270 class TakenSurfaceHolder extends BaseSurfaceHolder { 4271 @Override 4272 public boolean onAllowLockCanvas() { 4273 return mDrawingAllowed; 4274 } 4275 4276 @Override 4277 public void onRelayoutContainer() { 4278 // Not currently interesting -- from changing between fixed and layout size. 4279 } 4280 4281 public void setFormat(int format) { 4282 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4283 } 4284 4285 public void setType(int type) { 4286 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4287 } 4288 4289 @Override 4290 public void onUpdateSurface() { 4291 // We take care of format and type changes on our own. 4292 throw new IllegalStateException("Shouldn't be here"); 4293 } 4294 4295 public boolean isCreating() { 4296 return mIsCreating; 4297 } 4298 4299 @Override 4300 public void setFixedSize(int width, int height) { 4301 throw new UnsupportedOperationException( 4302 "Currently only support sizing from layout"); 4303 } 4304 4305 public void setKeepScreenOn(boolean screenOn) { 4306 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4307 } 4308 } 4309 4310 static class InputMethodCallback extends IInputMethodCallback.Stub { 4311 private WeakReference<ViewRootImpl> mViewAncestor; 4312 4313 public InputMethodCallback(ViewRootImpl viewAncestor) { 4314 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4315 } 4316 4317 public void finishedEvent(int seq, boolean handled) { 4318 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4319 if (viewAncestor != null) { 4320 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4321 } 4322 } 4323 4324 public void sessionCreated(IInputMethodSession session) { 4325 // Stub -- not for use in the client. 4326 } 4327 } 4328 4329 static class W extends IWindow.Stub { 4330 private final WeakReference<ViewRootImpl> mViewAncestor; 4331 4332 W(ViewRootImpl viewAncestor) { 4333 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4334 } 4335 4336 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets, 4337 boolean reportDraw, Configuration newConfig) { 4338 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4339 if (viewAncestor != null) { 4340 viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, 4341 newConfig); 4342 } 4343 } 4344 4345 public void dispatchAppVisibility(boolean visible) { 4346 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4347 if (viewAncestor != null) { 4348 viewAncestor.dispatchAppVisibility(visible); 4349 } 4350 } 4351 4352 public void dispatchScreenStatus(boolean on) { 4353 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4354 if (viewAncestor != null) { 4355 viewAncestor.dispatchScreenStatusChange(on); 4356 } 4357 } 4358 4359 public void dispatchGetNewSurface() { 4360 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4361 if (viewAncestor != null) { 4362 viewAncestor.dispatchGetNewSurface(); 4363 } 4364 } 4365 4366 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4367 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4368 if (viewAncestor != null) { 4369 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4370 } 4371 } 4372 4373 private static int checkCallingPermission(String permission) { 4374 try { 4375 return ActivityManagerNative.getDefault().checkPermission( 4376 permission, Binder.getCallingPid(), Binder.getCallingUid()); 4377 } catch (RemoteException e) { 4378 return PackageManager.PERMISSION_DENIED; 4379 } 4380 } 4381 4382 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 4383 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4384 if (viewAncestor != null) { 4385 final View view = viewAncestor.mView; 4386 if (view != null) { 4387 if (checkCallingPermission(Manifest.permission.DUMP) != 4388 PackageManager.PERMISSION_GRANTED) { 4389 throw new SecurityException("Insufficient permissions to invoke" 4390 + " executeCommand() from pid=" + Binder.getCallingPid() 4391 + ", uid=" + Binder.getCallingUid()); 4392 } 4393 4394 OutputStream clientStream = null; 4395 try { 4396 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 4397 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 4398 } catch (IOException e) { 4399 e.printStackTrace(); 4400 } finally { 4401 if (clientStream != null) { 4402 try { 4403 clientStream.close(); 4404 } catch (IOException e) { 4405 e.printStackTrace(); 4406 } 4407 } 4408 } 4409 } 4410 } 4411 } 4412 4413 public void closeSystemDialogs(String reason) { 4414 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4415 if (viewAncestor != null) { 4416 viewAncestor.dispatchCloseSystemDialogs(reason); 4417 } 4418 } 4419 4420 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 4421 boolean sync) { 4422 if (sync) { 4423 try { 4424 sWindowSession.wallpaperOffsetsComplete(asBinder()); 4425 } catch (RemoteException e) { 4426 } 4427 } 4428 } 4429 4430 public void dispatchWallpaperCommand(String action, int x, int y, 4431 int z, Bundle extras, boolean sync) { 4432 if (sync) { 4433 try { 4434 sWindowSession.wallpaperCommandComplete(asBinder(), null); 4435 } catch (RemoteException e) { 4436 } 4437 } 4438 } 4439 4440 /* Drag/drop */ 4441 public void dispatchDragEvent(DragEvent event) { 4442 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4443 if (viewAncestor != null) { 4444 viewAncestor.dispatchDragEvent(event); 4445 } 4446 } 4447 4448 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4449 int localValue, int localChanges) { 4450 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4451 if (viewAncestor != null) { 4452 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 4453 localValue, localChanges); 4454 } 4455 } 4456 } 4457 4458 /** 4459 * Maintains state information for a single trackball axis, generating 4460 * discrete (DPAD) movements based on raw trackball motion. 4461 */ 4462 static final class TrackballAxis { 4463 /** 4464 * The maximum amount of acceleration we will apply. 4465 */ 4466 static final float MAX_ACCELERATION = 20; 4467 4468 /** 4469 * The maximum amount of time (in milliseconds) between events in order 4470 * for us to consider the user to be doing fast trackball movements, 4471 * and thus apply an acceleration. 4472 */ 4473 static final long FAST_MOVE_TIME = 150; 4474 4475 /** 4476 * Scaling factor to the time (in milliseconds) between events to how 4477 * much to multiple/divide the current acceleration. When movement 4478 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4479 * FAST_MOVE_TIME it divides it. 4480 */ 4481 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4482 4483 float position; 4484 float absPosition; 4485 float acceleration = 1; 4486 long lastMoveTime = 0; 4487 int step; 4488 int dir; 4489 int nonAccelMovement; 4490 4491 void reset(int _step) { 4492 position = 0; 4493 acceleration = 1; 4494 lastMoveTime = 0; 4495 step = _step; 4496 dir = 0; 4497 } 4498 4499 /** 4500 * Add trackball movement into the state. If the direction of movement 4501 * has been reversed, the state is reset before adding the 4502 * movement (so that you don't have to compensate for any previously 4503 * collected movement before see the result of the movement in the 4504 * new direction). 4505 * 4506 * @return Returns the absolute value of the amount of movement 4507 * collected so far. 4508 */ 4509 float collect(float off, long time, String axis) { 4510 long normTime; 4511 if (off > 0) { 4512 normTime = (long)(off * FAST_MOVE_TIME); 4513 if (dir < 0) { 4514 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4515 position = 0; 4516 step = 0; 4517 acceleration = 1; 4518 lastMoveTime = 0; 4519 } 4520 dir = 1; 4521 } else if (off < 0) { 4522 normTime = (long)((-off) * FAST_MOVE_TIME); 4523 if (dir > 0) { 4524 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4525 position = 0; 4526 step = 0; 4527 acceleration = 1; 4528 lastMoveTime = 0; 4529 } 4530 dir = -1; 4531 } else { 4532 normTime = 0; 4533 } 4534 4535 // The number of milliseconds between each movement that is 4536 // considered "normal" and will not result in any acceleration 4537 // or deceleration, scaled by the offset we have here. 4538 if (normTime > 0) { 4539 long delta = time - lastMoveTime; 4540 lastMoveTime = time; 4541 float acc = acceleration; 4542 if (delta < normTime) { 4543 // The user is scrolling rapidly, so increase acceleration. 4544 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4545 if (scale > 1) acc *= scale; 4546 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4547 + off + " normTime=" + normTime + " delta=" + delta 4548 + " scale=" + scale + " acc=" + acc); 4549 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4550 } else { 4551 // The user is scrolling slowly, so decrease acceleration. 4552 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4553 if (scale > 1) acc /= scale; 4554 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4555 + off + " normTime=" + normTime + " delta=" + delta 4556 + " scale=" + scale + " acc=" + acc); 4557 acceleration = acc > 1 ? acc : 1; 4558 } 4559 } 4560 position += off; 4561 return (absPosition = Math.abs(position)); 4562 } 4563 4564 /** 4565 * Generate the number of discrete movement events appropriate for 4566 * the currently collected trackball movement. 4567 * 4568 * @param precision The minimum movement required to generate the 4569 * first discrete movement. 4570 * 4571 * @return Returns the number of discrete movements, either positive 4572 * or negative, or 0 if there is not enough trackball movement yet 4573 * for a discrete movement. 4574 */ 4575 int generate(float precision) { 4576 int movement = 0; 4577 nonAccelMovement = 0; 4578 do { 4579 final int dir = position >= 0 ? 1 : -1; 4580 switch (step) { 4581 // If we are going to execute the first step, then we want 4582 // to do this as soon as possible instead of waiting for 4583 // a full movement, in order to make things look responsive. 4584 case 0: 4585 if (absPosition < precision) { 4586 return movement; 4587 } 4588 movement += dir; 4589 nonAccelMovement += dir; 4590 step = 1; 4591 break; 4592 // If we have generated the first movement, then we need 4593 // to wait for the second complete trackball motion before 4594 // generating the second discrete movement. 4595 case 1: 4596 if (absPosition < 2) { 4597 return movement; 4598 } 4599 movement += dir; 4600 nonAccelMovement += dir; 4601 position += dir > 0 ? -2 : 2; 4602 absPosition = Math.abs(position); 4603 step = 2; 4604 break; 4605 // After the first two, we generate discrete movements 4606 // consistently with the trackball, applying an acceleration 4607 // if the trackball is moving quickly. This is a simple 4608 // acceleration on top of what we already compute based 4609 // on how quickly the wheel is being turned, to apply 4610 // a longer increasing acceleration to continuous movement 4611 // in one direction. 4612 default: 4613 if (absPosition < 1) { 4614 return movement; 4615 } 4616 movement += dir; 4617 position += dir >= 0 ? -1 : 1; 4618 absPosition = Math.abs(position); 4619 float acc = acceleration; 4620 acc *= 1.1f; 4621 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4622 break; 4623 } 4624 } while (true); 4625 } 4626 } 4627 4628 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 4629 public CalledFromWrongThreadException(String msg) { 4630 super(msg); 4631 } 4632 } 4633 4634 private SurfaceHolder mHolder = new SurfaceHolder() { 4635 // we only need a SurfaceHolder for opengl. it would be nice 4636 // to implement everything else though, especially the callback 4637 // support (opengl doesn't make use of it right now, but eventually 4638 // will). 4639 public Surface getSurface() { 4640 return mSurface; 4641 } 4642 4643 public boolean isCreating() { 4644 return false; 4645 } 4646 4647 public void addCallback(Callback callback) { 4648 } 4649 4650 public void removeCallback(Callback callback) { 4651 } 4652 4653 public void setFixedSize(int width, int height) { 4654 } 4655 4656 public void setSizeFromLayout() { 4657 } 4658 4659 public void setFormat(int format) { 4660 } 4661 4662 public void setType(int type) { 4663 } 4664 4665 public void setKeepScreenOn(boolean screenOn) { 4666 } 4667 4668 public Canvas lockCanvas() { 4669 return null; 4670 } 4671 4672 public Canvas lockCanvas(Rect dirty) { 4673 return null; 4674 } 4675 4676 public void unlockCanvasAndPost(Canvas canvas) { 4677 } 4678 public Rect getSurfaceFrame() { 4679 return null; 4680 } 4681 }; 4682 4683 static RunQueue getRunQueue() { 4684 RunQueue rq = sRunQueues.get(); 4685 if (rq != null) { 4686 return rq; 4687 } 4688 rq = new RunQueue(); 4689 sRunQueues.set(rq); 4690 return rq; 4691 } 4692 4693 /** 4694 * The run queue is used to enqueue pending work from Views when no Handler is 4695 * attached. The work is executed during the next call to performTraversals on 4696 * the thread. 4697 * @hide 4698 */ 4699 static final class RunQueue { 4700 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 4701 4702 void post(Runnable action) { 4703 postDelayed(action, 0); 4704 } 4705 4706 void postDelayed(Runnable action, long delayMillis) { 4707 HandlerAction handlerAction = new HandlerAction(); 4708 handlerAction.action = action; 4709 handlerAction.delay = delayMillis; 4710 4711 synchronized (mActions) { 4712 mActions.add(handlerAction); 4713 } 4714 } 4715 4716 void removeCallbacks(Runnable action) { 4717 final HandlerAction handlerAction = new HandlerAction(); 4718 handlerAction.action = action; 4719 4720 synchronized (mActions) { 4721 final ArrayList<HandlerAction> actions = mActions; 4722 4723 while (actions.remove(handlerAction)) { 4724 // Keep going 4725 } 4726 } 4727 } 4728 4729 void executeActions(Handler handler) { 4730 synchronized (mActions) { 4731 final ArrayList<HandlerAction> actions = mActions; 4732 final int count = actions.size(); 4733 4734 for (int i = 0; i < count; i++) { 4735 final HandlerAction handlerAction = actions.get(i); 4736 handler.postDelayed(handlerAction.action, handlerAction.delay); 4737 } 4738 4739 actions.clear(); 4740 } 4741 } 4742 4743 private static class HandlerAction { 4744 Runnable action; 4745 long delay; 4746 4747 @Override 4748 public boolean equals(Object o) { 4749 if (this == o) return true; 4750 if (o == null || getClass() != o.getClass()) return false; 4751 4752 HandlerAction that = (HandlerAction) o; 4753 return !(action != null ? !action.equals(that.action) : that.action != null); 4754 4755 } 4756 4757 @Override 4758 public int hashCode() { 4759 int result = action != null ? action.hashCode() : 0; 4760 result = 31 * result + (int) (delay ^ (delay >>> 32)); 4761 return result; 4762 } 4763 } 4764 } 4765 4766 /** 4767 * Class for managing the accessibility interaction connection 4768 * based on the global accessibility state. 4769 */ 4770 final class AccessibilityInteractionConnectionManager 4771 implements AccessibilityStateChangeListener { 4772 public void onAccessibilityStateChanged(boolean enabled) { 4773 if (enabled) { 4774 ensureConnection(); 4775 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 4776 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 4777 View focusedView = mView.findFocus(); 4778 if (focusedView != null && focusedView != mView) { 4779 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4780 } 4781 } 4782 } else { 4783 ensureNoConnection(); 4784 } 4785 } 4786 4787 public void ensureConnection() { 4788 if (mAttachInfo != null) { 4789 final boolean registered = 4790 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 4791 if (!registered) { 4792 mAttachInfo.mAccessibilityWindowId = 4793 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 4794 new AccessibilityInteractionConnection(ViewRootImpl.this)); 4795 } 4796 } 4797 } 4798 4799 public void ensureNoConnection() { 4800 final boolean registered = 4801 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 4802 if (registered) { 4803 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 4804 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 4805 } 4806 } 4807 } 4808 4809 /** 4810 * This class is an interface this ViewAncestor provides to the 4811 * AccessibilityManagerService to the latter can interact with 4812 * the view hierarchy in this ViewAncestor. 4813 */ 4814 static final class AccessibilityInteractionConnection 4815 extends IAccessibilityInteractionConnection.Stub { 4816 private final WeakReference<ViewRootImpl> mViewRootImpl; 4817 4818 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 4819 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 4820 } 4821 4822 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 4823 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4824 int prefetchFlags, int interrogatingPid, long interrogatingTid) { 4825 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4826 if (viewRootImpl != null && viewRootImpl.mView != null) { 4827 viewRootImpl.getAccessibilityInteractionController() 4828 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 4829 interactionId, callback, prefetchFlags, interrogatingPid, interrogatingTid); 4830 } else { 4831 // We cannot make the call and notify the caller so it does not wait. 4832 try { 4833 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 4834 } catch (RemoteException re) { 4835 /* best effort - ignore */ 4836 } 4837 } 4838 } 4839 4840 public void performAccessibilityAction(long accessibilityNodeId, int action, 4841 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4842 int interogatingPid, long interrogatingTid) { 4843 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4844 if (viewRootImpl != null && viewRootImpl.mView != null) { 4845 viewRootImpl.getAccessibilityInteractionController() 4846 .performAccessibilityActionClientThread(accessibilityNodeId, action, 4847 interactionId, callback, interogatingPid, interrogatingTid); 4848 } else { 4849 // We cannot make the call and notify the caller so it does not 4850 try { 4851 callback.setPerformAccessibilityActionResult(false, interactionId); 4852 } catch (RemoteException re) { 4853 /* best effort - ignore */ 4854 } 4855 } 4856 } 4857 4858 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId, 4859 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4860 int interrogatingPid, long interrogatingTid) { 4861 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4862 if (viewRootImpl != null && viewRootImpl.mView != null) { 4863 viewRootImpl.getAccessibilityInteractionController() 4864 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId, 4865 interactionId, callback, interrogatingPid, interrogatingTid); 4866 } else { 4867 // We cannot make the call and notify the caller so it does not 4868 try { 4869 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 4870 } catch (RemoteException re) { 4871 /* best effort - ignore */ 4872 } 4873 } 4874 } 4875 4876 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 4877 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4878 int interrogatingPid, long interrogatingTid) { 4879 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4880 if (viewRootImpl != null && viewRootImpl.mView != null) { 4881 viewRootImpl.getAccessibilityInteractionController() 4882 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 4883 interactionId, callback, interrogatingPid, interrogatingTid); 4884 } else { 4885 // We cannot make the call and notify the caller so it does not 4886 try { 4887 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 4888 } catch (RemoteException re) { 4889 /* best effort - ignore */ 4890 } 4891 } 4892 } 4893 } 4894 4895 /** 4896 * Class for managing accessibility interactions initiated from the system 4897 * and targeting the view hierarchy. A *ClientThread method is to be 4898 * called from the interaction connection this ViewAncestor gives the 4899 * system to talk to it and a corresponding *UiThread method that is executed 4900 * on the UI thread. 4901 */ 4902 final class AccessibilityInteractionController { 4903 private static final int POOL_SIZE = 5; 4904 4905 private ArrayList<AccessibilityNodeInfo> mTempAccessibilityNodeInfoList = 4906 new ArrayList<AccessibilityNodeInfo>(); 4907 4908 // Reusable poolable arguments for interacting with the view hierarchy 4909 // to fit more arguments than Message and to avoid sharing objects between 4910 // two messages since several threads can send messages concurrently. 4911 private final Pool<SomeArgs> mPool = Pools.synchronizedPool(Pools.finitePool( 4912 new PoolableManager<SomeArgs>() { 4913 public SomeArgs newInstance() { 4914 return new SomeArgs(); 4915 } 4916 4917 public void onAcquired(SomeArgs info) { 4918 /* do nothing */ 4919 } 4920 4921 public void onReleased(SomeArgs info) { 4922 info.clear(); 4923 } 4924 }, POOL_SIZE) 4925 ); 4926 4927 public class SomeArgs implements Poolable<SomeArgs> { 4928 private SomeArgs mNext; 4929 private boolean mIsPooled; 4930 4931 public Object arg1; 4932 public Object arg2; 4933 public int argi1; 4934 public int argi2; 4935 public int argi3; 4936 4937 public SomeArgs getNextPoolable() { 4938 return mNext; 4939 } 4940 4941 public boolean isPooled() { 4942 return mIsPooled; 4943 } 4944 4945 public void setNextPoolable(SomeArgs args) { 4946 mNext = args; 4947 } 4948 4949 public void setPooled(boolean isPooled) { 4950 mIsPooled = isPooled; 4951 } 4952 4953 private void clear() { 4954 arg1 = null; 4955 arg2 = null; 4956 argi1 = 0; 4957 argi2 = 0; 4958 argi3 = 0; 4959 } 4960 } 4961 4962 public void findAccessibilityNodeInfoByAccessibilityIdClientThread( 4963 long accessibilityNodeId, int interactionId, 4964 IAccessibilityInteractionConnectionCallback callback, int prefetchFlags, 4965 int interrogatingPid, long interrogatingTid) { 4966 Message message = mHandler.obtainMessage(); 4967 message.what = MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID; 4968 message.arg1 = prefetchFlags; 4969 SomeArgs args = mPool.acquire(); 4970 args.argi1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 4971 args.argi2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 4972 args.argi3 = interactionId; 4973 args.arg1 = callback; 4974 message.obj = args; 4975 // If the interrogation is performed by the same thread as the main UI 4976 // thread in this process, set the message as a static reference so 4977 // after this call completes the same thread but in the interrogating 4978 // client can handle the message to generate the result. 4979 if (interrogatingPid == Process.myPid() 4980 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 4981 AccessibilityInteractionClient.getInstanceForThread( 4982 interrogatingTid).setSameThreadMessage(message); 4983 } else { 4984 mHandler.sendMessage(message); 4985 } 4986 } 4987 4988 public void findAccessibilityNodeInfoByAccessibilityIdUiThread(Message message) { 4989 final int prefetchFlags = message.arg1; 4990 SomeArgs args = (SomeArgs) message.obj; 4991 final int accessibilityViewId = args.argi1; 4992 final int virtualDescendantId = args.argi2; 4993 final int interactionId = args.argi3; 4994 final IAccessibilityInteractionConnectionCallback callback = 4995 (IAccessibilityInteractionConnectionCallback) args.arg1; 4996 mPool.release(args); 4997 List<AccessibilityNodeInfo> infos = mTempAccessibilityNodeInfoList; 4998 infos.clear(); 4999 try { 5000 View target = null; 5001 if (accessibilityViewId == AccessibilityNodeInfo.UNDEFINED) { 5002 target = ViewRootImpl.this.mView; 5003 } else { 5004 target = findViewByAccessibilityId(accessibilityViewId); 5005 } 5006 if (target != null && target.getVisibility() == View.VISIBLE) { 5007 getAccessibilityNodePrefetcher().prefetchAccessibilityNodeInfos(target, 5008 virtualDescendantId, prefetchFlags, infos); 5009 } 5010 } finally { 5011 try { 5012 callback.setFindAccessibilityNodeInfosResult(infos, interactionId); 5013 infos.clear(); 5014 } catch (RemoteException re) { 5015 /* ignore - the other side will time out */ 5016 } 5017 } 5018 } 5019 5020 public void findAccessibilityNodeInfoByViewIdClientThread(long accessibilityNodeId, 5021 int viewId, int interactionId, IAccessibilityInteractionConnectionCallback callback, 5022 int interrogatingPid, long interrogatingTid) { 5023 Message message = mHandler.obtainMessage(); 5024 message.what = MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID; 5025 message.arg1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 5026 SomeArgs args = mPool.acquire(); 5027 args.argi1 = viewId; 5028 args.argi2 = interactionId; 5029 args.arg1 = callback; 5030 message.obj = args; 5031 // If the interrogation is performed by the same thread as the main UI 5032 // thread in this process, set the message as a static reference so 5033 // after this call completes the same thread but in the interrogating 5034 // client can handle the message to generate the result. 5035 if (interrogatingPid == Process.myPid() 5036 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 5037 AccessibilityInteractionClient.getInstanceForThread( 5038 interrogatingTid).setSameThreadMessage(message); 5039 } else { 5040 mHandler.sendMessage(message); 5041 } 5042 } 5043 5044 public void findAccessibilityNodeInfoByViewIdUiThread(Message message) { 5045 final int accessibilityViewId = message.arg1; 5046 SomeArgs args = (SomeArgs) message.obj; 5047 final int viewId = args.argi1; 5048 final int interactionId = args.argi2; 5049 final IAccessibilityInteractionConnectionCallback callback = 5050 (IAccessibilityInteractionConnectionCallback) args.arg1; 5051 mPool.release(args); 5052 AccessibilityNodeInfo info = null; 5053 try { 5054 View root = null; 5055 if (accessibilityViewId != AccessibilityNodeInfo.UNDEFINED) { 5056 root = findViewByAccessibilityId(accessibilityViewId); 5057 } else { 5058 root = ViewRootImpl.this.mView; 5059 } 5060 if (root != null) { 5061 View target = root.findViewById(viewId); 5062 if (target != null && target.getVisibility() == View.VISIBLE) { 5063 info = target.createAccessibilityNodeInfo(); 5064 } 5065 } 5066 } finally { 5067 try { 5068 callback.setFindAccessibilityNodeInfoResult(info, interactionId); 5069 } catch (RemoteException re) { 5070 /* ignore - the other side will time out */ 5071 } 5072 } 5073 } 5074 5075 public void findAccessibilityNodeInfosByTextClientThread(long accessibilityNodeId, 5076 String text, int interactionId, 5077 IAccessibilityInteractionConnectionCallback callback, int interrogatingPid, 5078 long interrogatingTid) { 5079 Message message = mHandler.obtainMessage(); 5080 message.what = MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT; 5081 SomeArgs args = mPool.acquire(); 5082 args.arg1 = text; 5083 args.argi1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 5084 args.argi2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 5085 args.argi3 = interactionId; 5086 args.arg2 = callback; 5087 message.obj = args; 5088 // If the interrogation is performed by the same thread as the main UI 5089 // thread in this process, set the message as a static reference so 5090 // after this call completes the same thread but in the interrogating 5091 // client can handle the message to generate the result. 5092 if (interrogatingPid == Process.myPid() 5093 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 5094 AccessibilityInteractionClient.getInstanceForThread( 5095 interrogatingTid).setSameThreadMessage(message); 5096 } else { 5097 mHandler.sendMessage(message); 5098 } 5099 } 5100 5101 public void findAccessibilityNodeInfosByTextUiThread(Message message) { 5102 SomeArgs args = (SomeArgs) message.obj; 5103 final String text = (String) args.arg1; 5104 final int accessibilityViewId = args.argi1; 5105 final int virtualDescendantId = args.argi2; 5106 final int interactionId = args.argi3; 5107 final IAccessibilityInteractionConnectionCallback callback = 5108 (IAccessibilityInteractionConnectionCallback) args.arg2; 5109 mPool.release(args); 5110 List<AccessibilityNodeInfo> infos = null; 5111 try { 5112 View target; 5113 if (accessibilityViewId != AccessibilityNodeInfo.UNDEFINED) { 5114 target = findViewByAccessibilityId(accessibilityViewId); 5115 } else { 5116 target = ViewRootImpl.this.mView; 5117 } 5118 if (target != null && target.getVisibility() == View.VISIBLE) { 5119 AccessibilityNodeProvider provider = target.getAccessibilityNodeProvider(); 5120 if (provider != null) { 5121 infos = provider.findAccessibilityNodeInfosByText(text, 5122 virtualDescendantId); 5123 } else if (virtualDescendantId == AccessibilityNodeInfo.UNDEFINED) { 5124 ArrayList<View> foundViews = mAttachInfo.mFocusablesTempList; 5125 foundViews.clear(); 5126 target.findViewsWithText(foundViews, text, View.FIND_VIEWS_WITH_TEXT 5127 | View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5128 | View.FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS); 5129 if (!foundViews.isEmpty()) { 5130 infos = mTempAccessibilityNodeInfoList; 5131 infos.clear(); 5132 final int viewCount = foundViews.size(); 5133 for (int i = 0; i < viewCount; i++) { 5134 View foundView = foundViews.get(i); 5135 if (foundView.getVisibility() == View.VISIBLE) { 5136 provider = foundView.getAccessibilityNodeProvider(); 5137 if (provider != null) { 5138 List<AccessibilityNodeInfo> infosFromProvider = 5139 provider.findAccessibilityNodeInfosByText(text, 5140 virtualDescendantId); 5141 if (infosFromProvider != null) { 5142 infos.addAll(infosFromProvider); 5143 } 5144 } else { 5145 infos.add(foundView.createAccessibilityNodeInfo()); 5146 } 5147 } 5148 } 5149 } 5150 } 5151 } 5152 } finally { 5153 try { 5154 callback.setFindAccessibilityNodeInfosResult(infos, interactionId); 5155 } catch (RemoteException re) { 5156 /* ignore - the other side will time out */ 5157 } 5158 } 5159 } 5160 5161 public void performAccessibilityActionClientThread(long accessibilityNodeId, int action, 5162 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5163 int interogatingPid, long interrogatingTid) { 5164 Message message = mHandler.obtainMessage(); 5165 message.what = MSG_PERFORM_ACCESSIBILITY_ACTION; 5166 message.arg1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 5167 message.arg2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 5168 SomeArgs args = mPool.acquire(); 5169 args.argi1 = action; 5170 args.argi2 = interactionId; 5171 args.arg1 = callback; 5172 message.obj = args; 5173 // If the interrogation is performed by the same thread as the main UI 5174 // thread in this process, set the message as a static reference so 5175 // after this call completes the same thread but in the interrogating 5176 // client can handle the message to generate the result. 5177 if (interogatingPid == Process.myPid() 5178 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 5179 AccessibilityInteractionClient.getInstanceForThread( 5180 interrogatingTid).setSameThreadMessage(message); 5181 } else { 5182 mHandler.sendMessage(message); 5183 } 5184 } 5185 5186 public void perfromAccessibilityActionUiThread(Message message) { 5187 final int accessibilityViewId = message.arg1; 5188 final int virtualDescendantId = message.arg2; 5189 SomeArgs args = (SomeArgs) message.obj; 5190 final int action = args.argi1; 5191 final int interactionId = args.argi2; 5192 final IAccessibilityInteractionConnectionCallback callback = 5193 (IAccessibilityInteractionConnectionCallback) args.arg1; 5194 mPool.release(args); 5195 boolean succeeded = false; 5196 try { 5197 View target = findViewByAccessibilityId(accessibilityViewId); 5198 if (target != null && target.getVisibility() == View.VISIBLE) { 5199 AccessibilityNodeProvider provider = target.getAccessibilityNodeProvider(); 5200 if (provider != null) { 5201 succeeded = provider.performAccessibilityAction(action, 5202 virtualDescendantId); 5203 } else if (virtualDescendantId == AccessibilityNodeInfo.UNDEFINED) { 5204 switch (action) { 5205 case AccessibilityNodeInfo.ACTION_FOCUS: { 5206 if (!target.hasFocus()) { 5207 // Get out of touch mode since accessibility 5208 // wants to move focus around. 5209 ensureTouchMode(false); 5210 succeeded = target.requestFocus(); 5211 } 5212 } break; 5213 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 5214 if (target.hasFocus()) { 5215 target.clearFocus(); 5216 succeeded = !target.isFocused(); 5217 } 5218 } break; 5219 case AccessibilityNodeInfo.ACTION_SELECT: { 5220 if (!target.isSelected()) { 5221 target.setSelected(true); 5222 succeeded = target.isSelected(); 5223 } 5224 } break; 5225 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 5226 if (target.isSelected()) { 5227 target.setSelected(false); 5228 succeeded = !target.isSelected(); 5229 } 5230 } break; 5231 } 5232 } 5233 } 5234 } finally { 5235 try { 5236 callback.setPerformAccessibilityActionResult(succeeded, interactionId); 5237 } catch (RemoteException re) { 5238 /* ignore - the other side will time out */ 5239 } 5240 } 5241 } 5242 5243 private View findViewByAccessibilityId(int accessibilityId) { 5244 View root = ViewRootImpl.this.mView; 5245 if (root == null) { 5246 return null; 5247 } 5248 View foundView = root.findViewByAccessibilityId(accessibilityId); 5249 if (foundView != null && foundView.getVisibility() != View.VISIBLE) { 5250 return null; 5251 } 5252 return foundView; 5253 } 5254 } 5255 5256 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 5257 public volatile boolean mIsPending; 5258 5259 public void run() { 5260 if (mView != null) { 5261 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 5262 mIsPending = false; 5263 } 5264 } 5265 } 5266 5267 /** 5268 * This class encapsulates a prefetching strategy for the accessibility APIs for 5269 * querying window content. It is responsible to prefetch a batch of 5270 * AccessibilityNodeInfos in addition to the one for a requested node. 5271 */ 5272 class AccessibilityNodePrefetcher { 5273 5274 private static final int MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE = 50; 5275 5276 public void prefetchAccessibilityNodeInfos(View view, int virtualViewId, int prefetchFlags, 5277 List<AccessibilityNodeInfo> outInfos) { 5278 AccessibilityNodeProvider provider = view.getAccessibilityNodeProvider(); 5279 if (provider == null) { 5280 AccessibilityNodeInfo root = view.createAccessibilityNodeInfo(); 5281 if (root != null) { 5282 outInfos.add(root); 5283 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_PREDECESSORS) != 0) { 5284 prefetchPredecessorsOfRealNode(view, outInfos); 5285 } 5286 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_SIBLINGS) != 0) { 5287 prefetchSiblingsOfRealNode(view, outInfos); 5288 } 5289 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_DESCENDANTS) != 0) { 5290 prefetchDescendantsOfRealNode(view, outInfos); 5291 } 5292 } 5293 } else { 5294 AccessibilityNodeInfo root = provider.createAccessibilityNodeInfo(virtualViewId); 5295 if (root != null) { 5296 outInfos.add(root); 5297 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_PREDECESSORS) != 0) { 5298 prefetchPredecessorsOfVirtualNode(root, view, provider, outInfos); 5299 } 5300 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_SIBLINGS) != 0) { 5301 prefetchSiblingsOfVirtualNode(root, view, provider, outInfos); 5302 } 5303 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_DESCENDANTS) != 0) { 5304 prefetchDescendantsOfVirtualNode(root, provider, outInfos); 5305 } 5306 } 5307 } 5308 } 5309 5310 private void prefetchPredecessorsOfRealNode(View view, 5311 List<AccessibilityNodeInfo> outInfos) { 5312 ViewParent parent = view.getParent(); 5313 while (parent instanceof View 5314 && outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5315 View parentView = (View) parent; 5316 final long parentNodeId = AccessibilityNodeInfo.makeNodeId( 5317 parentView.getAccessibilityViewId(), AccessibilityNodeInfo.UNDEFINED); 5318 AccessibilityNodeInfo info = parentView.createAccessibilityNodeInfo(); 5319 if (info != null) { 5320 outInfos.add(info); 5321 } 5322 parent = parent.getParent(); 5323 } 5324 } 5325 5326 private void prefetchSiblingsOfRealNode(View current, 5327 List<AccessibilityNodeInfo> outInfos) { 5328 ViewParent parent = current.getParent(); 5329 if (parent instanceof ViewGroup) { 5330 ViewGroup parentGroup = (ViewGroup) parent; 5331 final int childCount = parentGroup.getChildCount(); 5332 for (int i = 0; i < childCount; i++) { 5333 View child = parentGroup.getChildAt(i); 5334 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE 5335 && child.getAccessibilityViewId() != current.getAccessibilityViewId() 5336 && child.getVisibility() == View.VISIBLE) { 5337 final long childNodeId = AccessibilityNodeInfo.makeNodeId( 5338 child.getAccessibilityViewId(), AccessibilityNodeInfo.UNDEFINED); 5339 AccessibilityNodeInfo info = null; 5340 AccessibilityNodeProvider provider = child.getAccessibilityNodeProvider(); 5341 if (provider == null) { 5342 info = child.createAccessibilityNodeInfo(); 5343 } else { 5344 info = provider.createAccessibilityNodeInfo( 5345 AccessibilityNodeInfo.UNDEFINED); 5346 } 5347 if (info != null) { 5348 outInfos.add(info); 5349 } 5350 } 5351 } 5352 } 5353 } 5354 5355 private void prefetchDescendantsOfRealNode(View root, 5356 List<AccessibilityNodeInfo> outInfos) { 5357 if (root instanceof ViewGroup) { 5358 ViewGroup rootGroup = (ViewGroup) root; 5359 HashMap<View, AccessibilityNodeInfo> addedChildren = 5360 new HashMap<View, AccessibilityNodeInfo>(); 5361 final int childCount = rootGroup.getChildCount(); 5362 for (int i = 0; i < childCount; i++) { 5363 View child = rootGroup.getChildAt(i); 5364 if (child.getVisibility() == View.VISIBLE 5365 && outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5366 final long childNodeId = AccessibilityNodeInfo.makeNodeId( 5367 child.getAccessibilityViewId(), AccessibilityNodeInfo.UNDEFINED); 5368 AccessibilityNodeProvider provider = child.getAccessibilityNodeProvider(); 5369 if (provider == null) { 5370 AccessibilityNodeInfo info = child.createAccessibilityNodeInfo(); 5371 if (info != null) { 5372 outInfos.add(info); 5373 addedChildren.put(child, null); 5374 } 5375 } else { 5376 AccessibilityNodeInfo info = provider.createAccessibilityNodeInfo( 5377 AccessibilityNodeInfo.UNDEFINED); 5378 if (info != null) { 5379 outInfos.add(info); 5380 addedChildren.put(child, info); 5381 } 5382 } 5383 } 5384 } 5385 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5386 for (Map.Entry<View, AccessibilityNodeInfo> entry : addedChildren.entrySet()) { 5387 View addedChild = entry.getKey(); 5388 AccessibilityNodeInfo virtualRoot = entry.getValue(); 5389 if (virtualRoot == null) { 5390 prefetchDescendantsOfRealNode(addedChild, outInfos); 5391 } else { 5392 AccessibilityNodeProvider provider = 5393 addedChild.getAccessibilityNodeProvider(); 5394 prefetchDescendantsOfVirtualNode(virtualRoot, provider, outInfos); 5395 } 5396 } 5397 } 5398 } 5399 } 5400 5401 private void prefetchPredecessorsOfVirtualNode(AccessibilityNodeInfo root, 5402 View providerHost, AccessibilityNodeProvider provider, 5403 List<AccessibilityNodeInfo> outInfos) { 5404 long parentNodeId = root.getParentNodeId(); 5405 int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(parentNodeId); 5406 while (accessibilityViewId != AccessibilityNodeInfo.UNDEFINED) { 5407 final int virtualDescendantId = 5408 AccessibilityNodeInfo.getVirtualDescendantId(parentNodeId); 5409 if (virtualDescendantId != AccessibilityNodeInfo.UNDEFINED 5410 || accessibilityViewId == providerHost.getAccessibilityViewId()) { 5411 AccessibilityNodeInfo parent = provider.createAccessibilityNodeInfo( 5412 virtualDescendantId); 5413 if (parent != null) { 5414 outInfos.add(parent); 5415 } 5416 parentNodeId = parent.getParentNodeId(); 5417 accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5418 parentNodeId); 5419 } else { 5420 prefetchPredecessorsOfRealNode(providerHost, outInfos); 5421 return; 5422 } 5423 } 5424 } 5425 5426 private void prefetchSiblingsOfVirtualNode(AccessibilityNodeInfo current, View providerHost, 5427 AccessibilityNodeProvider provider, List<AccessibilityNodeInfo> outInfos) { 5428 final long parentNodeId = current.getParentNodeId(); 5429 final int parentAccessibilityViewId = 5430 AccessibilityNodeInfo.getAccessibilityViewId(parentNodeId); 5431 final int parentVirtualDescendantId = 5432 AccessibilityNodeInfo.getVirtualDescendantId(parentNodeId); 5433 if (parentVirtualDescendantId != AccessibilityNodeInfo.UNDEFINED 5434 || parentAccessibilityViewId == providerHost.getAccessibilityViewId()) { 5435 AccessibilityNodeInfo parent = 5436 provider.createAccessibilityNodeInfo(parentVirtualDescendantId); 5437 if (parent != null) { 5438 SparseLongArray childNodeIds = parent.getChildNodeIds(); 5439 final int childCount = childNodeIds.size(); 5440 for (int i = 0; i < childCount; i++) { 5441 final long childNodeId = childNodeIds.get(i); 5442 if (childNodeId != current.getSourceNodeId() 5443 && outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5444 final int childVirtualDescendantId = 5445 AccessibilityNodeInfo.getVirtualDescendantId(childNodeId); 5446 AccessibilityNodeInfo child = provider.createAccessibilityNodeInfo( 5447 childVirtualDescendantId); 5448 if (child != null) { 5449 outInfos.add(child); 5450 } 5451 } 5452 } 5453 } 5454 } else { 5455 prefetchSiblingsOfRealNode(providerHost, outInfos); 5456 } 5457 } 5458 5459 private void prefetchDescendantsOfVirtualNode(AccessibilityNodeInfo root, 5460 AccessibilityNodeProvider provider, List<AccessibilityNodeInfo> outInfos) { 5461 SparseLongArray childNodeIds = root.getChildNodeIds(); 5462 final int initialOutInfosSize = outInfos.size(); 5463 final int childCount = childNodeIds.size(); 5464 for (int i = 0; i < childCount; i++) { 5465 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5466 final long childNodeId = childNodeIds.get(i); 5467 AccessibilityNodeInfo child = provider.createAccessibilityNodeInfo( 5468 AccessibilityNodeInfo.getVirtualDescendantId(childNodeId)); 5469 if (child != null) { 5470 outInfos.add(child); 5471 } 5472 } 5473 } 5474 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5475 final int addedChildCount = outInfos.size() - initialOutInfosSize; 5476 for (int i = 0; i < addedChildCount; i++) { 5477 AccessibilityNodeInfo child = outInfos.get(initialOutInfosSize + i); 5478 prefetchDescendantsOfVirtualNode(child, provider, outInfos); 5479 } 5480 } 5481 } 5482 } 5483} 5484