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