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