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