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