ViewRootImpl.java revision a08f3e866a46c990e786defa95013ee0313b0887
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 static 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 destroyHardwareRenderer(); 2419 2420 mView = null; 2421 mAttachInfo.mRootView = null; 2422 mAttachInfo.mSurface = null; 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 static 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 static 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 destroyHardwareRenderer(); 3771 mHandler.sendEmptyMessage(MSG_DIE); 3772 } 3773 } 3774 3775 void doDie() { 3776 checkThread(); 3777 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 3778 synchronized (this) { 3779 if (mAdded) { 3780 mAdded = false; 3781 dispatchDetachedFromWindow(); 3782 } 3783 3784 if (mAdded && !mFirst) { 3785 destroyHardwareRenderer(); 3786 3787 int viewVisibility = mView.getVisibility(); 3788 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 3789 if (mWindowAttributesChanged || viewVisibilityChanged) { 3790 // If layout params have been changed, first give them 3791 // to the window manager to make sure it has the correct 3792 // animation info. 3793 try { 3794 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 3795 & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) { 3796 sWindowSession.finishDrawing(mWindow); 3797 } 3798 } catch (RemoteException e) { 3799 } 3800 } 3801 3802 mSurface.release(); 3803 } 3804 } 3805 } 3806 3807 public void requestUpdateConfiguration(Configuration config) { 3808 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 3809 mHandler.sendMessage(msg); 3810 } 3811 3812 private void destroyHardwareRenderer() { 3813 AttachInfo attachInfo = mAttachInfo; 3814 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 3815 3816 if (hardwareRenderer != null) { 3817 if (mView != null) { 3818 hardwareRenderer.destroyHardwareResources(mView); 3819 } 3820 hardwareRenderer.destroy(true); 3821 hardwareRenderer.setRequested(false); 3822 3823 attachInfo.mHardwareRenderer = null; 3824 attachInfo.mHardwareAccelerated = false; 3825 } 3826 } 3827 3828 void dispatchImeFinishedEvent(int seq, boolean handled) { 3829 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT); 3830 msg.arg1 = seq; 3831 msg.arg2 = handled ? 1 : 0; 3832 msg.setAsynchronous(true); 3833 mHandler.sendMessage(msg); 3834 } 3835 3836 public void dispatchFinishInputConnection(InputConnection connection) { 3837 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 3838 mHandler.sendMessage(msg); 3839 } 3840 3841 public void dispatchResized(int w, int h, Rect coveredInsets, 3842 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 3843 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w 3844 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString() 3845 + " visibleInsets=" + visibleInsets.toShortString() 3846 + " reportDraw=" + reportDraw); 3847 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED); 3848 if (mTranslator != null) { 3849 mTranslator.translateRectInScreenToAppWindow(coveredInsets); 3850 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 3851 w *= mTranslator.applicationInvertedScale; 3852 h *= mTranslator.applicationInvertedScale; 3853 } 3854 msg.arg1 = w; 3855 msg.arg2 = h; 3856 ResizedInfo ri = new ResizedInfo(); 3857 ri.coveredInsets = new Rect(coveredInsets); 3858 ri.visibleInsets = new Rect(visibleInsets); 3859 ri.newConfig = newConfig; 3860 msg.obj = ri; 3861 mHandler.sendMessage(msg); 3862 } 3863 3864 /** 3865 * Represents a pending input event that is waiting in a queue. 3866 * 3867 * Input events are processed in serial order by the timestamp specified by 3868 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 3869 * one input event to the application at a time and waits for the application 3870 * to finish handling it before delivering the next one. 3871 * 3872 * However, because the application or IME can synthesize and inject multiple 3873 * key events at a time without going through the input dispatcher, we end up 3874 * needing a queue on the application's side. 3875 */ 3876 private static final class QueuedInputEvent { 3877 public static final int FLAG_DELIVER_POST_IME = 1; 3878 3879 public QueuedInputEvent mNext; 3880 3881 public InputEvent mEvent; 3882 public InputEventReceiver mReceiver; 3883 public int mFlags; 3884 3885 // Used for latency calculations. 3886 public long mReceiveTimeNanos; 3887 public long mDeliverTimeNanos; 3888 public long mDeliverPostImeTimeNanos; 3889 } 3890 3891 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 3892 InputEventReceiver receiver, int flags) { 3893 QueuedInputEvent q = mQueuedInputEventPool; 3894 if (q != null) { 3895 mQueuedInputEventPoolSize -= 1; 3896 mQueuedInputEventPool = q.mNext; 3897 q.mNext = null; 3898 } else { 3899 q = new QueuedInputEvent(); 3900 } 3901 3902 q.mEvent = event; 3903 q.mReceiver = receiver; 3904 q.mFlags = flags; 3905 return q; 3906 } 3907 3908 private void recycleQueuedInputEvent(QueuedInputEvent q) { 3909 q.mEvent = null; 3910 q.mReceiver = null; 3911 3912 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 3913 mQueuedInputEventPoolSize += 1; 3914 q.mNext = mQueuedInputEventPool; 3915 mQueuedInputEventPool = q; 3916 } 3917 } 3918 3919 void enqueueInputEvent(InputEvent event) { 3920 enqueueInputEvent(event, null, 0, false); 3921 } 3922 3923 void enqueueInputEvent(InputEvent event, 3924 InputEventReceiver receiver, int flags, boolean processImmediately) { 3925 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 3926 3927 if (ViewDebug.DEBUG_LATENCY) { 3928 q.mReceiveTimeNanos = System.nanoTime(); 3929 q.mDeliverTimeNanos = 0; 3930 q.mDeliverPostImeTimeNanos = 0; 3931 } 3932 3933 // Always enqueue the input event in order, regardless of its time stamp. 3934 // We do this because the application or the IME may inject key events 3935 // in response to touch events and we want to ensure that the injected keys 3936 // are processed in the order they were received and we cannot trust that 3937 // the time stamp of injected events are monotonic. 3938 QueuedInputEvent last = mFirstPendingInputEvent; 3939 if (last == null) { 3940 mFirstPendingInputEvent = q; 3941 } else { 3942 while (last.mNext != null) { 3943 last = last.mNext; 3944 } 3945 last.mNext = q; 3946 } 3947 3948 if (processImmediately) { 3949 doProcessInputEvents(); 3950 } else { 3951 scheduleProcessInputEvents(); 3952 } 3953 } 3954 3955 private void scheduleProcessInputEvents() { 3956 if (!mProcessInputEventsScheduled) { 3957 mProcessInputEventsScheduled = true; 3958 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 3959 msg.setAsynchronous(true); 3960 mHandler.sendMessage(msg); 3961 } 3962 } 3963 3964 void doProcessInputEvents() { 3965 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 3966 QueuedInputEvent q = mFirstPendingInputEvent; 3967 mFirstPendingInputEvent = q.mNext; 3968 q.mNext = null; 3969 mCurrentInputEvent = q; 3970 deliverInputEvent(q); 3971 } 3972 3973 // We are done processing all input events that we can process right now 3974 // so we can clear the pending flag immediately. 3975 if (mProcessInputEventsScheduled) { 3976 mProcessInputEventsScheduled = false; 3977 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 3978 } 3979 } 3980 3981 private void finishInputEvent(QueuedInputEvent q, boolean handled) { 3982 if (q != mCurrentInputEvent) { 3983 throw new IllegalStateException("finished input event out of order"); 3984 } 3985 3986 if (ViewDebug.DEBUG_LATENCY) { 3987 final long now = System.nanoTime(); 3988 final long eventTime = q.mEvent.getEventTimeNano(); 3989 final StringBuilder msg = new StringBuilder(); 3990 msg.append("Spent "); 3991 msg.append((now - q.mReceiveTimeNanos) * 0.000001f); 3992 msg.append("ms processing "); 3993 if (q.mEvent instanceof KeyEvent) { 3994 final KeyEvent keyEvent = (KeyEvent)q.mEvent; 3995 msg.append("key event, action="); 3996 msg.append(KeyEvent.actionToString(keyEvent.getAction())); 3997 } else { 3998 final MotionEvent motionEvent = (MotionEvent)q.mEvent; 3999 msg.append("motion event, action="); 4000 msg.append(MotionEvent.actionToString(motionEvent.getAction())); 4001 msg.append(", historySize="); 4002 msg.append(motionEvent.getHistorySize()); 4003 } 4004 msg.append(", handled="); 4005 msg.append(handled); 4006 msg.append(", received at +"); 4007 msg.append((q.mReceiveTimeNanos - eventTime) * 0.000001f); 4008 if (q.mDeliverTimeNanos != 0) { 4009 msg.append("ms, delivered at +"); 4010 msg.append((q.mDeliverTimeNanos - eventTime) * 0.000001f); 4011 } 4012 if (q.mDeliverPostImeTimeNanos != 0) { 4013 msg.append("ms, delivered post IME at +"); 4014 msg.append((q.mDeliverPostImeTimeNanos - eventTime) * 0.000001f); 4015 } 4016 msg.append("ms, finished at +"); 4017 msg.append((now - eventTime) * 0.000001f); 4018 msg.append("ms."); 4019 Log.d(ViewDebug.DEBUG_LATENCY_TAG, msg.toString()); 4020 } 4021 4022 if (q.mReceiver != null) { 4023 q.mReceiver.finishInputEvent(q.mEvent, handled); 4024 } else { 4025 q.mEvent.recycleIfNeededAfterDispatch(); 4026 } 4027 4028 recycleQueuedInputEvent(q); 4029 4030 mCurrentInputEvent = null; 4031 if (mFirstPendingInputEvent != null) { 4032 scheduleProcessInputEvents(); 4033 } 4034 } 4035 4036 void scheduleConsumeBatchedInput() { 4037 if (!mConsumeBatchedInputScheduled) { 4038 mConsumeBatchedInputScheduled = true; 4039 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 4040 mConsumedBatchedInputRunnable, null); 4041 } 4042 } 4043 4044 void unscheduleConsumeBatchedInput() { 4045 if (mConsumeBatchedInputScheduled) { 4046 mConsumeBatchedInputScheduled = false; 4047 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4048 mConsumedBatchedInputRunnable, null); 4049 } 4050 } 4051 4052 void doConsumeBatchedInput(boolean callback) { 4053 if (mConsumeBatchedInputScheduled) { 4054 mConsumeBatchedInputScheduled = false; 4055 if (!callback) { 4056 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4057 mConsumedBatchedInputRunnable, null); 4058 } 4059 if (mInputEventReceiver != null) { 4060 mInputEventReceiver.consumeBatchedInputEvents(); 4061 } 4062 } 4063 } 4064 4065 final class TraversalRunnable implements Runnable { 4066 @Override 4067 public void run() { 4068 doTraversal(); 4069 } 4070 } 4071 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 4072 4073 final class WindowInputEventReceiver extends InputEventReceiver { 4074 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 4075 super(inputChannel, looper); 4076 } 4077 4078 @Override 4079 public void onInputEvent(InputEvent event) { 4080 enqueueInputEvent(event, this, 0, true); 4081 } 4082 4083 @Override 4084 public void onBatchedInputEventPending() { 4085 scheduleConsumeBatchedInput(); 4086 } 4087 4088 @Override 4089 public void dispose() { 4090 unscheduleConsumeBatchedInput(); 4091 super.dispose(); 4092 } 4093 } 4094 WindowInputEventReceiver mInputEventReceiver; 4095 4096 final class ConsumeBatchedInputRunnable implements Runnable { 4097 @Override 4098 public void run() { 4099 doConsumeBatchedInput(true); 4100 doProcessInputEvents(); 4101 } 4102 } 4103 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 4104 new ConsumeBatchedInputRunnable(); 4105 boolean mConsumeBatchedInputScheduled; 4106 4107 final class InvalidateOnAnimationRunnable implements Runnable { 4108 private boolean mPosted; 4109 private ArrayList<View> mViews = new ArrayList<View>(); 4110 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 4111 new ArrayList<AttachInfo.InvalidateInfo>(); 4112 private View[] mTempViews; 4113 private AttachInfo.InvalidateInfo[] mTempViewRects; 4114 4115 public void addView(View view) { 4116 synchronized (this) { 4117 mViews.add(view); 4118 postIfNeededLocked(); 4119 } 4120 } 4121 4122 public void addViewRect(AttachInfo.InvalidateInfo info) { 4123 synchronized (this) { 4124 mViewRects.add(info); 4125 postIfNeededLocked(); 4126 } 4127 } 4128 4129 public void removeView(View view) { 4130 synchronized (this) { 4131 mViews.remove(view); 4132 4133 for (int i = mViewRects.size(); i-- > 0; ) { 4134 AttachInfo.InvalidateInfo info = mViewRects.get(i); 4135 if (info.target == view) { 4136 mViewRects.remove(i); 4137 info.release(); 4138 } 4139 } 4140 4141 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 4142 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 4143 mPosted = false; 4144 } 4145 } 4146 } 4147 4148 @Override 4149 public void run() { 4150 final int viewCount; 4151 final int viewRectCount; 4152 synchronized (this) { 4153 mPosted = false; 4154 4155 viewCount = mViews.size(); 4156 if (viewCount != 0) { 4157 mTempViews = mViews.toArray(mTempViews != null 4158 ? mTempViews : new View[viewCount]); 4159 mViews.clear(); 4160 } 4161 4162 viewRectCount = mViewRects.size(); 4163 if (viewRectCount != 0) { 4164 mTempViewRects = mViewRects.toArray(mTempViewRects != null 4165 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 4166 mViewRects.clear(); 4167 } 4168 } 4169 4170 for (int i = 0; i < viewCount; i++) { 4171 mTempViews[i].invalidate(); 4172 } 4173 4174 for (int i = 0; i < viewRectCount; i++) { 4175 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 4176 info.target.invalidate(info.left, info.top, info.right, info.bottom); 4177 info.release(); 4178 } 4179 } 4180 4181 private void postIfNeededLocked() { 4182 if (!mPosted) { 4183 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 4184 mPosted = true; 4185 } 4186 } 4187 } 4188 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 4189 new InvalidateOnAnimationRunnable(); 4190 4191 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 4192 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 4193 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4194 } 4195 4196 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 4197 long delayMilliseconds) { 4198 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 4199 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4200 } 4201 4202 public void dispatchInvalidateOnAnimation(View view) { 4203 mInvalidateOnAnimationRunnable.addView(view); 4204 } 4205 4206 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 4207 mInvalidateOnAnimationRunnable.addViewRect(info); 4208 } 4209 4210 public void invalidateDisplayList(DisplayList displayList) { 4211 mDisplayLists.add(displayList); 4212 4213 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4214 Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST); 4215 mHandler.sendMessage(msg); 4216 } 4217 4218 public void cancelInvalidate(View view) { 4219 mHandler.removeMessages(MSG_INVALIDATE, view); 4220 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 4221 // them to the pool 4222 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 4223 mInvalidateOnAnimationRunnable.removeView(view); 4224 } 4225 4226 public void dispatchKey(KeyEvent event) { 4227 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 4228 msg.setAsynchronous(true); 4229 mHandler.sendMessage(msg); 4230 } 4231 4232 public void dispatchKeyFromIme(KeyEvent event) { 4233 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 4234 msg.setAsynchronous(true); 4235 mHandler.sendMessage(msg); 4236 } 4237 4238 public void dispatchAppVisibility(boolean visible) { 4239 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 4240 msg.arg1 = visible ? 1 : 0; 4241 mHandler.sendMessage(msg); 4242 } 4243 4244 public void dispatchScreenStateChange(boolean on) { 4245 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 4246 msg.arg1 = on ? 1 : 0; 4247 mHandler.sendMessage(msg); 4248 } 4249 4250 public void dispatchGetNewSurface() { 4251 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 4252 mHandler.sendMessage(msg); 4253 } 4254 4255 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4256 Message msg = Message.obtain(); 4257 msg.what = MSG_WINDOW_FOCUS_CHANGED; 4258 msg.arg1 = hasFocus ? 1 : 0; 4259 msg.arg2 = inTouchMode ? 1 : 0; 4260 mHandler.sendMessage(msg); 4261 } 4262 4263 public void dispatchCloseSystemDialogs(String reason) { 4264 Message msg = Message.obtain(); 4265 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 4266 msg.obj = reason; 4267 mHandler.sendMessage(msg); 4268 } 4269 4270 public void dispatchDragEvent(DragEvent event) { 4271 final int what; 4272 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 4273 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 4274 mHandler.removeMessages(what); 4275 } else { 4276 what = MSG_DISPATCH_DRAG_EVENT; 4277 } 4278 Message msg = mHandler.obtainMessage(what, event); 4279 mHandler.sendMessage(msg); 4280 } 4281 4282 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4283 int localValue, int localChanges) { 4284 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 4285 args.seq = seq; 4286 args.globalVisibility = globalVisibility; 4287 args.localValue = localValue; 4288 args.localChanges = localChanges; 4289 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 4290 } 4291 4292 public void dispatchCheckFocus() { 4293 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 4294 // This will result in a call to checkFocus() below. 4295 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 4296 } 4297 } 4298 4299 /** 4300 * Post a callback to send a 4301 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4302 * This event is send at most once every 4303 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 4304 */ 4305 private void postSendWindowContentChangedCallback() { 4306 if (mSendWindowContentChangedAccessibilityEvent == null) { 4307 mSendWindowContentChangedAccessibilityEvent = 4308 new SendWindowContentChangedAccessibilityEvent(); 4309 } 4310 if (!mSendWindowContentChangedAccessibilityEvent.mIsPending) { 4311 mSendWindowContentChangedAccessibilityEvent.mIsPending = true; 4312 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 4313 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 4314 } 4315 } 4316 4317 /** 4318 * Remove a posted callback to send a 4319 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4320 */ 4321 private void removeSendWindowContentChangedCallback() { 4322 if (mSendWindowContentChangedAccessibilityEvent != null) { 4323 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 4324 } 4325 } 4326 4327 public boolean showContextMenuForChild(View originalView) { 4328 return false; 4329 } 4330 4331 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 4332 return null; 4333 } 4334 4335 public void createContextMenu(ContextMenu menu) { 4336 } 4337 4338 public void childDrawableStateChanged(View child) { 4339 } 4340 4341 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 4342 if (mView == null) { 4343 return false; 4344 } 4345 mAccessibilityManager.sendAccessibilityEvent(event); 4346 return true; 4347 } 4348 4349 void checkThread() { 4350 if (mThread != Thread.currentThread()) { 4351 throw new CalledFromWrongThreadException( 4352 "Only the original thread that created a view hierarchy can touch its views."); 4353 } 4354 } 4355 4356 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4357 // ViewAncestor never intercepts touch event, so this can be a no-op 4358 } 4359 4360 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 4361 boolean immediate) { 4362 return scrollToRectOrFocus(rectangle, immediate); 4363 } 4364 4365 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 4366 // Do nothing. 4367 } 4368 4369 class TakenSurfaceHolder extends BaseSurfaceHolder { 4370 @Override 4371 public boolean onAllowLockCanvas() { 4372 return mDrawingAllowed; 4373 } 4374 4375 @Override 4376 public void onRelayoutContainer() { 4377 // Not currently interesting -- from changing between fixed and layout size. 4378 } 4379 4380 public void setFormat(int format) { 4381 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4382 } 4383 4384 public void setType(int type) { 4385 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4386 } 4387 4388 @Override 4389 public void onUpdateSurface() { 4390 // We take care of format and type changes on our own. 4391 throw new IllegalStateException("Shouldn't be here"); 4392 } 4393 4394 public boolean isCreating() { 4395 return mIsCreating; 4396 } 4397 4398 @Override 4399 public void setFixedSize(int width, int height) { 4400 throw new UnsupportedOperationException( 4401 "Currently only support sizing from layout"); 4402 } 4403 4404 public void setKeepScreenOn(boolean screenOn) { 4405 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4406 } 4407 } 4408 4409 static class InputMethodCallback extends IInputMethodCallback.Stub { 4410 private WeakReference<ViewRootImpl> mViewAncestor; 4411 4412 public InputMethodCallback(ViewRootImpl viewAncestor) { 4413 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4414 } 4415 4416 public void finishedEvent(int seq, boolean handled) { 4417 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4418 if (viewAncestor != null) { 4419 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4420 } 4421 } 4422 4423 public void sessionCreated(IInputMethodSession session) { 4424 // Stub -- not for use in the client. 4425 } 4426 } 4427 4428 static class W extends IWindow.Stub { 4429 private final WeakReference<ViewRootImpl> mViewAncestor; 4430 4431 W(ViewRootImpl viewAncestor) { 4432 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4433 } 4434 4435 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets, 4436 boolean reportDraw, Configuration newConfig) { 4437 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4438 if (viewAncestor != null) { 4439 viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, 4440 newConfig); 4441 } 4442 } 4443 4444 public void dispatchAppVisibility(boolean visible) { 4445 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4446 if (viewAncestor != null) { 4447 viewAncestor.dispatchAppVisibility(visible); 4448 } 4449 } 4450 4451 public void dispatchScreenState(boolean on) { 4452 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4453 if (viewAncestor != null) { 4454 viewAncestor.dispatchScreenStateChange(on); 4455 } 4456 } 4457 4458 public void dispatchGetNewSurface() { 4459 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4460 if (viewAncestor != null) { 4461 viewAncestor.dispatchGetNewSurface(); 4462 } 4463 } 4464 4465 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4466 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4467 if (viewAncestor != null) { 4468 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4469 } 4470 } 4471 4472 private static int checkCallingPermission(String permission) { 4473 try { 4474 return ActivityManagerNative.getDefault().checkPermission( 4475 permission, Binder.getCallingPid(), Binder.getCallingUid()); 4476 } catch (RemoteException e) { 4477 return PackageManager.PERMISSION_DENIED; 4478 } 4479 } 4480 4481 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 4482 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4483 if (viewAncestor != null) { 4484 final View view = viewAncestor.mView; 4485 if (view != null) { 4486 if (checkCallingPermission(Manifest.permission.DUMP) != 4487 PackageManager.PERMISSION_GRANTED) { 4488 throw new SecurityException("Insufficient permissions to invoke" 4489 + " executeCommand() from pid=" + Binder.getCallingPid() 4490 + ", uid=" + Binder.getCallingUid()); 4491 } 4492 4493 OutputStream clientStream = null; 4494 try { 4495 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 4496 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 4497 } catch (IOException e) { 4498 e.printStackTrace(); 4499 } finally { 4500 if (clientStream != null) { 4501 try { 4502 clientStream.close(); 4503 } catch (IOException e) { 4504 e.printStackTrace(); 4505 } 4506 } 4507 } 4508 } 4509 } 4510 } 4511 4512 public void closeSystemDialogs(String reason) { 4513 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4514 if (viewAncestor != null) { 4515 viewAncestor.dispatchCloseSystemDialogs(reason); 4516 } 4517 } 4518 4519 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 4520 boolean sync) { 4521 if (sync) { 4522 try { 4523 sWindowSession.wallpaperOffsetsComplete(asBinder()); 4524 } catch (RemoteException e) { 4525 } 4526 } 4527 } 4528 4529 public void dispatchWallpaperCommand(String action, int x, int y, 4530 int z, Bundle extras, boolean sync) { 4531 if (sync) { 4532 try { 4533 sWindowSession.wallpaperCommandComplete(asBinder(), null); 4534 } catch (RemoteException e) { 4535 } 4536 } 4537 } 4538 4539 /* Drag/drop */ 4540 public void dispatchDragEvent(DragEvent event) { 4541 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4542 if (viewAncestor != null) { 4543 viewAncestor.dispatchDragEvent(event); 4544 } 4545 } 4546 4547 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4548 int localValue, int localChanges) { 4549 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4550 if (viewAncestor != null) { 4551 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 4552 localValue, localChanges); 4553 } 4554 } 4555 } 4556 4557 /** 4558 * Maintains state information for a single trackball axis, generating 4559 * discrete (DPAD) movements based on raw trackball motion. 4560 */ 4561 static final class TrackballAxis { 4562 /** 4563 * The maximum amount of acceleration we will apply. 4564 */ 4565 static final float MAX_ACCELERATION = 20; 4566 4567 /** 4568 * The maximum amount of time (in milliseconds) between events in order 4569 * for us to consider the user to be doing fast trackball movements, 4570 * and thus apply an acceleration. 4571 */ 4572 static final long FAST_MOVE_TIME = 150; 4573 4574 /** 4575 * Scaling factor to the time (in milliseconds) between events to how 4576 * much to multiple/divide the current acceleration. When movement 4577 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4578 * FAST_MOVE_TIME it divides it. 4579 */ 4580 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4581 4582 float position; 4583 float absPosition; 4584 float acceleration = 1; 4585 long lastMoveTime = 0; 4586 int step; 4587 int dir; 4588 int nonAccelMovement; 4589 4590 void reset(int _step) { 4591 position = 0; 4592 acceleration = 1; 4593 lastMoveTime = 0; 4594 step = _step; 4595 dir = 0; 4596 } 4597 4598 /** 4599 * Add trackball movement into the state. If the direction of movement 4600 * has been reversed, the state is reset before adding the 4601 * movement (so that you don't have to compensate for any previously 4602 * collected movement before see the result of the movement in the 4603 * new direction). 4604 * 4605 * @return Returns the absolute value of the amount of movement 4606 * collected so far. 4607 */ 4608 float collect(float off, long time, String axis) { 4609 long normTime; 4610 if (off > 0) { 4611 normTime = (long)(off * FAST_MOVE_TIME); 4612 if (dir < 0) { 4613 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4614 position = 0; 4615 step = 0; 4616 acceleration = 1; 4617 lastMoveTime = 0; 4618 } 4619 dir = 1; 4620 } else if (off < 0) { 4621 normTime = (long)((-off) * FAST_MOVE_TIME); 4622 if (dir > 0) { 4623 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4624 position = 0; 4625 step = 0; 4626 acceleration = 1; 4627 lastMoveTime = 0; 4628 } 4629 dir = -1; 4630 } else { 4631 normTime = 0; 4632 } 4633 4634 // The number of milliseconds between each movement that is 4635 // considered "normal" and will not result in any acceleration 4636 // or deceleration, scaled by the offset we have here. 4637 if (normTime > 0) { 4638 long delta = time - lastMoveTime; 4639 lastMoveTime = time; 4640 float acc = acceleration; 4641 if (delta < normTime) { 4642 // The user is scrolling rapidly, so increase acceleration. 4643 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4644 if (scale > 1) acc *= scale; 4645 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4646 + off + " normTime=" + normTime + " delta=" + delta 4647 + " scale=" + scale + " acc=" + acc); 4648 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4649 } else { 4650 // The user is scrolling slowly, so decrease acceleration. 4651 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4652 if (scale > 1) acc /= scale; 4653 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4654 + off + " normTime=" + normTime + " delta=" + delta 4655 + " scale=" + scale + " acc=" + acc); 4656 acceleration = acc > 1 ? acc : 1; 4657 } 4658 } 4659 position += off; 4660 return (absPosition = Math.abs(position)); 4661 } 4662 4663 /** 4664 * Generate the number of discrete movement events appropriate for 4665 * the currently collected trackball movement. 4666 * 4667 * @param precision The minimum movement required to generate the 4668 * first discrete movement. 4669 * 4670 * @return Returns the number of discrete movements, either positive 4671 * or negative, or 0 if there is not enough trackball movement yet 4672 * for a discrete movement. 4673 */ 4674 int generate(float precision) { 4675 int movement = 0; 4676 nonAccelMovement = 0; 4677 do { 4678 final int dir = position >= 0 ? 1 : -1; 4679 switch (step) { 4680 // If we are going to execute the first step, then we want 4681 // to do this as soon as possible instead of waiting for 4682 // a full movement, in order to make things look responsive. 4683 case 0: 4684 if (absPosition < precision) { 4685 return movement; 4686 } 4687 movement += dir; 4688 nonAccelMovement += dir; 4689 step = 1; 4690 break; 4691 // If we have generated the first movement, then we need 4692 // to wait for the second complete trackball motion before 4693 // generating the second discrete movement. 4694 case 1: 4695 if (absPosition < 2) { 4696 return movement; 4697 } 4698 movement += dir; 4699 nonAccelMovement += dir; 4700 position += dir > 0 ? -2 : 2; 4701 absPosition = Math.abs(position); 4702 step = 2; 4703 break; 4704 // After the first two, we generate discrete movements 4705 // consistently with the trackball, applying an acceleration 4706 // if the trackball is moving quickly. This is a simple 4707 // acceleration on top of what we already compute based 4708 // on how quickly the wheel is being turned, to apply 4709 // a longer increasing acceleration to continuous movement 4710 // in one direction. 4711 default: 4712 if (absPosition < 1) { 4713 return movement; 4714 } 4715 movement += dir; 4716 position += dir >= 0 ? -1 : 1; 4717 absPosition = Math.abs(position); 4718 float acc = acceleration; 4719 acc *= 1.1f; 4720 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4721 break; 4722 } 4723 } while (true); 4724 } 4725 } 4726 4727 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 4728 public CalledFromWrongThreadException(String msg) { 4729 super(msg); 4730 } 4731 } 4732 4733 private SurfaceHolder mHolder = new SurfaceHolder() { 4734 // we only need a SurfaceHolder for opengl. it would be nice 4735 // to implement everything else though, especially the callback 4736 // support (opengl doesn't make use of it right now, but eventually 4737 // will). 4738 public Surface getSurface() { 4739 return mSurface; 4740 } 4741 4742 public boolean isCreating() { 4743 return false; 4744 } 4745 4746 public void addCallback(Callback callback) { 4747 } 4748 4749 public void removeCallback(Callback callback) { 4750 } 4751 4752 public void setFixedSize(int width, int height) { 4753 } 4754 4755 public void setSizeFromLayout() { 4756 } 4757 4758 public void setFormat(int format) { 4759 } 4760 4761 public void setType(int type) { 4762 } 4763 4764 public void setKeepScreenOn(boolean screenOn) { 4765 } 4766 4767 public Canvas lockCanvas() { 4768 return null; 4769 } 4770 4771 public Canvas lockCanvas(Rect dirty) { 4772 return null; 4773 } 4774 4775 public void unlockCanvasAndPost(Canvas canvas) { 4776 } 4777 public Rect getSurfaceFrame() { 4778 return null; 4779 } 4780 }; 4781 4782 static RunQueue getRunQueue() { 4783 RunQueue rq = sRunQueues.get(); 4784 if (rq != null) { 4785 return rq; 4786 } 4787 rq = new RunQueue(); 4788 sRunQueues.set(rq); 4789 return rq; 4790 } 4791 4792 /** 4793 * The run queue is used to enqueue pending work from Views when no Handler is 4794 * attached. The work is executed during the next call to performTraversals on 4795 * the thread. 4796 * @hide 4797 */ 4798 static final class RunQueue { 4799 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 4800 4801 void post(Runnable action) { 4802 postDelayed(action, 0); 4803 } 4804 4805 void postDelayed(Runnable action, long delayMillis) { 4806 HandlerAction handlerAction = new HandlerAction(); 4807 handlerAction.action = action; 4808 handlerAction.delay = delayMillis; 4809 4810 synchronized (mActions) { 4811 mActions.add(handlerAction); 4812 } 4813 } 4814 4815 void removeCallbacks(Runnable action) { 4816 final HandlerAction handlerAction = new HandlerAction(); 4817 handlerAction.action = action; 4818 4819 synchronized (mActions) { 4820 final ArrayList<HandlerAction> actions = mActions; 4821 4822 while (actions.remove(handlerAction)) { 4823 // Keep going 4824 } 4825 } 4826 } 4827 4828 void executeActions(Handler handler) { 4829 synchronized (mActions) { 4830 final ArrayList<HandlerAction> actions = mActions; 4831 final int count = actions.size(); 4832 4833 for (int i = 0; i < count; i++) { 4834 final HandlerAction handlerAction = actions.get(i); 4835 handler.postDelayed(handlerAction.action, handlerAction.delay); 4836 } 4837 4838 actions.clear(); 4839 } 4840 } 4841 4842 private static class HandlerAction { 4843 Runnable action; 4844 long delay; 4845 4846 @Override 4847 public boolean equals(Object o) { 4848 if (this == o) return true; 4849 if (o == null || getClass() != o.getClass()) return false; 4850 4851 HandlerAction that = (HandlerAction) o; 4852 return !(action != null ? !action.equals(that.action) : that.action != null); 4853 4854 } 4855 4856 @Override 4857 public int hashCode() { 4858 int result = action != null ? action.hashCode() : 0; 4859 result = 31 * result + (int) (delay ^ (delay >>> 32)); 4860 return result; 4861 } 4862 } 4863 } 4864 4865 /** 4866 * Class for managing the accessibility interaction connection 4867 * based on the global accessibility state. 4868 */ 4869 final class AccessibilityInteractionConnectionManager 4870 implements AccessibilityStateChangeListener { 4871 public void onAccessibilityStateChanged(boolean enabled) { 4872 if (enabled) { 4873 ensureConnection(); 4874 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 4875 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 4876 View focusedView = mView.findFocus(); 4877 if (focusedView != null && focusedView != mView) { 4878 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4879 } 4880 } 4881 } else { 4882 ensureNoConnection(); 4883 } 4884 } 4885 4886 public void ensureConnection() { 4887 if (mAttachInfo != null) { 4888 final boolean registered = 4889 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 4890 if (!registered) { 4891 mAttachInfo.mAccessibilityWindowId = 4892 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 4893 new AccessibilityInteractionConnection(ViewRootImpl.this)); 4894 } 4895 } 4896 } 4897 4898 public void ensureNoConnection() { 4899 final boolean registered = 4900 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 4901 if (registered) { 4902 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 4903 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 4904 } 4905 } 4906 } 4907 4908 /** 4909 * This class is an interface this ViewAncestor provides to the 4910 * AccessibilityManagerService to the latter can interact with 4911 * the view hierarchy in this ViewAncestor. 4912 */ 4913 static final class AccessibilityInteractionConnection 4914 extends IAccessibilityInteractionConnection.Stub { 4915 private final WeakReference<ViewRootImpl> mViewRootImpl; 4916 4917 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 4918 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 4919 } 4920 4921 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 4922 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4923 int prefetchFlags, int interrogatingPid, long interrogatingTid) { 4924 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4925 if (viewRootImpl != null && viewRootImpl.mView != null) { 4926 viewRootImpl.getAccessibilityInteractionController() 4927 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 4928 interactionId, callback, prefetchFlags, interrogatingPid, interrogatingTid); 4929 } else { 4930 // We cannot make the call and notify the caller so it does not wait. 4931 try { 4932 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 4933 } catch (RemoteException re) { 4934 /* best effort - ignore */ 4935 } 4936 } 4937 } 4938 4939 public void performAccessibilityAction(long accessibilityNodeId, int action, 4940 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4941 int interogatingPid, long interrogatingTid) { 4942 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4943 if (viewRootImpl != null && viewRootImpl.mView != null) { 4944 viewRootImpl.getAccessibilityInteractionController() 4945 .performAccessibilityActionClientThread(accessibilityNodeId, action, 4946 interactionId, callback, interogatingPid, interrogatingTid); 4947 } else { 4948 // We cannot make the call and notify the caller so it does not 4949 try { 4950 callback.setPerformAccessibilityActionResult(false, interactionId); 4951 } catch (RemoteException re) { 4952 /* best effort - ignore */ 4953 } 4954 } 4955 } 4956 4957 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId, 4958 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4959 int interrogatingPid, long interrogatingTid) { 4960 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4961 if (viewRootImpl != null && viewRootImpl.mView != null) { 4962 viewRootImpl.getAccessibilityInteractionController() 4963 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId, 4964 interactionId, callback, interrogatingPid, interrogatingTid); 4965 } else { 4966 // We cannot make the call and notify the caller so it does not 4967 try { 4968 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 4969 } catch (RemoteException re) { 4970 /* best effort - ignore */ 4971 } 4972 } 4973 } 4974 4975 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 4976 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4977 int interrogatingPid, long interrogatingTid) { 4978 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4979 if (viewRootImpl != null && viewRootImpl.mView != null) { 4980 viewRootImpl.getAccessibilityInteractionController() 4981 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 4982 interactionId, callback, interrogatingPid, interrogatingTid); 4983 } else { 4984 // We cannot make the call and notify the caller so it does not 4985 try { 4986 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 4987 } catch (RemoteException re) { 4988 /* best effort - ignore */ 4989 } 4990 } 4991 } 4992 } 4993 4994 /** 4995 * Class for managing accessibility interactions initiated from the system 4996 * and targeting the view hierarchy. A *ClientThread method is to be 4997 * called from the interaction connection this ViewAncestor gives the 4998 * system to talk to it and a corresponding *UiThread method that is executed 4999 * on the UI thread. 5000 */ 5001 final class AccessibilityInteractionController { 5002 private static final int POOL_SIZE = 5; 5003 5004 private ArrayList<AccessibilityNodeInfo> mTempAccessibilityNodeInfoList = 5005 new ArrayList<AccessibilityNodeInfo>(); 5006 5007 // Reusable poolable arguments for interacting with the view hierarchy 5008 // to fit more arguments than Message and to avoid sharing objects between 5009 // two messages since several threads can send messages concurrently. 5010 private final Pool<SomeArgs> mPool = Pools.synchronizedPool(Pools.finitePool( 5011 new PoolableManager<SomeArgs>() { 5012 public SomeArgs newInstance() { 5013 return new SomeArgs(); 5014 } 5015 5016 public void onAcquired(SomeArgs info) { 5017 /* do nothing */ 5018 } 5019 5020 public void onReleased(SomeArgs info) { 5021 info.clear(); 5022 } 5023 }, POOL_SIZE) 5024 ); 5025 5026 public class SomeArgs implements Poolable<SomeArgs> { 5027 private SomeArgs mNext; 5028 private boolean mIsPooled; 5029 5030 public Object arg1; 5031 public Object arg2; 5032 public int argi1; 5033 public int argi2; 5034 public int argi3; 5035 5036 public SomeArgs getNextPoolable() { 5037 return mNext; 5038 } 5039 5040 public boolean isPooled() { 5041 return mIsPooled; 5042 } 5043 5044 public void setNextPoolable(SomeArgs args) { 5045 mNext = args; 5046 } 5047 5048 public void setPooled(boolean isPooled) { 5049 mIsPooled = isPooled; 5050 } 5051 5052 private void clear() { 5053 arg1 = null; 5054 arg2 = null; 5055 argi1 = 0; 5056 argi2 = 0; 5057 argi3 = 0; 5058 } 5059 } 5060 5061 public void findAccessibilityNodeInfoByAccessibilityIdClientThread( 5062 long accessibilityNodeId, int interactionId, 5063 IAccessibilityInteractionConnectionCallback callback, int prefetchFlags, 5064 int interrogatingPid, long interrogatingTid) { 5065 Message message = mHandler.obtainMessage(); 5066 message.what = MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID; 5067 message.arg1 = prefetchFlags; 5068 SomeArgs args = mPool.acquire(); 5069 args.argi1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 5070 args.argi2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 5071 args.argi3 = interactionId; 5072 args.arg1 = callback; 5073 message.obj = args; 5074 // If the interrogation is performed by the same thread as the main UI 5075 // thread in this process, set the message as a static reference so 5076 // after this call completes the same thread but in the interrogating 5077 // client can handle the message to generate the result. 5078 if (interrogatingPid == Process.myPid() 5079 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 5080 AccessibilityInteractionClient.getInstanceForThread( 5081 interrogatingTid).setSameThreadMessage(message); 5082 } else { 5083 mHandler.sendMessage(message); 5084 } 5085 } 5086 5087 public void findAccessibilityNodeInfoByAccessibilityIdUiThread(Message message) { 5088 final int prefetchFlags = message.arg1; 5089 SomeArgs args = (SomeArgs) message.obj; 5090 final int accessibilityViewId = args.argi1; 5091 final int virtualDescendantId = args.argi2; 5092 final int interactionId = args.argi3; 5093 final IAccessibilityInteractionConnectionCallback callback = 5094 (IAccessibilityInteractionConnectionCallback) args.arg1; 5095 mPool.release(args); 5096 List<AccessibilityNodeInfo> infos = mTempAccessibilityNodeInfoList; 5097 infos.clear(); 5098 try { 5099 View target = null; 5100 if (accessibilityViewId == AccessibilityNodeInfo.UNDEFINED) { 5101 target = ViewRootImpl.this.mView; 5102 } else { 5103 target = findViewByAccessibilityId(accessibilityViewId); 5104 } 5105 if (target != null && target.getVisibility() == View.VISIBLE) { 5106 getAccessibilityNodePrefetcher().prefetchAccessibilityNodeInfos(target, 5107 virtualDescendantId, prefetchFlags, infos); 5108 } 5109 } finally { 5110 try { 5111 callback.setFindAccessibilityNodeInfosResult(infos, interactionId); 5112 infos.clear(); 5113 } catch (RemoteException re) { 5114 /* ignore - the other side will time out */ 5115 } 5116 } 5117 } 5118 5119 public void findAccessibilityNodeInfoByViewIdClientThread(long accessibilityNodeId, 5120 int viewId, int interactionId, IAccessibilityInteractionConnectionCallback callback, 5121 int interrogatingPid, long interrogatingTid) { 5122 Message message = mHandler.obtainMessage(); 5123 message.what = MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID; 5124 message.arg1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 5125 SomeArgs args = mPool.acquire(); 5126 args.argi1 = viewId; 5127 args.argi2 = interactionId; 5128 args.arg1 = callback; 5129 message.obj = args; 5130 // If the interrogation is performed by the same thread as the main UI 5131 // thread in this process, set the message as a static reference so 5132 // after this call completes the same thread but in the interrogating 5133 // client can handle the message to generate the result. 5134 if (interrogatingPid == Process.myPid() 5135 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 5136 AccessibilityInteractionClient.getInstanceForThread( 5137 interrogatingTid).setSameThreadMessage(message); 5138 } else { 5139 mHandler.sendMessage(message); 5140 } 5141 } 5142 5143 public void findAccessibilityNodeInfoByViewIdUiThread(Message message) { 5144 final int accessibilityViewId = message.arg1; 5145 SomeArgs args = (SomeArgs) message.obj; 5146 final int viewId = args.argi1; 5147 final int interactionId = args.argi2; 5148 final IAccessibilityInteractionConnectionCallback callback = 5149 (IAccessibilityInteractionConnectionCallback) args.arg1; 5150 mPool.release(args); 5151 AccessibilityNodeInfo info = null; 5152 try { 5153 View root = null; 5154 if (accessibilityViewId != AccessibilityNodeInfo.UNDEFINED) { 5155 root = findViewByAccessibilityId(accessibilityViewId); 5156 } else { 5157 root = ViewRootImpl.this.mView; 5158 } 5159 if (root != null) { 5160 View target = root.findViewById(viewId); 5161 if (target != null && target.getVisibility() == View.VISIBLE) { 5162 info = target.createAccessibilityNodeInfo(); 5163 } 5164 } 5165 } finally { 5166 try { 5167 callback.setFindAccessibilityNodeInfoResult(info, interactionId); 5168 } catch (RemoteException re) { 5169 /* ignore - the other side will time out */ 5170 } 5171 } 5172 } 5173 5174 public void findAccessibilityNodeInfosByTextClientThread(long accessibilityNodeId, 5175 String text, int interactionId, 5176 IAccessibilityInteractionConnectionCallback callback, int interrogatingPid, 5177 long interrogatingTid) { 5178 Message message = mHandler.obtainMessage(); 5179 message.what = MSG_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT; 5180 SomeArgs args = mPool.acquire(); 5181 args.arg1 = text; 5182 args.argi1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 5183 args.argi2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 5184 args.argi3 = interactionId; 5185 args.arg2 = callback; 5186 message.obj = args; 5187 // If the interrogation is performed by the same thread as the main UI 5188 // thread in this process, set the message as a static reference so 5189 // after this call completes the same thread but in the interrogating 5190 // client can handle the message to generate the result. 5191 if (interrogatingPid == Process.myPid() 5192 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 5193 AccessibilityInteractionClient.getInstanceForThread( 5194 interrogatingTid).setSameThreadMessage(message); 5195 } else { 5196 mHandler.sendMessage(message); 5197 } 5198 } 5199 5200 public void findAccessibilityNodeInfosByTextUiThread(Message message) { 5201 SomeArgs args = (SomeArgs) message.obj; 5202 final String text = (String) args.arg1; 5203 final int accessibilityViewId = args.argi1; 5204 final int virtualDescendantId = args.argi2; 5205 final int interactionId = args.argi3; 5206 final IAccessibilityInteractionConnectionCallback callback = 5207 (IAccessibilityInteractionConnectionCallback) args.arg2; 5208 mPool.release(args); 5209 List<AccessibilityNodeInfo> infos = null; 5210 try { 5211 View target; 5212 if (accessibilityViewId != AccessibilityNodeInfo.UNDEFINED) { 5213 target = findViewByAccessibilityId(accessibilityViewId); 5214 } else { 5215 target = ViewRootImpl.this.mView; 5216 } 5217 if (target != null && target.getVisibility() == View.VISIBLE) { 5218 AccessibilityNodeProvider provider = target.getAccessibilityNodeProvider(); 5219 if (provider != null) { 5220 infos = provider.findAccessibilityNodeInfosByText(text, 5221 virtualDescendantId); 5222 } else if (virtualDescendantId == AccessibilityNodeInfo.UNDEFINED) { 5223 ArrayList<View> foundViews = mAttachInfo.mFocusablesTempList; 5224 foundViews.clear(); 5225 target.findViewsWithText(foundViews, text, View.FIND_VIEWS_WITH_TEXT 5226 | View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION 5227 | View.FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS); 5228 if (!foundViews.isEmpty()) { 5229 infos = mTempAccessibilityNodeInfoList; 5230 infos.clear(); 5231 final int viewCount = foundViews.size(); 5232 for (int i = 0; i < viewCount; i++) { 5233 View foundView = foundViews.get(i); 5234 if (foundView.getVisibility() == View.VISIBLE) { 5235 provider = foundView.getAccessibilityNodeProvider(); 5236 if (provider != null) { 5237 List<AccessibilityNodeInfo> infosFromProvider = 5238 provider.findAccessibilityNodeInfosByText(text, 5239 virtualDescendantId); 5240 if (infosFromProvider != null) { 5241 infos.addAll(infosFromProvider); 5242 } 5243 } else { 5244 infos.add(foundView.createAccessibilityNodeInfo()); 5245 } 5246 } 5247 } 5248 } 5249 } 5250 } 5251 } finally { 5252 try { 5253 callback.setFindAccessibilityNodeInfosResult(infos, interactionId); 5254 } catch (RemoteException re) { 5255 /* ignore - the other side will time out */ 5256 } 5257 } 5258 } 5259 5260 public void performAccessibilityActionClientThread(long accessibilityNodeId, int action, 5261 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5262 int interogatingPid, long interrogatingTid) { 5263 Message message = mHandler.obtainMessage(); 5264 message.what = MSG_PERFORM_ACCESSIBILITY_ACTION; 5265 message.arg1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 5266 message.arg2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 5267 SomeArgs args = mPool.acquire(); 5268 args.argi1 = action; 5269 args.argi2 = interactionId; 5270 args.arg1 = callback; 5271 message.obj = args; 5272 // If the interrogation is performed by the same thread as the main UI 5273 // thread in this process, set the message as a static reference so 5274 // after this call completes the same thread but in the interrogating 5275 // client can handle the message to generate the result. 5276 if (interogatingPid == Process.myPid() 5277 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 5278 AccessibilityInteractionClient.getInstanceForThread( 5279 interrogatingTid).setSameThreadMessage(message); 5280 } else { 5281 mHandler.sendMessage(message); 5282 } 5283 } 5284 5285 public void perfromAccessibilityActionUiThread(Message message) { 5286 final int accessibilityViewId = message.arg1; 5287 final int virtualDescendantId = message.arg2; 5288 SomeArgs args = (SomeArgs) message.obj; 5289 final int action = args.argi1; 5290 final int interactionId = args.argi2; 5291 final IAccessibilityInteractionConnectionCallback callback = 5292 (IAccessibilityInteractionConnectionCallback) args.arg1; 5293 mPool.release(args); 5294 boolean succeeded = false; 5295 try { 5296 View target = findViewByAccessibilityId(accessibilityViewId); 5297 if (target != null && target.getVisibility() == View.VISIBLE) { 5298 AccessibilityNodeProvider provider = target.getAccessibilityNodeProvider(); 5299 if (provider != null) { 5300 succeeded = provider.performAccessibilityAction(action, 5301 virtualDescendantId); 5302 } else if (virtualDescendantId == AccessibilityNodeInfo.UNDEFINED) { 5303 switch (action) { 5304 case AccessibilityNodeInfo.ACTION_FOCUS: { 5305 if (!target.hasFocus()) { 5306 // Get out of touch mode since accessibility 5307 // wants to move focus around. 5308 ensureTouchMode(false); 5309 succeeded = target.requestFocus(); 5310 } 5311 } break; 5312 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 5313 if (target.hasFocus()) { 5314 target.clearFocus(); 5315 succeeded = !target.isFocused(); 5316 } 5317 } break; 5318 case AccessibilityNodeInfo.ACTION_SELECT: { 5319 if (!target.isSelected()) { 5320 target.setSelected(true); 5321 succeeded = target.isSelected(); 5322 } 5323 } break; 5324 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 5325 if (target.isSelected()) { 5326 target.setSelected(false); 5327 succeeded = !target.isSelected(); 5328 } 5329 } break; 5330 } 5331 } 5332 } 5333 } finally { 5334 try { 5335 callback.setPerformAccessibilityActionResult(succeeded, interactionId); 5336 } catch (RemoteException re) { 5337 /* ignore - the other side will time out */ 5338 } 5339 } 5340 } 5341 5342 private View findViewByAccessibilityId(int accessibilityId) { 5343 View root = ViewRootImpl.this.mView; 5344 if (root == null) { 5345 return null; 5346 } 5347 View foundView = root.findViewByAccessibilityId(accessibilityId); 5348 if (foundView != null && foundView.getVisibility() != View.VISIBLE) { 5349 return null; 5350 } 5351 return foundView; 5352 } 5353 } 5354 5355 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 5356 public volatile boolean mIsPending; 5357 5358 public void run() { 5359 if (mView != null) { 5360 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 5361 mIsPending = false; 5362 } 5363 } 5364 } 5365 5366 /** 5367 * This class encapsulates a prefetching strategy for the accessibility APIs for 5368 * querying window content. It is responsible to prefetch a batch of 5369 * AccessibilityNodeInfos in addition to the one for a requested node. 5370 */ 5371 class AccessibilityNodePrefetcher { 5372 5373 private static final int MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE = 50; 5374 5375 public void prefetchAccessibilityNodeInfos(View view, int virtualViewId, int prefetchFlags, 5376 List<AccessibilityNodeInfo> outInfos) { 5377 AccessibilityNodeProvider provider = view.getAccessibilityNodeProvider(); 5378 if (provider == null) { 5379 AccessibilityNodeInfo root = view.createAccessibilityNodeInfo(); 5380 if (root != null) { 5381 outInfos.add(root); 5382 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_PREDECESSORS) != 0) { 5383 prefetchPredecessorsOfRealNode(view, outInfos); 5384 } 5385 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_SIBLINGS) != 0) { 5386 prefetchSiblingsOfRealNode(view, outInfos); 5387 } 5388 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_DESCENDANTS) != 0) { 5389 prefetchDescendantsOfRealNode(view, outInfos); 5390 } 5391 } 5392 } else { 5393 AccessibilityNodeInfo root = provider.createAccessibilityNodeInfo(virtualViewId); 5394 if (root != null) { 5395 outInfos.add(root); 5396 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_PREDECESSORS) != 0) { 5397 prefetchPredecessorsOfVirtualNode(root, view, provider, outInfos); 5398 } 5399 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_SIBLINGS) != 0) { 5400 prefetchSiblingsOfVirtualNode(root, view, provider, outInfos); 5401 } 5402 if ((prefetchFlags & AccessibilityNodeInfo.FLAG_PREFETCH_DESCENDANTS) != 0) { 5403 prefetchDescendantsOfVirtualNode(root, provider, outInfos); 5404 } 5405 } 5406 } 5407 } 5408 5409 private void prefetchPredecessorsOfRealNode(View view, 5410 List<AccessibilityNodeInfo> outInfos) { 5411 ViewParent parent = view.getParent(); 5412 while (parent instanceof View 5413 && outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5414 View parentView = (View) parent; 5415 final long parentNodeId = AccessibilityNodeInfo.makeNodeId( 5416 parentView.getAccessibilityViewId(), AccessibilityNodeInfo.UNDEFINED); 5417 AccessibilityNodeInfo info = parentView.createAccessibilityNodeInfo(); 5418 if (info != null) { 5419 outInfos.add(info); 5420 } 5421 parent = parent.getParent(); 5422 } 5423 } 5424 5425 private void prefetchSiblingsOfRealNode(View current, 5426 List<AccessibilityNodeInfo> outInfos) { 5427 ViewParent parent = current.getParent(); 5428 if (parent instanceof ViewGroup) { 5429 ViewGroup parentGroup = (ViewGroup) parent; 5430 final int childCount = parentGroup.getChildCount(); 5431 for (int i = 0; i < childCount; i++) { 5432 View child = parentGroup.getChildAt(i); 5433 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE 5434 && child.getAccessibilityViewId() != current.getAccessibilityViewId() 5435 && child.getVisibility() == View.VISIBLE) { 5436 final long childNodeId = AccessibilityNodeInfo.makeNodeId( 5437 child.getAccessibilityViewId(), AccessibilityNodeInfo.UNDEFINED); 5438 AccessibilityNodeInfo info = null; 5439 AccessibilityNodeProvider provider = child.getAccessibilityNodeProvider(); 5440 if (provider == null) { 5441 info = child.createAccessibilityNodeInfo(); 5442 } else { 5443 info = provider.createAccessibilityNodeInfo( 5444 AccessibilityNodeInfo.UNDEFINED); 5445 } 5446 if (info != null) { 5447 outInfos.add(info); 5448 } 5449 } 5450 } 5451 } 5452 } 5453 5454 private void prefetchDescendantsOfRealNode(View root, 5455 List<AccessibilityNodeInfo> outInfos) { 5456 if (root instanceof ViewGroup) { 5457 ViewGroup rootGroup = (ViewGroup) root; 5458 HashMap<View, AccessibilityNodeInfo> addedChildren = 5459 new HashMap<View, AccessibilityNodeInfo>(); 5460 final int childCount = rootGroup.getChildCount(); 5461 for (int i = 0; i < childCount; i++) { 5462 View child = rootGroup.getChildAt(i); 5463 if (child.getVisibility() == View.VISIBLE 5464 && outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5465 final long childNodeId = AccessibilityNodeInfo.makeNodeId( 5466 child.getAccessibilityViewId(), AccessibilityNodeInfo.UNDEFINED); 5467 AccessibilityNodeProvider provider = child.getAccessibilityNodeProvider(); 5468 if (provider == null) { 5469 AccessibilityNodeInfo info = child.createAccessibilityNodeInfo(); 5470 if (info != null) { 5471 outInfos.add(info); 5472 addedChildren.put(child, null); 5473 } 5474 } else { 5475 AccessibilityNodeInfo info = provider.createAccessibilityNodeInfo( 5476 AccessibilityNodeInfo.UNDEFINED); 5477 if (info != null) { 5478 outInfos.add(info); 5479 addedChildren.put(child, info); 5480 } 5481 } 5482 } 5483 } 5484 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5485 for (Map.Entry<View, AccessibilityNodeInfo> entry : addedChildren.entrySet()) { 5486 View addedChild = entry.getKey(); 5487 AccessibilityNodeInfo virtualRoot = entry.getValue(); 5488 if (virtualRoot == null) { 5489 prefetchDescendantsOfRealNode(addedChild, outInfos); 5490 } else { 5491 AccessibilityNodeProvider provider = 5492 addedChild.getAccessibilityNodeProvider(); 5493 prefetchDescendantsOfVirtualNode(virtualRoot, provider, outInfos); 5494 } 5495 } 5496 } 5497 } 5498 } 5499 5500 private void prefetchPredecessorsOfVirtualNode(AccessibilityNodeInfo root, 5501 View providerHost, AccessibilityNodeProvider provider, 5502 List<AccessibilityNodeInfo> outInfos) { 5503 long parentNodeId = root.getParentNodeId(); 5504 int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(parentNodeId); 5505 while (accessibilityViewId != AccessibilityNodeInfo.UNDEFINED) { 5506 final int virtualDescendantId = 5507 AccessibilityNodeInfo.getVirtualDescendantId(parentNodeId); 5508 if (virtualDescendantId != AccessibilityNodeInfo.UNDEFINED 5509 || accessibilityViewId == providerHost.getAccessibilityViewId()) { 5510 AccessibilityNodeInfo parent = provider.createAccessibilityNodeInfo( 5511 virtualDescendantId); 5512 if (parent != null) { 5513 outInfos.add(parent); 5514 } 5515 parentNodeId = parent.getParentNodeId(); 5516 accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5517 parentNodeId); 5518 } else { 5519 prefetchPredecessorsOfRealNode(providerHost, outInfos); 5520 return; 5521 } 5522 } 5523 } 5524 5525 private void prefetchSiblingsOfVirtualNode(AccessibilityNodeInfo current, View providerHost, 5526 AccessibilityNodeProvider provider, List<AccessibilityNodeInfo> outInfos) { 5527 final long parentNodeId = current.getParentNodeId(); 5528 final int parentAccessibilityViewId = 5529 AccessibilityNodeInfo.getAccessibilityViewId(parentNodeId); 5530 final int parentVirtualDescendantId = 5531 AccessibilityNodeInfo.getVirtualDescendantId(parentNodeId); 5532 if (parentVirtualDescendantId != AccessibilityNodeInfo.UNDEFINED 5533 || parentAccessibilityViewId == providerHost.getAccessibilityViewId()) { 5534 AccessibilityNodeInfo parent = 5535 provider.createAccessibilityNodeInfo(parentVirtualDescendantId); 5536 if (parent != null) { 5537 SparseLongArray childNodeIds = parent.getChildNodeIds(); 5538 final int childCount = childNodeIds.size(); 5539 for (int i = 0; i < childCount; i++) { 5540 final long childNodeId = childNodeIds.get(i); 5541 if (childNodeId != current.getSourceNodeId() 5542 && outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5543 final int childVirtualDescendantId = 5544 AccessibilityNodeInfo.getVirtualDescendantId(childNodeId); 5545 AccessibilityNodeInfo child = provider.createAccessibilityNodeInfo( 5546 childVirtualDescendantId); 5547 if (child != null) { 5548 outInfos.add(child); 5549 } 5550 } 5551 } 5552 } 5553 } else { 5554 prefetchSiblingsOfRealNode(providerHost, outInfos); 5555 } 5556 } 5557 5558 private void prefetchDescendantsOfVirtualNode(AccessibilityNodeInfo root, 5559 AccessibilityNodeProvider provider, List<AccessibilityNodeInfo> outInfos) { 5560 SparseLongArray childNodeIds = root.getChildNodeIds(); 5561 final int initialOutInfosSize = outInfos.size(); 5562 final int childCount = childNodeIds.size(); 5563 for (int i = 0; i < childCount; i++) { 5564 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5565 final long childNodeId = childNodeIds.get(i); 5566 AccessibilityNodeInfo child = provider.createAccessibilityNodeInfo( 5567 AccessibilityNodeInfo.getVirtualDescendantId(childNodeId)); 5568 if (child != null) { 5569 outInfos.add(child); 5570 } 5571 } 5572 } 5573 if (outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5574 final int addedChildCount = outInfos.size() - initialOutInfosSize; 5575 for (int i = 0; i < addedChildCount; i++) { 5576 AccessibilityNodeInfo child = outInfos.get(initialOutInfosSize + i); 5577 prefetchDescendantsOfVirtualNode(child, provider, outInfos); 5578 } 5579 } 5580 } 5581 } 5582} 5583