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