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