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