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