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