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