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