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