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