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