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