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