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