ViewRootImpl.java revision 97d5c418730946a0332f601cd140ed0b12ea19c1
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 } 639 } 640 641 void destroyHardwareResources() { 642 if (mAttachInfo.mHardwareRenderer != null) { 643 if (mAttachInfo.mHardwareRenderer.isEnabled()) { 644 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 645 } 646 mAttachInfo.mHardwareRenderer.destroy(false); 647 } 648 } 649 650 void terminateHardwareResources() { 651 if (mAttachInfo.mHardwareRenderer != null) { 652 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView); 653 mAttachInfo.mHardwareRenderer.destroy(false); 654 } 655 } 656 657 void destroyHardwareLayers() { 658 if (mThread != Thread.currentThread()) { 659 if (mAttachInfo.mHardwareRenderer != null && 660 mAttachInfo.mHardwareRenderer.isEnabled()) { 661 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE); 662 } 663 } else { 664 if (mAttachInfo.mHardwareRenderer != null && 665 mAttachInfo.mHardwareRenderer.isEnabled()) { 666 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 667 } 668 } 669 } 670 671 public void attachFunctor(int functor) { 672 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 673 mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor); 674 } 675 } 676 677 public void detachFunctor(int functor) { 678 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 679 mAttachInfo.mHardwareRenderer.detachFunctor(functor); 680 } 681 } 682 683 private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) { 684 mAttachInfo.mHardwareAccelerated = false; 685 mAttachInfo.mHardwareAccelerationRequested = false; 686 687 // Don't enable hardware acceleration when the application is in compatibility mode 688 if (mTranslator != null) return; 689 690 // Try to enable hardware acceleration if requested 691 final boolean hardwareAccelerated = 692 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0; 693 694 if (hardwareAccelerated) { 695 if (!HardwareRenderer.isAvailable()) { 696 return; 697 } 698 699 // Persistent processes (including the system) should not do 700 // accelerated rendering on low-end devices. In that case, 701 // sRendererDisabled will be set. In addition, the system process 702 // itself should never do accelerated rendering. In that case, both 703 // sRendererDisabled and sSystemRendererDisabled are set. When 704 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED 705 // can be used by code on the system process to escape that and enable 706 // HW accelerated drawing. (This is basically for the lock screen.) 707 708 final boolean fakeHwAccelerated = (attrs.privateFlags & 709 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0; 710 final boolean forceHwAccelerated = (attrs.privateFlags & 711 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0; 712 713 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled 714 && forceHwAccelerated)) { 715 // Don't enable hardware acceleration when we're not on the main thread 716 if (!HardwareRenderer.sSystemRendererDisabled && 717 Looper.getMainLooper() != Looper.myLooper()) { 718 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware " 719 + "acceleration outside of the main thread, aborting"); 720 return; 721 } 722 723 final boolean renderThread = isRenderThreadRequested(context); 724 if (renderThread) { 725 Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated"); 726 } 727 728 if (mAttachInfo.mHardwareRenderer != null) { 729 mAttachInfo.mHardwareRenderer.destroy(true); 730 } 731 732 final boolean translucent = attrs.format != PixelFormat.OPAQUE; 733 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent); 734 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested 735 = mAttachInfo.mHardwareRenderer != null; 736 737 } else if (fakeHwAccelerated) { 738 // The window had wanted to use hardware acceleration, but this 739 // is not allowed in its process. By setting this flag, it can 740 // still render as if it was accelerated. This is basically for 741 // the preview windows the window manager shows for launching 742 // applications, so they will look more like the app being launched. 743 mAttachInfo.mHardwareAccelerationRequested = true; 744 } 745 } 746 } 747 748 public View getView() { 749 return mView; 750 } 751 752 final WindowLeaked getLocation() { 753 return mLocation; 754 } 755 756 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) { 757 synchronized (this) { 758 int oldSoftInputMode = mWindowAttributes.softInputMode; 759 // preserve compatible window flag if exists. 760 int compatibleWindowFlag = 761 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 762 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs); 763 mWindowAttributes.flags |= compatibleWindowFlag; 764 765 if (newView) { 766 mSoftInputMode = attrs.softInputMode; 767 requestLayout(); 768 } 769 // Don't lose the mode we last auto-computed. 770 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 771 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 772 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode 773 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 774 | (oldSoftInputMode 775 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST); 776 } 777 mWindowAttributesChanged = true; 778 scheduleTraversals(); 779 } 780 } 781 782 void handleAppVisibility(boolean visible) { 783 if (mAppVisible != visible) { 784 mAppVisible = visible; 785 scheduleTraversals(); 786 } 787 } 788 789 void handleGetNewSurface() { 790 mNewSurfaceNeeded = true; 791 mFullRedrawNeeded = true; 792 scheduleTraversals(); 793 } 794 795 void handleScreenStateChange(boolean on) { 796 if (on != mAttachInfo.mScreenOn) { 797 mAttachInfo.mScreenOn = on; 798 if (mView != null) { 799 mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF); 800 } 801 if (on) { 802 mFullRedrawNeeded = true; 803 scheduleTraversals(); 804 } 805 } 806 } 807 808 /** 809 * {@inheritDoc} 810 */ 811 public void requestFitSystemWindows() { 812 checkThread(); 813 mFitSystemWindowsRequested = true; 814 scheduleTraversals(); 815 } 816 817 /** 818 * {@inheritDoc} 819 */ 820 public void requestLayout() { 821 checkThread(); 822 mLayoutRequested = true; 823 scheduleTraversals(); 824 } 825 826 /** 827 * {@inheritDoc} 828 */ 829 public boolean isLayoutRequested() { 830 return mLayoutRequested; 831 } 832 833 void invalidate() { 834 mDirty.set(0, 0, mWidth, mHeight); 835 scheduleTraversals(); 836 } 837 838 public void invalidateChild(View child, Rect dirty) { 839 invalidateChildInParent(null, dirty); 840 } 841 842 public ViewParent invalidateChildInParent(int[] location, Rect dirty) { 843 checkThread(); 844 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty); 845 846 if (dirty == null) { 847 invalidate(); 848 return null; 849 } 850 851 if (mCurScrollY != 0 || mTranslator != null) { 852 mTempRect.set(dirty); 853 dirty = mTempRect; 854 if (mCurScrollY != 0) { 855 dirty.offset(0, -mCurScrollY); 856 } 857 if (mTranslator != null) { 858 mTranslator.translateRectInAppWindowToScreen(dirty); 859 } 860 if (mAttachInfo.mScalingRequired) { 861 dirty.inset(-1, -1); 862 } 863 } 864 865 final Rect localDirty = mDirty; 866 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) { 867 mAttachInfo.mSetIgnoreDirtyState = true; 868 mAttachInfo.mIgnoreDirtyState = true; 869 } 870 871 // Add the new dirty rect to the current one 872 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom); 873 // Intersect with the bounds of the window to skip 874 // updates that lie outside of the visible region 875 final float appScale = mAttachInfo.mApplicationScale; 876 localDirty.intersect(0, 0, 877 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 878 879 if (!mWillDrawSoon) { 880 scheduleTraversals(); 881 } 882 883 return null; 884 } 885 886 void setStopped(boolean stopped) { 887 if (mStopped != stopped) { 888 mStopped = stopped; 889 if (!stopped) { 890 scheduleTraversals(); 891 } 892 } 893 } 894 895 public ViewParent getParent() { 896 return null; 897 } 898 899 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 900 if (child != mView) { 901 throw new RuntimeException("child is not mine, honest!"); 902 } 903 // Note: don't apply scroll offset, because we want to know its 904 // visibility in the virtual canvas being given to the view hierarchy. 905 return r.intersect(0, 0, mWidth, mHeight); 906 } 907 908 public void bringChildToFront(View child) { 909 } 910 911 int getHostVisibility() { 912 return mAppVisible ? mView.getVisibility() : View.GONE; 913 } 914 915 void disposeResizeBuffer() { 916 if (mResizeBuffer != null) { 917 mResizeBuffer.destroy(); 918 mResizeBuffer = null; 919 } 920 } 921 922 /** 923 * Add LayoutTransition to the list of transitions to be started in the next traversal. 924 * This list will be cleared after the transitions on the list are start()'ed. These 925 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup 926 * happens during the layout phase of traversal, which we want to complete before any of the 927 * animations are started (because those animations may side-effect properties that layout 928 * depends upon, like the bounding rectangles of the affected views). So we add the transition 929 * to the list and it is started just prior to starting the drawing phase of traversal. 930 * 931 * @param transition The LayoutTransition to be started on the next traversal. 932 * 933 * @hide 934 */ 935 public void requestTransitionStart(LayoutTransition transition) { 936 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) { 937 if (mPendingTransitions == null) { 938 mPendingTransitions = new ArrayList<LayoutTransition>(); 939 } 940 mPendingTransitions.add(transition); 941 } 942 } 943 944 void scheduleTraversals() { 945 if (!mTraversalScheduled) { 946 mTraversalScheduled = true; 947 mTraversalBarrier = mHandler.getLooper().postSyncBarrier(); 948 mChoreographer.postCallback( 949 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 950 } 951 } 952 953 void unscheduleTraversals() { 954 if (mTraversalScheduled) { 955 mTraversalScheduled = false; 956 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 957 mChoreographer.removeCallbacks( 958 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 959 } 960 } 961 962 void doTraversal() { 963 if (mTraversalScheduled) { 964 mTraversalScheduled = false; 965 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 966 967 doConsumeBatchedInput(false); 968 doProcessInputEvents(); 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 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds); 2332 bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop); 2333 } 2334 drawable.setBounds(bounds); 2335 drawable.draw(canvas); 2336 } 2337 2338 private Drawable getAccessibilityFocusedDrawable() { 2339 if (mAttachInfo != null) { 2340 // Lazily load the accessibility focus drawable. 2341 if (mAttachInfo.mAccessibilityFocusDrawable == null) { 2342 TypedValue value = new TypedValue(); 2343 final boolean resolved = mView.mContext.getTheme().resolveAttribute( 2344 R.attr.accessibilityFocusedDrawable, value, true); 2345 if (resolved) { 2346 mAttachInfo.mAccessibilityFocusDrawable = 2347 mView.mContext.getResources().getDrawable(value.resourceId); 2348 } 2349 } 2350 return mAttachInfo.mAccessibilityFocusDrawable; 2351 } 2352 return null; 2353 } 2354 2355 void invalidateDisplayLists() { 2356 final ArrayList<DisplayList> displayLists = mDisplayLists; 2357 final int count = displayLists.size(); 2358 2359 for (int i = 0; i < count; i++) { 2360 displayLists.get(i).invalidate(); 2361 } 2362 2363 displayLists.clear(); 2364 } 2365 2366 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2367 final View.AttachInfo attachInfo = mAttachInfo; 2368 final Rect ci = attachInfo.mContentInsets; 2369 final Rect vi = attachInfo.mVisibleInsets; 2370 int scrollY = 0; 2371 boolean handled = false; 2372 2373 if (vi.left > ci.left || vi.top > ci.top 2374 || vi.right > ci.right || vi.bottom > ci.bottom) { 2375 // We'll assume that we aren't going to change the scroll 2376 // offset, since we want to avoid that unless it is actually 2377 // going to make the focus visible... otherwise we scroll 2378 // all over the place. 2379 scrollY = mScrollY; 2380 // We can be called for two different situations: during a draw, 2381 // to update the scroll position if the focus has changed (in which 2382 // case 'rectangle' is null), or in response to a 2383 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2384 // is non-null and we just want to scroll to whatever that 2385 // rectangle is). 2386 View focus = mRealFocusedView; 2387 2388 // When in touch mode, focus points to the previously focused view, 2389 // which may have been removed from the view hierarchy. The following 2390 // line checks whether the view is still in our hierarchy. 2391 if (focus == null || focus.mAttachInfo != mAttachInfo) { 2392 mRealFocusedView = null; 2393 return false; 2394 } 2395 2396 if (focus != mLastScrolledFocus) { 2397 // If the focus has changed, then ignore any requests to scroll 2398 // to a rectangle; first we want to make sure the entire focus 2399 // view is visible. 2400 rectangle = null; 2401 } 2402 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2403 + " rectangle=" + rectangle + " ci=" + ci 2404 + " vi=" + vi); 2405 if (focus == mLastScrolledFocus && !mScrollMayChange 2406 && rectangle == null) { 2407 // Optimization: if the focus hasn't changed since last 2408 // time, and no layout has happened, then just leave things 2409 // as they are. 2410 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2411 + mScrollY + " vi=" + vi.toShortString()); 2412 } else if (focus != null) { 2413 // We need to determine if the currently focused view is 2414 // within the visible part of the window and, if not, apply 2415 // a pan so it can be seen. 2416 mLastScrolledFocus = focus; 2417 mScrollMayChange = false; 2418 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2419 // Try to find the rectangle from the focus view. 2420 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2421 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2422 + mView.getWidth() + " h=" + mView.getHeight() 2423 + " ci=" + ci.toShortString() 2424 + " vi=" + vi.toShortString()); 2425 if (rectangle == null) { 2426 focus.getFocusedRect(mTempRect); 2427 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2428 + ": focusRect=" + mTempRect.toShortString()); 2429 if (mView instanceof ViewGroup) { 2430 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2431 focus, mTempRect); 2432 } 2433 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2434 "Focus in window: focusRect=" 2435 + mTempRect.toShortString() 2436 + " visRect=" + mVisRect.toShortString()); 2437 } else { 2438 mTempRect.set(rectangle); 2439 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2440 "Request scroll to rect: " 2441 + mTempRect.toShortString() 2442 + " visRect=" + mVisRect.toShortString()); 2443 } 2444 if (mTempRect.intersect(mVisRect)) { 2445 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2446 "Focus window visible rect: " 2447 + mTempRect.toShortString()); 2448 if (mTempRect.height() > 2449 (mView.getHeight()-vi.top-vi.bottom)) { 2450 // If the focus simply is not going to fit, then 2451 // best is probably just to leave things as-is. 2452 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2453 "Too tall; leaving scrollY=" + scrollY); 2454 } else if ((mTempRect.top-scrollY) < vi.top) { 2455 scrollY -= vi.top - (mTempRect.top-scrollY); 2456 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2457 "Top covered; scrollY=" + scrollY); 2458 } else if ((mTempRect.bottom-scrollY) 2459 > (mView.getHeight()-vi.bottom)) { 2460 scrollY += (mTempRect.bottom-scrollY) 2461 - (mView.getHeight()-vi.bottom); 2462 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2463 "Bottom covered; scrollY=" + scrollY); 2464 } 2465 handled = true; 2466 } 2467 } 2468 } 2469 } 2470 2471 if (scrollY != mScrollY) { 2472 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2473 + mScrollY + " , new=" + scrollY); 2474 if (!immediate && mResizeBuffer == null) { 2475 if (mScroller == null) { 2476 mScroller = new Scroller(mView.getContext()); 2477 } 2478 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2479 } else if (mScroller != null) { 2480 mScroller.abortAnimation(); 2481 } 2482 mScrollY = scrollY; 2483 } 2484 2485 return handled; 2486 } 2487 2488 void setAccessibilityFocusedHost(View host) { 2489 if (mAccessibilityFocusedHost != null && mAccessibilityFocusedVirtualView == null) { 2490 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(); 2491 } 2492 mAccessibilityFocusedHost = host; 2493 mAccessibilityFocusedVirtualView = null; 2494 } 2495 2496 public void requestChildFocus(View child, View focused) { 2497 checkThread(); 2498 2499 if (DEBUG_INPUT_RESIZE) { 2500 Log.v(TAG, "Request child focus: focus now " + focused); 2501 } 2502 2503 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused); 2504 scheduleTraversals(); 2505 2506 mFocusedView = mRealFocusedView = focused; 2507 } 2508 2509 public void clearChildFocus(View child) { 2510 checkThread(); 2511 2512 if (DEBUG_INPUT_RESIZE) { 2513 Log.v(TAG, "Clearing child focus"); 2514 } 2515 2516 mOldFocusedView = mFocusedView; 2517 2518 // Invoke the listener only if there is no view to take focus 2519 if (focusSearch(null, View.FOCUS_FORWARD) == null) { 2520 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null); 2521 } 2522 2523 mFocusedView = mRealFocusedView = null; 2524 } 2525 2526 @Override 2527 public ViewParent getParentForAccessibility() { 2528 return null; 2529 } 2530 2531 public void focusableViewAvailable(View v) { 2532 checkThread(); 2533 if (mView != null) { 2534 if (!mView.hasFocus()) { 2535 v.requestFocus(); 2536 } else { 2537 // the one case where will transfer focus away from the current one 2538 // is if the current view is a view group that prefers to give focus 2539 // to its children first AND the view is a descendant of it. 2540 mFocusedView = mView.findFocus(); 2541 boolean descendantsHaveDibsOnFocus = 2542 (mFocusedView instanceof ViewGroup) && 2543 (((ViewGroup) mFocusedView).getDescendantFocusability() == 2544 ViewGroup.FOCUS_AFTER_DESCENDANTS); 2545 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) { 2546 // If a view gets the focus, the listener will be invoked from requestChildFocus() 2547 v.requestFocus(); 2548 } 2549 } 2550 } 2551 } 2552 2553 public void recomputeViewAttributes(View child) { 2554 checkThread(); 2555 if (mView == child) { 2556 mAttachInfo.mRecomputeGlobalAttributes = true; 2557 if (!mWillDrawSoon) { 2558 scheduleTraversals(); 2559 } 2560 } 2561 } 2562 2563 void dispatchDetachedFromWindow() { 2564 if (mView != null && mView.mAttachInfo != null) { 2565 if (mAttachInfo.mHardwareRenderer != null && 2566 mAttachInfo.mHardwareRenderer.isEnabled()) { 2567 mAttachInfo.mHardwareRenderer.validate(); 2568 } 2569 mView.dispatchDetachedFromWindow(); 2570 } 2571 2572 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2573 mAccessibilityManager.removeAccessibilityStateChangeListener( 2574 mAccessibilityInteractionConnectionManager); 2575 removeSendWindowContentChangedCallback(); 2576 2577 destroyHardwareRenderer(); 2578 2579 mView = null; 2580 mAttachInfo.mRootView = null; 2581 mAttachInfo.mSurface = null; 2582 2583 mSurface.release(); 2584 2585 if (mInputQueueCallback != null && mInputQueue != null) { 2586 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2587 mInputQueueCallback = null; 2588 mInputQueue = null; 2589 } else if (mInputEventReceiver != null) { 2590 mInputEventReceiver.dispose(); 2591 mInputEventReceiver = null; 2592 } 2593 try { 2594 sWindowSession.remove(mWindow); 2595 } catch (RemoteException e) { 2596 } 2597 2598 // Dispose the input channel after removing the window so the Window Manager 2599 // doesn't interpret the input channel being closed as an abnormal termination. 2600 if (mInputChannel != null) { 2601 mInputChannel.dispose(); 2602 mInputChannel = null; 2603 } 2604 2605 unscheduleTraversals(); 2606 } 2607 2608 void updateConfiguration(Configuration config, boolean force) { 2609 if (DEBUG_CONFIGURATION) Log.v(TAG, 2610 "Applying new config to window " 2611 + mWindowAttributes.getTitle() 2612 + ": " + config); 2613 2614 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded(); 2615 if (ci != null) { 2616 config = new Configuration(config); 2617 ci.applyToConfiguration(config); 2618 } 2619 2620 synchronized (sConfigCallbacks) { 2621 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2622 sConfigCallbacks.get(i).onConfigurationChanged(config); 2623 } 2624 } 2625 if (mView != null) { 2626 // At this point the resources have been updated to 2627 // have the most recent config, whatever that is. Use 2628 // the on in them which may be newer. 2629 config = mView.getResources().getConfiguration(); 2630 if (force || mLastConfiguration.diff(config) != 0) { 2631 mLastConfiguration.setTo(config); 2632 mView.dispatchConfigurationChanged(config); 2633 } 2634 } 2635 } 2636 2637 /** 2638 * Return true if child is an ancestor of parent, (or equal to the parent). 2639 */ 2640 static boolean isViewDescendantOf(View child, View parent) { 2641 if (child == parent) { 2642 return true; 2643 } 2644 2645 final ViewParent theParent = child.getParent(); 2646 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2647 } 2648 2649 private static void forceLayout(View view) { 2650 view.forceLayout(); 2651 if (view instanceof ViewGroup) { 2652 ViewGroup group = (ViewGroup) view; 2653 final int count = group.getChildCount(); 2654 for (int i = 0; i < count; i++) { 2655 forceLayout(group.getChildAt(i)); 2656 } 2657 } 2658 } 2659 2660 private final static int MSG_INVALIDATE = 1; 2661 private final static int MSG_INVALIDATE_RECT = 2; 2662 private final static int MSG_DIE = 3; 2663 private final static int MSG_RESIZED = 4; 2664 private final static int MSG_RESIZED_REPORT = 5; 2665 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 2666 private final static int MSG_DISPATCH_KEY = 7; 2667 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 2668 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 2669 private final static int MSG_IME_FINISHED_EVENT = 10; 2670 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 2671 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 2672 private final static int MSG_CHECK_FOCUS = 13; 2673 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 2674 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 2675 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 2676 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 2677 private final static int MSG_UPDATE_CONFIGURATION = 18; 2678 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 2679 private final static int MSG_DISPATCH_SCREEN_STATE = 20; 2680 private final static int MSG_INVALIDATE_DISPLAY_LIST = 21; 2681 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 22; 2682 2683 final class ViewRootHandler extends Handler { 2684 @Override 2685 public String getMessageName(Message message) { 2686 switch (message.what) { 2687 case MSG_INVALIDATE: 2688 return "MSG_INVALIDATE"; 2689 case MSG_INVALIDATE_RECT: 2690 return "MSG_INVALIDATE_RECT"; 2691 case MSG_DIE: 2692 return "MSG_DIE"; 2693 case MSG_RESIZED: 2694 return "MSG_RESIZED"; 2695 case MSG_RESIZED_REPORT: 2696 return "MSG_RESIZED_REPORT"; 2697 case MSG_WINDOW_FOCUS_CHANGED: 2698 return "MSG_WINDOW_FOCUS_CHANGED"; 2699 case MSG_DISPATCH_KEY: 2700 return "MSG_DISPATCH_KEY"; 2701 case MSG_DISPATCH_APP_VISIBILITY: 2702 return "MSG_DISPATCH_APP_VISIBILITY"; 2703 case MSG_DISPATCH_GET_NEW_SURFACE: 2704 return "MSG_DISPATCH_GET_NEW_SURFACE"; 2705 case MSG_IME_FINISHED_EVENT: 2706 return "MSG_IME_FINISHED_EVENT"; 2707 case MSG_DISPATCH_KEY_FROM_IME: 2708 return "MSG_DISPATCH_KEY_FROM_IME"; 2709 case MSG_FINISH_INPUT_CONNECTION: 2710 return "MSG_FINISH_INPUT_CONNECTION"; 2711 case MSG_CHECK_FOCUS: 2712 return "MSG_CHECK_FOCUS"; 2713 case MSG_CLOSE_SYSTEM_DIALOGS: 2714 return "MSG_CLOSE_SYSTEM_DIALOGS"; 2715 case MSG_DISPATCH_DRAG_EVENT: 2716 return "MSG_DISPATCH_DRAG_EVENT"; 2717 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 2718 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 2719 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 2720 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 2721 case MSG_UPDATE_CONFIGURATION: 2722 return "MSG_UPDATE_CONFIGURATION"; 2723 case MSG_PROCESS_INPUT_EVENTS: 2724 return "MSG_PROCESS_INPUT_EVENTS"; 2725 case MSG_DISPATCH_SCREEN_STATE: 2726 return "MSG_DISPATCH_SCREEN_STATE"; 2727 case MSG_INVALIDATE_DISPLAY_LIST: 2728 return "MSG_INVALIDATE_DISPLAY_LIST"; 2729 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 2730 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 2731 } 2732 return super.getMessageName(message); 2733 } 2734 2735 @Override 2736 public void handleMessage(Message msg) { 2737 switch (msg.what) { 2738 case MSG_INVALIDATE: 2739 ((View) msg.obj).invalidate(); 2740 break; 2741 case MSG_INVALIDATE_RECT: 2742 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 2743 info.target.invalidate(info.left, info.top, info.right, info.bottom); 2744 info.release(); 2745 break; 2746 case MSG_IME_FINISHED_EVENT: 2747 handleImeFinishedEvent(msg.arg1, msg.arg2 != 0); 2748 break; 2749 case MSG_PROCESS_INPUT_EVENTS: 2750 mProcessInputEventsScheduled = false; 2751 doProcessInputEvents(); 2752 break; 2753 case MSG_DISPATCH_APP_VISIBILITY: 2754 handleAppVisibility(msg.arg1 != 0); 2755 break; 2756 case MSG_DISPATCH_GET_NEW_SURFACE: 2757 handleGetNewSurface(); 2758 break; 2759 case MSG_RESIZED: 2760 ResizedInfo ri = (ResizedInfo)msg.obj; 2761 2762 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2 2763 && mPendingContentInsets.equals(ri.coveredInsets) 2764 && mPendingVisibleInsets.equals(ri.visibleInsets) 2765 && ((ResizedInfo)msg.obj).newConfig == null) { 2766 break; 2767 } 2768 // fall through... 2769 case MSG_RESIZED_REPORT: 2770 if (mAdded) { 2771 Configuration config = ((ResizedInfo)msg.obj).newConfig; 2772 if (config != null) { 2773 updateConfiguration(config, false); 2774 } 2775 mWinFrame.left = 0; 2776 mWinFrame.right = msg.arg1; 2777 mWinFrame.top = 0; 2778 mWinFrame.bottom = msg.arg2; 2779 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets); 2780 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets); 2781 if (msg.what == MSG_RESIZED_REPORT) { 2782 mReportNextDraw = true; 2783 } 2784 2785 if (mView != null) { 2786 forceLayout(mView); 2787 } 2788 requestLayout(); 2789 } 2790 break; 2791 case MSG_WINDOW_FOCUS_CHANGED: { 2792 if (mAdded) { 2793 boolean hasWindowFocus = msg.arg1 != 0; 2794 mAttachInfo.mHasWindowFocus = hasWindowFocus; 2795 2796 profileRendering(hasWindowFocus); 2797 2798 if (hasWindowFocus) { 2799 boolean inTouchMode = msg.arg2 != 0; 2800 ensureTouchModeLocally(inTouchMode); 2801 2802 if (mAttachInfo.mHardwareRenderer != null && 2803 mSurface != null && mSurface.isValid()) { 2804 mFullRedrawNeeded = true; 2805 try { 2806 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2807 mHolder); 2808 } catch (Surface.OutOfResourcesException e) { 2809 Log.e(TAG, "OutOfResourcesException locking surface", e); 2810 try { 2811 if (!sWindowSession.outOfMemory(mWindow)) { 2812 Slog.w(TAG, "No processes killed for memory; killing self"); 2813 Process.killProcess(Process.myPid()); 2814 } 2815 } catch (RemoteException ex) { 2816 } 2817 // Retry in a bit. 2818 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 2819 return; 2820 } 2821 } 2822 } 2823 2824 mLastWasImTarget = WindowManager.LayoutParams 2825 .mayUseInputMethod(mWindowAttributes.flags); 2826 2827 InputMethodManager imm = InputMethodManager.peekInstance(); 2828 if (mView != null) { 2829 if (hasWindowFocus && imm != null && mLastWasImTarget) { 2830 imm.startGettingWindowFocus(mView); 2831 } 2832 mAttachInfo.mKeyDispatchState.reset(); 2833 mView.dispatchWindowFocusChanged(hasWindowFocus); 2834 } 2835 2836 // Note: must be done after the focus change callbacks, 2837 // so all of the view state is set up correctly. 2838 if (hasWindowFocus) { 2839 if (imm != null && mLastWasImTarget) { 2840 imm.onWindowFocus(mView, mView.findFocus(), 2841 mWindowAttributes.softInputMode, 2842 !mHasHadWindowFocus, mWindowAttributes.flags); 2843 } 2844 // Clear the forward bit. We can just do this directly, since 2845 // the window manager doesn't care about it. 2846 mWindowAttributes.softInputMode &= 2847 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2848 ((WindowManager.LayoutParams)mView.getLayoutParams()) 2849 .softInputMode &= 2850 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2851 mHasHadWindowFocus = true; 2852 } 2853 2854 if (mView != null && mAccessibilityManager.isEnabled()) { 2855 if (hasWindowFocus) { 2856 mView.sendAccessibilityEvent( 2857 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 2858 // Give accessibility focus to the view that has input 2859 // focus if such, otherwise to the first one. 2860 if (mView instanceof ViewGroup) { 2861 ViewGroup viewGroup = (ViewGroup) mView; 2862 View focused = viewGroup.findFocus(); 2863 if (focused != null) { 2864 focused.requestAccessibilityFocus(); 2865 } 2866 } 2867 // There is no accessibility focus, despite our effort 2868 // above, now just give it to the first view. 2869 if (mAccessibilityFocusedHost == null) { 2870 mView.requestAccessibilityFocus(); 2871 } 2872 } else { 2873 // Clear accessibility focus when the window loses input focus. 2874 setAccessibilityFocusedHost(null); 2875 } 2876 } 2877 } 2878 } break; 2879 case MSG_DIE: 2880 doDie(); 2881 break; 2882 case MSG_DISPATCH_KEY: { 2883 KeyEvent event = (KeyEvent)msg.obj; 2884 enqueueInputEvent(event, null, 0, true); 2885 } break; 2886 case MSG_DISPATCH_KEY_FROM_IME: { 2887 if (LOCAL_LOGV) Log.v( 2888 TAG, "Dispatching key " 2889 + msg.obj + " from IME to " + mView); 2890 KeyEvent event = (KeyEvent)msg.obj; 2891 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 2892 // The IME is trying to say this event is from the 2893 // system! Bad bad bad! 2894 //noinspection UnusedAssignment 2895 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 2896 } 2897 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 2898 } break; 2899 case MSG_FINISH_INPUT_CONNECTION: { 2900 InputMethodManager imm = InputMethodManager.peekInstance(); 2901 if (imm != null) { 2902 imm.reportFinishInputConnection((InputConnection)msg.obj); 2903 } 2904 } break; 2905 case MSG_CHECK_FOCUS: { 2906 InputMethodManager imm = InputMethodManager.peekInstance(); 2907 if (imm != null) { 2908 imm.checkFocus(); 2909 } 2910 } break; 2911 case MSG_CLOSE_SYSTEM_DIALOGS: { 2912 if (mView != null) { 2913 mView.onCloseSystemDialogs((String)msg.obj); 2914 } 2915 } break; 2916 case MSG_DISPATCH_DRAG_EVENT: 2917 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 2918 DragEvent event = (DragEvent)msg.obj; 2919 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 2920 handleDragEvent(event); 2921 } break; 2922 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 2923 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj); 2924 } break; 2925 case MSG_UPDATE_CONFIGURATION: { 2926 Configuration config = (Configuration)msg.obj; 2927 if (config.isOtherSeqNewer(mLastConfiguration)) { 2928 config = mLastConfiguration; 2929 } 2930 updateConfiguration(config, false); 2931 } break; 2932 case MSG_DISPATCH_SCREEN_STATE: { 2933 if (mView != null) { 2934 handleScreenStateChange(msg.arg1 == 1); 2935 } 2936 } break; 2937 case MSG_INVALIDATE_DISPLAY_LIST: { 2938 invalidateDisplayLists(); 2939 } break; 2940 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 2941 setAccessibilityFocusedHost(null); 2942 } break; 2943 } 2944 } 2945 } 2946 2947 final ViewRootHandler mHandler = new ViewRootHandler(); 2948 2949 /** 2950 * Something in the current window tells us we need to change the touch mode. For 2951 * example, we are not in touch mode, and the user touches the screen. 2952 * 2953 * If the touch mode has changed, tell the window manager, and handle it locally. 2954 * 2955 * @param inTouchMode Whether we want to be in touch mode. 2956 * @return True if the touch mode changed and focus changed was changed as a result 2957 */ 2958 boolean ensureTouchMode(boolean inTouchMode) { 2959 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 2960 + "touch mode is " + mAttachInfo.mInTouchMode); 2961 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 2962 2963 // tell the window manager 2964 try { 2965 sWindowSession.setInTouchMode(inTouchMode); 2966 } catch (RemoteException e) { 2967 throw new RuntimeException(e); 2968 } 2969 2970 // handle the change 2971 return ensureTouchModeLocally(inTouchMode); 2972 } 2973 2974 /** 2975 * Ensure that the touch mode for this window is set, and if it is changing, 2976 * take the appropriate action. 2977 * @param inTouchMode Whether we want to be in touch mode. 2978 * @return True if the touch mode changed and focus changed was changed as a result 2979 */ 2980 private boolean ensureTouchModeLocally(boolean inTouchMode) { 2981 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 2982 + "touch mode is " + mAttachInfo.mInTouchMode); 2983 2984 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 2985 2986 mAttachInfo.mInTouchMode = inTouchMode; 2987 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 2988 2989 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 2990 } 2991 2992 private boolean enterTouchMode() { 2993 if (mView != null) { 2994 if (mView.hasFocus()) { 2995 // note: not relying on mFocusedView here because this could 2996 // be when the window is first being added, and mFocused isn't 2997 // set yet. 2998 final View focused = mView.findFocus(); 2999 if (focused != null) { 3000 if (focused.isFocusableInTouchMode()) { 3001 return true; 3002 } 3003 final ViewGroup ancestorToTakeFocus = 3004 findAncestorToTakeFocusInTouchMode(focused); 3005 if (ancestorToTakeFocus != null) { 3006 // there is an ancestor that wants focus after its descendants that 3007 // is focusable in touch mode.. give it focus 3008 return ancestorToTakeFocus.requestFocus(); 3009 } 3010 } 3011 // nothing appropriate to have focus in touch mode, clear it out 3012 mView.unFocus(); 3013 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null); 3014 mFocusedView = null; 3015 mOldFocusedView = null; 3016 return true; 3017 } 3018 } 3019 return false; 3020 } 3021 3022 /** 3023 * Find an ancestor of focused that wants focus after its descendants and is 3024 * focusable in touch mode. 3025 * @param focused The currently focused view. 3026 * @return An appropriate view, or null if no such view exists. 3027 */ 3028 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3029 ViewParent parent = focused.getParent(); 3030 while (parent instanceof ViewGroup) { 3031 final ViewGroup vgParent = (ViewGroup) parent; 3032 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3033 && vgParent.isFocusableInTouchMode()) { 3034 return vgParent; 3035 } 3036 if (vgParent.isRootNamespace()) { 3037 return null; 3038 } else { 3039 parent = vgParent.getParent(); 3040 } 3041 } 3042 return null; 3043 } 3044 3045 private boolean leaveTouchMode() { 3046 if (mView != null) { 3047 boolean inputFocusValid = false; 3048 if (mView.hasFocus()) { 3049 // i learned the hard way to not trust mFocusedView :) 3050 mFocusedView = mView.findFocus(); 3051 if (!(mFocusedView instanceof ViewGroup)) { 3052 // some view has focus, let it keep it 3053 inputFocusValid = true; 3054 } else if (((ViewGroup) mFocusedView).getDescendantFocusability() != 3055 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3056 // some view group has focus, and doesn't prefer its children 3057 // over itself for focus, so let them keep it. 3058 inputFocusValid = true; 3059 } 3060 } 3061 // In accessibility mode we always have a view that has the 3062 // accessibility focus and input focus follows it, i.e. we 3063 // try to give input focus to the accessibility focused view. 3064 if (!AccessibilityManager.getInstance(mView.mContext).isEnabled()) { 3065 // If the current input focus is not valid, find the best view to give 3066 // focus to in this brave new non-touch-mode world. 3067 if (!inputFocusValid) { 3068 final View focused = focusSearch(null, View.FOCUS_DOWN); 3069 if (focused != null) { 3070 return focused.requestFocus(View.FOCUS_DOWN); 3071 } 3072 } 3073 } else { 3074 // If the current input focus is not valid clear it but do not 3075 // give it to another view since the accessibility focus is 3076 // leading now and the input one follows. 3077 if (!inputFocusValid) { 3078 if (mFocusedView != null) { 3079 mView.unFocus(); 3080 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, null); 3081 mFocusedView = null; 3082 mOldFocusedView = null; 3083 return true; 3084 } 3085 } 3086 } 3087 } 3088 return false; 3089 } 3090 3091 private void deliverInputEvent(QueuedInputEvent q) { 3092 if (ViewDebug.DEBUG_LATENCY) { 3093 q.mDeliverTimeNanos = System.nanoTime(); 3094 } 3095 3096 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent"); 3097 try { 3098 if (q.mEvent instanceof KeyEvent) { 3099 deliverKeyEvent(q); 3100 } else { 3101 final int source = q.mEvent.getSource(); 3102 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3103 deliverPointerEvent(q); 3104 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3105 deliverTrackballEvent(q); 3106 } else { 3107 deliverGenericMotionEvent(q); 3108 } 3109 } 3110 } finally { 3111 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 3112 } 3113 } 3114 3115 private void deliverPointerEvent(QueuedInputEvent q) { 3116 final MotionEvent event = (MotionEvent)q.mEvent; 3117 final boolean isTouchEvent = event.isTouchEvent(); 3118 if (mInputEventConsistencyVerifier != null) { 3119 if (isTouchEvent) { 3120 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 3121 } else { 3122 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3123 } 3124 } 3125 3126 // If there is no view, then the event will not be handled. 3127 if (mView == null || !mAdded) { 3128 finishInputEvent(q, false); 3129 return; 3130 } 3131 3132 // Translate the pointer event for compatibility, if needed. 3133 if (mTranslator != null) { 3134 mTranslator.translateEventInScreenToAppWindow(event); 3135 } 3136 3137 // Enter touch mode on down or scroll. 3138 final int action = event.getAction(); 3139 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3140 ensureTouchMode(true); 3141 } 3142 3143 // Offset the scroll position. 3144 if (mCurScrollY != 0) { 3145 event.offsetLocation(0, mCurScrollY); 3146 } 3147 if (MEASURE_LATENCY) { 3148 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano()); 3149 } 3150 3151 // Remember the touch position for possible drag-initiation. 3152 if (isTouchEvent) { 3153 mLastTouchPoint.x = event.getRawX(); 3154 mLastTouchPoint.y = event.getRawY(); 3155 } 3156 3157 // Dispatch touch to view hierarchy. 3158 boolean handled = mView.dispatchPointerEvent(event); 3159 if (MEASURE_LATENCY) { 3160 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano()); 3161 } 3162 if (handled) { 3163 finishInputEvent(q, true); 3164 return; 3165 } 3166 3167 // Pointer event was unhandled. 3168 finishInputEvent(q, false); 3169 } 3170 3171 private void deliverTrackballEvent(QueuedInputEvent q) { 3172 final MotionEvent event = (MotionEvent)q.mEvent; 3173 if (mInputEventConsistencyVerifier != null) { 3174 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 3175 } 3176 3177 // If there is no view, then the event will not be handled. 3178 if (mView == null || !mAdded) { 3179 finishInputEvent(q, false); 3180 return; 3181 } 3182 3183 // Deliver the trackball event to the view. 3184 if (mView.dispatchTrackballEvent(event)) { 3185 // If we reach this, we delivered a trackball event to mView and 3186 // mView consumed it. Because we will not translate the trackball 3187 // event into a key event, touch mode will not exit, so we exit 3188 // touch mode here. 3189 ensureTouchMode(false); 3190 3191 finishInputEvent(q, true); 3192 mLastTrackballTime = Integer.MIN_VALUE; 3193 return; 3194 } 3195 3196 // Translate the trackball event into DPAD keys and try to deliver those. 3197 final TrackballAxis x = mTrackballAxisX; 3198 final TrackballAxis y = mTrackballAxisY; 3199 3200 long curTime = SystemClock.uptimeMillis(); 3201 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) { 3202 // It has been too long since the last movement, 3203 // so restart at the beginning. 3204 x.reset(0); 3205 y.reset(0); 3206 mLastTrackballTime = curTime; 3207 } 3208 3209 final int action = event.getAction(); 3210 final int metaState = event.getMetaState(); 3211 switch (action) { 3212 case MotionEvent.ACTION_DOWN: 3213 x.reset(2); 3214 y.reset(2); 3215 enqueueInputEvent(new KeyEvent(curTime, curTime, 3216 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3217 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3218 InputDevice.SOURCE_KEYBOARD)); 3219 break; 3220 case MotionEvent.ACTION_UP: 3221 x.reset(2); 3222 y.reset(2); 3223 enqueueInputEvent(new KeyEvent(curTime, curTime, 3224 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3225 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3226 InputDevice.SOURCE_KEYBOARD)); 3227 break; 3228 } 3229 3230 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step=" 3231 + x.step + " dir=" + x.dir + " acc=" + x.acceleration 3232 + " move=" + event.getX() 3233 + " / Y=" + y.position + " step=" 3234 + y.step + " dir=" + y.dir + " acc=" + y.acceleration 3235 + " move=" + event.getY()); 3236 final float xOff = x.collect(event.getX(), event.getEventTime(), "X"); 3237 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y"); 3238 3239 // Generate DPAD events based on the trackball movement. 3240 // We pick the axis that has moved the most as the direction of 3241 // the DPAD. When we generate DPAD events for one axis, then the 3242 // other axis is reset -- we don't want to perform DPAD jumps due 3243 // to slight movements in the trackball when making major movements 3244 // along the other axis. 3245 int keycode = 0; 3246 int movement = 0; 3247 float accel = 1; 3248 if (xOff > yOff) { 3249 movement = x.generate((2/event.getXPrecision())); 3250 if (movement != 0) { 3251 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3252 : KeyEvent.KEYCODE_DPAD_LEFT; 3253 accel = x.acceleration; 3254 y.reset(2); 3255 } 3256 } else if (yOff > 0) { 3257 movement = y.generate((2/event.getYPrecision())); 3258 if (movement != 0) { 3259 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3260 : KeyEvent.KEYCODE_DPAD_UP; 3261 accel = y.acceleration; 3262 x.reset(2); 3263 } 3264 } 3265 3266 if (keycode != 0) { 3267 if (movement < 0) movement = -movement; 3268 int accelMovement = (int)(movement * accel); 3269 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 3270 + " accelMovement=" + accelMovement 3271 + " accel=" + accel); 3272 if (accelMovement > movement) { 3273 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3274 + keycode); 3275 movement--; 3276 int repeatCount = accelMovement - movement; 3277 enqueueInputEvent(new KeyEvent(curTime, curTime, 3278 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 3279 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3280 InputDevice.SOURCE_KEYBOARD)); 3281 } 3282 while (movement > 0) { 3283 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3284 + keycode); 3285 movement--; 3286 curTime = SystemClock.uptimeMillis(); 3287 enqueueInputEvent(new KeyEvent(curTime, curTime, 3288 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 3289 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3290 InputDevice.SOURCE_KEYBOARD)); 3291 enqueueInputEvent(new KeyEvent(curTime, curTime, 3292 KeyEvent.ACTION_UP, keycode, 0, metaState, 3293 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3294 InputDevice.SOURCE_KEYBOARD)); 3295 } 3296 mLastTrackballTime = curTime; 3297 } 3298 3299 // Unfortunately we can't tell whether the application consumed the keys, so 3300 // we always consider the trackball event handled. 3301 finishInputEvent(q, true); 3302 } 3303 3304 private void deliverGenericMotionEvent(QueuedInputEvent q) { 3305 final MotionEvent event = (MotionEvent)q.mEvent; 3306 if (mInputEventConsistencyVerifier != null) { 3307 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3308 } 3309 3310 final int source = event.getSource(); 3311 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0; 3312 3313 // If there is no view, then the event will not be handled. 3314 if (mView == null || !mAdded) { 3315 if (isJoystick) { 3316 updateJoystickDirection(event, false); 3317 } 3318 finishInputEvent(q, false); 3319 return; 3320 } 3321 3322 // Deliver the event to the view. 3323 if (mView.dispatchGenericMotionEvent(event)) { 3324 if (isJoystick) { 3325 updateJoystickDirection(event, false); 3326 } 3327 finishInputEvent(q, true); 3328 return; 3329 } 3330 3331 if (isJoystick) { 3332 // Translate the joystick event into DPAD keys and try to deliver those. 3333 updateJoystickDirection(event, true); 3334 finishInputEvent(q, true); 3335 } else { 3336 finishInputEvent(q, false); 3337 } 3338 } 3339 3340 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) { 3341 final long time = event.getEventTime(); 3342 final int metaState = event.getMetaState(); 3343 final int deviceId = event.getDeviceId(); 3344 final int source = event.getSource(); 3345 3346 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X)); 3347 if (xDirection == 0) { 3348 xDirection = joystickAxisValueToDirection(event.getX()); 3349 } 3350 3351 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 3352 if (yDirection == 0) { 3353 yDirection = joystickAxisValueToDirection(event.getY()); 3354 } 3355 3356 if (xDirection != mLastJoystickXDirection) { 3357 if (mLastJoystickXKeyCode != 0) { 3358 enqueueInputEvent(new KeyEvent(time, time, 3359 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState, 3360 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3361 mLastJoystickXKeyCode = 0; 3362 } 3363 3364 mLastJoystickXDirection = xDirection; 3365 3366 if (xDirection != 0 && synthesizeNewKeys) { 3367 mLastJoystickXKeyCode = xDirection > 0 3368 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 3369 enqueueInputEvent(new KeyEvent(time, time, 3370 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState, 3371 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3372 } 3373 } 3374 3375 if (yDirection != mLastJoystickYDirection) { 3376 if (mLastJoystickYKeyCode != 0) { 3377 enqueueInputEvent(new KeyEvent(time, time, 3378 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState, 3379 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3380 mLastJoystickYKeyCode = 0; 3381 } 3382 3383 mLastJoystickYDirection = yDirection; 3384 3385 if (yDirection != 0 && synthesizeNewKeys) { 3386 mLastJoystickYKeyCode = yDirection > 0 3387 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 3388 enqueueInputEvent(new KeyEvent(time, time, 3389 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState, 3390 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3391 } 3392 } 3393 } 3394 3395 private static int joystickAxisValueToDirection(float value) { 3396 if (value >= 0.5f) { 3397 return 1; 3398 } else if (value <= -0.5f) { 3399 return -1; 3400 } else { 3401 return 0; 3402 } 3403 } 3404 3405 /** 3406 * Returns true if the key is used for keyboard navigation. 3407 * @param keyEvent The key event. 3408 * @return True if the key is used for keyboard navigation. 3409 */ 3410 private static boolean isNavigationKey(KeyEvent keyEvent) { 3411 switch (keyEvent.getKeyCode()) { 3412 case KeyEvent.KEYCODE_DPAD_LEFT: 3413 case KeyEvent.KEYCODE_DPAD_RIGHT: 3414 case KeyEvent.KEYCODE_DPAD_UP: 3415 case KeyEvent.KEYCODE_DPAD_DOWN: 3416 case KeyEvent.KEYCODE_DPAD_CENTER: 3417 case KeyEvent.KEYCODE_PAGE_UP: 3418 case KeyEvent.KEYCODE_PAGE_DOWN: 3419 case KeyEvent.KEYCODE_MOVE_HOME: 3420 case KeyEvent.KEYCODE_MOVE_END: 3421 case KeyEvent.KEYCODE_TAB: 3422 case KeyEvent.KEYCODE_SPACE: 3423 case KeyEvent.KEYCODE_ENTER: 3424 return true; 3425 } 3426 return false; 3427 } 3428 3429 /** 3430 * Returns true if the key is used for typing. 3431 * @param keyEvent The key event. 3432 * @return True if the key is used for typing. 3433 */ 3434 private static boolean isTypingKey(KeyEvent keyEvent) { 3435 return keyEvent.getUnicodeChar() > 0; 3436 } 3437 3438 /** 3439 * See if the key event means we should leave touch mode (and leave touch mode if so). 3440 * @param event The key event. 3441 * @return Whether this key event should be consumed (meaning the act of 3442 * leaving touch mode alone is considered the event). 3443 */ 3444 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 3445 // Only relevant in touch mode. 3446 if (!mAttachInfo.mInTouchMode) { 3447 return false; 3448 } 3449 3450 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 3451 final int action = event.getAction(); 3452 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 3453 return false; 3454 } 3455 3456 // Don't leave touch mode if the IME told us not to. 3457 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 3458 return false; 3459 } 3460 3461 // If the key can be used for keyboard navigation then leave touch mode 3462 // and select a focused view if needed (in ensureTouchMode). 3463 // When a new focused view is selected, we consume the navigation key because 3464 // navigation doesn't make much sense unless a view already has focus so 3465 // the key's purpose is to set focus. 3466 if (isNavigationKey(event)) { 3467 return ensureTouchMode(false); 3468 } 3469 3470 // If the key can be used for typing then leave touch mode 3471 // and select a focused view if needed (in ensureTouchMode). 3472 // Always allow the view to process the typing key. 3473 if (isTypingKey(event)) { 3474 ensureTouchMode(false); 3475 return false; 3476 } 3477 3478 return false; 3479 } 3480 3481 private void deliverKeyEvent(QueuedInputEvent q) { 3482 final KeyEvent event = (KeyEvent)q.mEvent; 3483 if (mInputEventConsistencyVerifier != null) { 3484 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 3485 } 3486 3487 if ((q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3488 // If there is no view, then the event will not be handled. 3489 if (mView == null || !mAdded) { 3490 finishInputEvent(q, false); 3491 return; 3492 } 3493 3494 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView); 3495 3496 // Perform predispatching before the IME. 3497 if (mView.dispatchKeyEventPreIme(event)) { 3498 finishInputEvent(q, true); 3499 return; 3500 } 3501 3502 // Dispatch to the IME before propagating down the view hierarchy. 3503 // The IME will eventually call back into handleImeFinishedEvent. 3504 if (mLastWasImTarget) { 3505 InputMethodManager imm = InputMethodManager.peekInstance(); 3506 if (imm != null) { 3507 final int seq = event.getSequenceNumber(); 3508 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq=" 3509 + seq + " event=" + event); 3510 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback); 3511 return; 3512 } 3513 } 3514 } 3515 3516 // Not dispatching to IME, continue with post IME actions. 3517 deliverKeyEventPostIme(q); 3518 } 3519 3520 void handleImeFinishedEvent(int seq, boolean handled) { 3521 final QueuedInputEvent q = mCurrentInputEvent; 3522 if (q != null && q.mEvent.getSequenceNumber() == seq) { 3523 final KeyEvent event = (KeyEvent)q.mEvent; 3524 if (DEBUG_IMF) { 3525 Log.v(TAG, "IME finished event: seq=" + seq 3526 + " handled=" + handled + " event=" + event); 3527 } 3528 if (handled) { 3529 finishInputEvent(q, true); 3530 } else { 3531 deliverKeyEventPostIme(q); 3532 } 3533 } else { 3534 if (DEBUG_IMF) { 3535 Log.v(TAG, "IME finished event: seq=" + seq 3536 + " handled=" + handled + ", event not found!"); 3537 } 3538 } 3539 } 3540 3541 private void deliverKeyEventPostIme(QueuedInputEvent q) { 3542 final KeyEvent event = (KeyEvent)q.mEvent; 3543 if (ViewDebug.DEBUG_LATENCY) { 3544 q.mDeliverPostImeTimeNanos = System.nanoTime(); 3545 } 3546 3547 // If the view went away, then the event will not be handled. 3548 if (mView == null || !mAdded) { 3549 finishInputEvent(q, false); 3550 return; 3551 } 3552 3553 // If the key's purpose is to exit touch mode then we consume it and consider it handled. 3554 if (checkForLeavingTouchModeAndConsume(event)) { 3555 finishInputEvent(q, true); 3556 return; 3557 } 3558 3559 // Make sure the fallback event policy sees all keys that will be delivered to the 3560 // view hierarchy. 3561 mFallbackEventHandler.preDispatchKeyEvent(event); 3562 3563 // Deliver the key to the view hierarchy. 3564 if (mView.dispatchKeyEvent(event)) { 3565 finishInputEvent(q, true); 3566 return; 3567 } 3568 3569 // If the Control modifier is held, try to interpret the key as a shortcut. 3570 if (event.getAction() == KeyEvent.ACTION_DOWN 3571 && event.isCtrlPressed() 3572 && event.getRepeatCount() == 0 3573 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3574 if (mView.dispatchKeyShortcutEvent(event)) { 3575 finishInputEvent(q, true); 3576 return; 3577 } 3578 } 3579 3580 // Apply the fallback event policy. 3581 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3582 finishInputEvent(q, true); 3583 return; 3584 } 3585 3586 // Handle automatic focus changes. 3587 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3588 int direction = 0; 3589 switch (event.getKeyCode()) { 3590 case KeyEvent.KEYCODE_DPAD_LEFT: 3591 if (event.hasNoModifiers()) { 3592 direction = View.FOCUS_LEFT; 3593 } 3594 break; 3595 case KeyEvent.KEYCODE_DPAD_RIGHT: 3596 if (event.hasNoModifiers()) { 3597 direction = View.FOCUS_RIGHT; 3598 } 3599 break; 3600 case KeyEvent.KEYCODE_DPAD_UP: 3601 if (event.hasNoModifiers()) { 3602 direction = View.FOCUS_UP; 3603 } 3604 break; 3605 case KeyEvent.KEYCODE_DPAD_DOWN: 3606 if (event.hasNoModifiers()) { 3607 direction = View.FOCUS_DOWN; 3608 } 3609 break; 3610 case KeyEvent.KEYCODE_TAB: 3611 if (event.hasNoModifiers()) { 3612 direction = View.FOCUS_FORWARD; 3613 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3614 direction = View.FOCUS_BACKWARD; 3615 } 3616 break; 3617 } 3618 if (direction != 0) { 3619 View focused = mView.findFocus(); 3620 if (focused != null) { 3621 View v = focused.focusSearch(direction); 3622 if (v != null && v != focused) { 3623 // do the math the get the interesting rect 3624 // of previous focused into the coord system of 3625 // newly focused view 3626 focused.getFocusedRect(mTempRect); 3627 if (mView instanceof ViewGroup) { 3628 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3629 focused, mTempRect); 3630 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3631 v, mTempRect); 3632 } 3633 if (v.requestFocus(direction, mTempRect)) { 3634 playSoundEffect(SoundEffectConstants 3635 .getContantForFocusDirection(direction)); 3636 finishInputEvent(q, true); 3637 return; 3638 } 3639 } 3640 3641 // Give the focused view a last chance to handle the dpad key. 3642 if (mView.dispatchUnhandledMove(focused, direction)) { 3643 finishInputEvent(q, true); 3644 return; 3645 } 3646 } 3647 } 3648 } 3649 3650 // Key was unhandled. 3651 finishInputEvent(q, false); 3652 } 3653 3654 /* drag/drop */ 3655 void setLocalDragState(Object obj) { 3656 mLocalDragState = obj; 3657 } 3658 3659 private void handleDragEvent(DragEvent event) { 3660 // From the root, only drag start/end/location are dispatched. entered/exited 3661 // are determined and dispatched by the viewgroup hierarchy, who then report 3662 // that back here for ultimate reporting back to the framework. 3663 if (mView != null && mAdded) { 3664 final int what = event.mAction; 3665 3666 if (what == DragEvent.ACTION_DRAG_EXITED) { 3667 // A direct EXITED event means that the window manager knows we've just crossed 3668 // a window boundary, so the current drag target within this one must have 3669 // just been exited. Send it the usual notifications and then we're done 3670 // for now. 3671 mView.dispatchDragEvent(event); 3672 } else { 3673 // Cache the drag description when the operation starts, then fill it in 3674 // on subsequent calls as a convenience 3675 if (what == DragEvent.ACTION_DRAG_STARTED) { 3676 mCurrentDragView = null; // Start the current-recipient tracking 3677 mDragDescription = event.mClipDescription; 3678 } else { 3679 event.mClipDescription = mDragDescription; 3680 } 3681 3682 // For events with a [screen] location, translate into window coordinates 3683 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 3684 mDragPoint.set(event.mX, event.mY); 3685 if (mTranslator != null) { 3686 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 3687 } 3688 3689 if (mCurScrollY != 0) { 3690 mDragPoint.offset(0, mCurScrollY); 3691 } 3692 3693 event.mX = mDragPoint.x; 3694 event.mY = mDragPoint.y; 3695 } 3696 3697 // Remember who the current drag target is pre-dispatch 3698 final View prevDragView = mCurrentDragView; 3699 3700 // Now dispatch the drag/drop event 3701 boolean result = mView.dispatchDragEvent(event); 3702 3703 // If we changed apparent drag target, tell the OS about it 3704 if (prevDragView != mCurrentDragView) { 3705 try { 3706 if (prevDragView != null) { 3707 sWindowSession.dragRecipientExited(mWindow); 3708 } 3709 if (mCurrentDragView != null) { 3710 sWindowSession.dragRecipientEntered(mWindow); 3711 } 3712 } catch (RemoteException e) { 3713 Slog.e(TAG, "Unable to note drag target change"); 3714 } 3715 } 3716 3717 // Report the drop result when we're done 3718 if (what == DragEvent.ACTION_DROP) { 3719 mDragDescription = null; 3720 try { 3721 Log.i(TAG, "Reporting drop result: " + result); 3722 sWindowSession.reportDropResult(mWindow, result); 3723 } catch (RemoteException e) { 3724 Log.e(TAG, "Unable to report drop result"); 3725 } 3726 } 3727 3728 // When the drag operation ends, release any local state object 3729 // that may have been in use 3730 if (what == DragEvent.ACTION_DRAG_ENDED) { 3731 setLocalDragState(null); 3732 } 3733 } 3734 } 3735 event.recycle(); 3736 } 3737 3738 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 3739 if (mSeq != args.seq) { 3740 // The sequence has changed, so we need to update our value and make 3741 // sure to do a traversal afterward so the window manager is given our 3742 // most recent data. 3743 mSeq = args.seq; 3744 mAttachInfo.mForceReportNewAttributes = true; 3745 scheduleTraversals(); 3746 } 3747 if (mView == null) return; 3748 if (args.localChanges != 0) { 3749 if (mAttachInfo != null) { 3750 mAttachInfo.mRecomputeGlobalAttributes = true; 3751 } 3752 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 3753 scheduleTraversals(); 3754 } 3755 mView.dispatchSystemUiVisibilityChanged(args.globalVisibility); 3756 } 3757 3758 public void getLastTouchPoint(Point outLocation) { 3759 outLocation.x = (int) mLastTouchPoint.x; 3760 outLocation.y = (int) mLastTouchPoint.y; 3761 } 3762 3763 public void setDragFocus(View newDragTarget) { 3764 if (mCurrentDragView != newDragTarget) { 3765 mCurrentDragView = newDragTarget; 3766 } 3767 } 3768 3769 private AudioManager getAudioManager() { 3770 if (mView == null) { 3771 throw new IllegalStateException("getAudioManager called when there is no mView"); 3772 } 3773 if (mAudioManager == null) { 3774 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 3775 } 3776 return mAudioManager; 3777 } 3778 3779 public AccessibilityInteractionController getAccessibilityInteractionController() { 3780 if (mView == null) { 3781 throw new IllegalStateException("getAccessibilityInteractionController" 3782 + " called when there is no mView"); 3783 } 3784 if (mAccessibilityInteractionController == null) { 3785 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 3786 } 3787 return mAccessibilityInteractionController; 3788 } 3789 3790 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 3791 boolean insetsPending) throws RemoteException { 3792 3793 float appScale = mAttachInfo.mApplicationScale; 3794 boolean restore = false; 3795 if (params != null && mTranslator != null) { 3796 restore = true; 3797 params.backup(); 3798 mTranslator.translateWindowLayout(params); 3799 } 3800 if (params != null) { 3801 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 3802 } 3803 mPendingConfiguration.seq = 0; 3804 //Log.d(TAG, ">>>>>> CALLING relayout"); 3805 if (params != null && mOrigWindowType != params.type) { 3806 // For compatibility with old apps, don't crash here. 3807 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 3808 Slog.w(TAG, "Window type can not be changed after " 3809 + "the window is added; ignoring change of " + mView); 3810 params.type = mOrigWindowType; 3811 } 3812 } 3813 int relayoutResult = sWindowSession.relayout( 3814 mWindow, mSeq, params, 3815 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 3816 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 3817 viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0, 3818 mWinFrame, mPendingContentInsets, mPendingVisibleInsets, 3819 mPendingConfiguration, mSurface); 3820 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 3821 if (restore) { 3822 params.restore(); 3823 } 3824 3825 if (mTranslator != null) { 3826 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 3827 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 3828 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 3829 } 3830 return relayoutResult; 3831 } 3832 3833 /** 3834 * {@inheritDoc} 3835 */ 3836 public void playSoundEffect(int effectId) { 3837 checkThread(); 3838 3839 try { 3840 final AudioManager audioManager = getAudioManager(); 3841 3842 switch (effectId) { 3843 case SoundEffectConstants.CLICK: 3844 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 3845 return; 3846 case SoundEffectConstants.NAVIGATION_DOWN: 3847 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 3848 return; 3849 case SoundEffectConstants.NAVIGATION_LEFT: 3850 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 3851 return; 3852 case SoundEffectConstants.NAVIGATION_RIGHT: 3853 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 3854 return; 3855 case SoundEffectConstants.NAVIGATION_UP: 3856 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 3857 return; 3858 default: 3859 throw new IllegalArgumentException("unknown effect id " + effectId + 3860 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 3861 } 3862 } catch (IllegalStateException e) { 3863 // Exception thrown by getAudioManager() when mView is null 3864 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 3865 e.printStackTrace(); 3866 } 3867 } 3868 3869 /** 3870 * {@inheritDoc} 3871 */ 3872 public boolean performHapticFeedback(int effectId, boolean always) { 3873 try { 3874 return sWindowSession.performHapticFeedback(mWindow, effectId, always); 3875 } catch (RemoteException e) { 3876 return false; 3877 } 3878 } 3879 3880 /** 3881 * {@inheritDoc} 3882 */ 3883 public View focusSearch(View focused, int direction) { 3884 checkThread(); 3885 if (!(mView instanceof ViewGroup)) { 3886 return null; 3887 } 3888 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 3889 } 3890 3891 public void debug() { 3892 mView.debug(); 3893 } 3894 3895 public void dumpGfxInfo(int[] info) { 3896 if (mView != null) { 3897 getGfxInfo(mView, info); 3898 } else { 3899 info[0] = info[1] = 0; 3900 } 3901 } 3902 3903 private static void getGfxInfo(View view, int[] info) { 3904 DisplayList displayList = view.mDisplayList; 3905 info[0]++; 3906 if (displayList != null) { 3907 info[1] += displayList.getSize(); 3908 } 3909 3910 if (view instanceof ViewGroup) { 3911 ViewGroup group = (ViewGroup) view; 3912 3913 int count = group.getChildCount(); 3914 for (int i = 0; i < count; i++) { 3915 getGfxInfo(group.getChildAt(i), info); 3916 } 3917 } 3918 } 3919 3920 public void die(boolean immediate) { 3921 if (immediate) { 3922 doDie(); 3923 } else { 3924 destroyHardwareRenderer(); 3925 mHandler.sendEmptyMessage(MSG_DIE); 3926 } 3927 } 3928 3929 void doDie() { 3930 checkThread(); 3931 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 3932 synchronized (this) { 3933 if (mAdded) { 3934 dispatchDetachedFromWindow(); 3935 } 3936 3937 if (mAdded && !mFirst) { 3938 destroyHardwareRenderer(); 3939 3940 if (mView != null) { 3941 int viewVisibility = mView.getVisibility(); 3942 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 3943 if (mWindowAttributesChanged || viewVisibilityChanged) { 3944 // If layout params have been changed, first give them 3945 // to the window manager to make sure it has the correct 3946 // animation info. 3947 try { 3948 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 3949 & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) { 3950 sWindowSession.finishDrawing(mWindow); 3951 } 3952 } catch (RemoteException e) { 3953 } 3954 } 3955 3956 mSurface.release(); 3957 } 3958 } 3959 3960 mAdded = false; 3961 } 3962 } 3963 3964 public void requestUpdateConfiguration(Configuration config) { 3965 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 3966 mHandler.sendMessage(msg); 3967 } 3968 3969 private void destroyHardwareRenderer() { 3970 AttachInfo attachInfo = mAttachInfo; 3971 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 3972 3973 if (hardwareRenderer != null) { 3974 if (mView != null) { 3975 hardwareRenderer.destroyHardwareResources(mView); 3976 } 3977 hardwareRenderer.destroy(true); 3978 hardwareRenderer.setRequested(false); 3979 3980 attachInfo.mHardwareRenderer = null; 3981 attachInfo.mHardwareAccelerated = false; 3982 } 3983 } 3984 3985 void dispatchImeFinishedEvent(int seq, boolean handled) { 3986 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT); 3987 msg.arg1 = seq; 3988 msg.arg2 = handled ? 1 : 0; 3989 msg.setAsynchronous(true); 3990 mHandler.sendMessage(msg); 3991 } 3992 3993 public void dispatchFinishInputConnection(InputConnection connection) { 3994 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 3995 mHandler.sendMessage(msg); 3996 } 3997 3998 public void dispatchResized(int w, int h, Rect coveredInsets, 3999 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4000 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w 4001 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString() 4002 + " visibleInsets=" + visibleInsets.toShortString() 4003 + " reportDraw=" + reportDraw); 4004 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED); 4005 if (mTranslator != null) { 4006 mTranslator.translateRectInScreenToAppWindow(coveredInsets); 4007 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 4008 w *= mTranslator.applicationInvertedScale; 4009 h *= mTranslator.applicationInvertedScale; 4010 } 4011 msg.arg1 = w; 4012 msg.arg2 = h; 4013 ResizedInfo ri = new ResizedInfo(); 4014 ri.coveredInsets = new Rect(coveredInsets); 4015 ri.visibleInsets = new Rect(visibleInsets); 4016 ri.newConfig = newConfig; 4017 msg.obj = ri; 4018 mHandler.sendMessage(msg); 4019 } 4020 4021 /** 4022 * Represents a pending input event that is waiting in a queue. 4023 * 4024 * Input events are processed in serial order by the timestamp specified by 4025 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 4026 * one input event to the application at a time and waits for the application 4027 * to finish handling it before delivering the next one. 4028 * 4029 * However, because the application or IME can synthesize and inject multiple 4030 * key events at a time without going through the input dispatcher, we end up 4031 * needing a queue on the application's side. 4032 */ 4033 private static final class QueuedInputEvent { 4034 public static final int FLAG_DELIVER_POST_IME = 1; 4035 4036 public QueuedInputEvent mNext; 4037 4038 public InputEvent mEvent; 4039 public InputEventReceiver mReceiver; 4040 public int mFlags; 4041 4042 // Used for latency calculations. 4043 public long mReceiveTimeNanos; 4044 public long mDeliverTimeNanos; 4045 public long mDeliverPostImeTimeNanos; 4046 } 4047 4048 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 4049 InputEventReceiver receiver, int flags) { 4050 QueuedInputEvent q = mQueuedInputEventPool; 4051 if (q != null) { 4052 mQueuedInputEventPoolSize -= 1; 4053 mQueuedInputEventPool = q.mNext; 4054 q.mNext = null; 4055 } else { 4056 q = new QueuedInputEvent(); 4057 } 4058 4059 q.mEvent = event; 4060 q.mReceiver = receiver; 4061 q.mFlags = flags; 4062 return q; 4063 } 4064 4065 private void recycleQueuedInputEvent(QueuedInputEvent q) { 4066 q.mEvent = null; 4067 q.mReceiver = null; 4068 4069 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 4070 mQueuedInputEventPoolSize += 1; 4071 q.mNext = mQueuedInputEventPool; 4072 mQueuedInputEventPool = q; 4073 } 4074 } 4075 4076 void enqueueInputEvent(InputEvent event) { 4077 enqueueInputEvent(event, null, 0, false); 4078 } 4079 4080 void enqueueInputEvent(InputEvent event, 4081 InputEventReceiver receiver, int flags, boolean processImmediately) { 4082 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 4083 4084 if (ViewDebug.DEBUG_LATENCY) { 4085 q.mReceiveTimeNanos = System.nanoTime(); 4086 q.mDeliverTimeNanos = 0; 4087 q.mDeliverPostImeTimeNanos = 0; 4088 } 4089 4090 // Always enqueue the input event in order, regardless of its time stamp. 4091 // We do this because the application or the IME may inject key events 4092 // in response to touch events and we want to ensure that the injected keys 4093 // are processed in the order they were received and we cannot trust that 4094 // the time stamp of injected events are monotonic. 4095 QueuedInputEvent last = mFirstPendingInputEvent; 4096 if (last == null) { 4097 mFirstPendingInputEvent = q; 4098 } else { 4099 while (last.mNext != null) { 4100 last = last.mNext; 4101 } 4102 last.mNext = q; 4103 } 4104 4105 if (processImmediately) { 4106 doProcessInputEvents(); 4107 } else { 4108 scheduleProcessInputEvents(); 4109 } 4110 } 4111 4112 private void scheduleProcessInputEvents() { 4113 if (!mProcessInputEventsScheduled) { 4114 mProcessInputEventsScheduled = true; 4115 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 4116 msg.setAsynchronous(true); 4117 mHandler.sendMessage(msg); 4118 } 4119 } 4120 4121 void doProcessInputEvents() { 4122 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 4123 QueuedInputEvent q = mFirstPendingInputEvent; 4124 mFirstPendingInputEvent = q.mNext; 4125 q.mNext = null; 4126 mCurrentInputEvent = q; 4127 deliverInputEvent(q); 4128 } 4129 4130 // We are done processing all input events that we can process right now 4131 // so we can clear the pending flag immediately. 4132 if (mProcessInputEventsScheduled) { 4133 mProcessInputEventsScheduled = false; 4134 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 4135 } 4136 } 4137 4138 private void finishInputEvent(QueuedInputEvent q, boolean handled) { 4139 if (q != mCurrentInputEvent) { 4140 throw new IllegalStateException("finished input event out of order"); 4141 } 4142 4143 if (ViewDebug.DEBUG_LATENCY) { 4144 final long now = System.nanoTime(); 4145 final long eventTime = q.mEvent.getEventTimeNano(); 4146 final StringBuilder msg = new StringBuilder(); 4147 msg.append("Spent "); 4148 msg.append((now - q.mReceiveTimeNanos) * 0.000001f); 4149 msg.append("ms processing "); 4150 if (q.mEvent instanceof KeyEvent) { 4151 final KeyEvent keyEvent = (KeyEvent)q.mEvent; 4152 msg.append("key event, action="); 4153 msg.append(KeyEvent.actionToString(keyEvent.getAction())); 4154 } else { 4155 final MotionEvent motionEvent = (MotionEvent)q.mEvent; 4156 msg.append("motion event, action="); 4157 msg.append(MotionEvent.actionToString(motionEvent.getAction())); 4158 msg.append(", historySize="); 4159 msg.append(motionEvent.getHistorySize()); 4160 } 4161 msg.append(", handled="); 4162 msg.append(handled); 4163 msg.append(", received at +"); 4164 msg.append((q.mReceiveTimeNanos - eventTime) * 0.000001f); 4165 if (q.mDeliverTimeNanos != 0) { 4166 msg.append("ms, delivered at +"); 4167 msg.append((q.mDeliverTimeNanos - eventTime) * 0.000001f); 4168 } 4169 if (q.mDeliverPostImeTimeNanos != 0) { 4170 msg.append("ms, delivered post IME at +"); 4171 msg.append((q.mDeliverPostImeTimeNanos - eventTime) * 0.000001f); 4172 } 4173 msg.append("ms, finished at +"); 4174 msg.append((now - eventTime) * 0.000001f); 4175 msg.append("ms."); 4176 Log.d(ViewDebug.DEBUG_LATENCY_TAG, msg.toString()); 4177 } 4178 4179 if (q.mReceiver != null) { 4180 q.mReceiver.finishInputEvent(q.mEvent, handled); 4181 } else { 4182 q.mEvent.recycleIfNeededAfterDispatch(); 4183 } 4184 4185 recycleQueuedInputEvent(q); 4186 4187 mCurrentInputEvent = null; 4188 if (mFirstPendingInputEvent != null) { 4189 scheduleProcessInputEvents(); 4190 } 4191 } 4192 4193 void scheduleConsumeBatchedInput() { 4194 if (!mConsumeBatchedInputScheduled) { 4195 mConsumeBatchedInputScheduled = true; 4196 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 4197 mConsumedBatchedInputRunnable, null); 4198 } 4199 } 4200 4201 void unscheduleConsumeBatchedInput() { 4202 if (mConsumeBatchedInputScheduled) { 4203 mConsumeBatchedInputScheduled = false; 4204 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4205 mConsumedBatchedInputRunnable, null); 4206 } 4207 } 4208 4209 void doConsumeBatchedInput(boolean callback) { 4210 if (mConsumeBatchedInputScheduled) { 4211 mConsumeBatchedInputScheduled = false; 4212 if (!callback) { 4213 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4214 mConsumedBatchedInputRunnable, null); 4215 } 4216 } 4217 4218 // Always consume batched input events even if not scheduled, because there 4219 // might be new input there waiting for us that we have no noticed yet because 4220 // the Looper has not had a chance to run again. 4221 if (mInputEventReceiver != null) { 4222 mInputEventReceiver.consumeBatchedInputEvents(); 4223 } 4224 } 4225 4226 final class TraversalRunnable implements Runnable { 4227 @Override 4228 public void run() { 4229 doTraversal(); 4230 } 4231 } 4232 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 4233 4234 final class WindowInputEventReceiver extends InputEventReceiver { 4235 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 4236 super(inputChannel, looper); 4237 } 4238 4239 @Override 4240 public void onInputEvent(InputEvent event) { 4241 enqueueInputEvent(event, this, 0, true); 4242 } 4243 4244 @Override 4245 public void onBatchedInputEventPending() { 4246 scheduleConsumeBatchedInput(); 4247 } 4248 4249 @Override 4250 public void dispose() { 4251 unscheduleConsumeBatchedInput(); 4252 super.dispose(); 4253 } 4254 } 4255 WindowInputEventReceiver mInputEventReceiver; 4256 4257 final class ConsumeBatchedInputRunnable implements Runnable { 4258 @Override 4259 public void run() { 4260 doConsumeBatchedInput(true); 4261 doProcessInputEvents(); 4262 } 4263 } 4264 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 4265 new ConsumeBatchedInputRunnable(); 4266 boolean mConsumeBatchedInputScheduled; 4267 4268 final class InvalidateOnAnimationRunnable implements Runnable { 4269 private boolean mPosted; 4270 private ArrayList<View> mViews = new ArrayList<View>(); 4271 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 4272 new ArrayList<AttachInfo.InvalidateInfo>(); 4273 private View[] mTempViews; 4274 private AttachInfo.InvalidateInfo[] mTempViewRects; 4275 4276 public void addView(View view) { 4277 synchronized (this) { 4278 mViews.add(view); 4279 postIfNeededLocked(); 4280 } 4281 } 4282 4283 public void addViewRect(AttachInfo.InvalidateInfo info) { 4284 synchronized (this) { 4285 mViewRects.add(info); 4286 postIfNeededLocked(); 4287 } 4288 } 4289 4290 public void removeView(View view) { 4291 synchronized (this) { 4292 mViews.remove(view); 4293 4294 for (int i = mViewRects.size(); i-- > 0; ) { 4295 AttachInfo.InvalidateInfo info = mViewRects.get(i); 4296 if (info.target == view) { 4297 mViewRects.remove(i); 4298 info.release(); 4299 } 4300 } 4301 4302 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 4303 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 4304 mPosted = false; 4305 } 4306 } 4307 } 4308 4309 @Override 4310 public void run() { 4311 final int viewCount; 4312 final int viewRectCount; 4313 synchronized (this) { 4314 mPosted = false; 4315 4316 viewCount = mViews.size(); 4317 if (viewCount != 0) { 4318 mTempViews = mViews.toArray(mTempViews != null 4319 ? mTempViews : new View[viewCount]); 4320 mViews.clear(); 4321 } 4322 4323 viewRectCount = mViewRects.size(); 4324 if (viewRectCount != 0) { 4325 mTempViewRects = mViewRects.toArray(mTempViewRects != null 4326 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 4327 mViewRects.clear(); 4328 } 4329 } 4330 4331 for (int i = 0; i < viewCount; i++) { 4332 mTempViews[i].invalidate(); 4333 } 4334 4335 for (int i = 0; i < viewRectCount; i++) { 4336 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 4337 info.target.invalidate(info.left, info.top, info.right, info.bottom); 4338 info.release(); 4339 } 4340 } 4341 4342 private void postIfNeededLocked() { 4343 if (!mPosted) { 4344 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 4345 mPosted = true; 4346 } 4347 } 4348 } 4349 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 4350 new InvalidateOnAnimationRunnable(); 4351 4352 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 4353 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 4354 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4355 } 4356 4357 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 4358 long delayMilliseconds) { 4359 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 4360 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4361 } 4362 4363 public void dispatchInvalidateOnAnimation(View view) { 4364 mInvalidateOnAnimationRunnable.addView(view); 4365 } 4366 4367 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 4368 mInvalidateOnAnimationRunnable.addViewRect(info); 4369 } 4370 4371 public void invalidateDisplayList(DisplayList displayList) { 4372 mDisplayLists.add(displayList); 4373 4374 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4375 Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST); 4376 mHandler.sendMessage(msg); 4377 } 4378 4379 public void cancelInvalidate(View view) { 4380 mHandler.removeMessages(MSG_INVALIDATE, view); 4381 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 4382 // them to the pool 4383 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 4384 mInvalidateOnAnimationRunnable.removeView(view); 4385 } 4386 4387 public void dispatchKey(KeyEvent event) { 4388 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 4389 msg.setAsynchronous(true); 4390 mHandler.sendMessage(msg); 4391 } 4392 4393 public void dispatchKeyFromIme(KeyEvent event) { 4394 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 4395 msg.setAsynchronous(true); 4396 mHandler.sendMessage(msg); 4397 } 4398 4399 public void dispatchUnhandledKey(KeyEvent event) { 4400 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 4401 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 4402 final int keyCode = event.getKeyCode(); 4403 final int metaState = event.getMetaState(); 4404 4405 KeyEvent fallbackEvent = null; 4406 synchronized (mFallbackAction) { 4407 // Check for fallback actions specified by the key character map. 4408 if (kcm.getFallbackAction(keyCode, metaState, mFallbackAction)) { 4409 int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 4410 fallbackEvent = KeyEvent.obtain( 4411 event.getDownTime(), event.getEventTime(), 4412 event.getAction(), mFallbackAction.keyCode, 4413 event.getRepeatCount(), mFallbackAction.metaState, 4414 event.getDeviceId(), event.getScanCode(), 4415 flags, event.getSource(), null); 4416 } 4417 } 4418 if (fallbackEvent != null) { 4419 dispatchKey(fallbackEvent); 4420 } 4421 } 4422 } 4423 4424 public void dispatchAppVisibility(boolean visible) { 4425 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 4426 msg.arg1 = visible ? 1 : 0; 4427 mHandler.sendMessage(msg); 4428 } 4429 4430 public void dispatchScreenStateChange(boolean on) { 4431 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 4432 msg.arg1 = on ? 1 : 0; 4433 mHandler.sendMessage(msg); 4434 } 4435 4436 public void dispatchGetNewSurface() { 4437 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 4438 mHandler.sendMessage(msg); 4439 } 4440 4441 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4442 Message msg = Message.obtain(); 4443 msg.what = MSG_WINDOW_FOCUS_CHANGED; 4444 msg.arg1 = hasFocus ? 1 : 0; 4445 msg.arg2 = inTouchMode ? 1 : 0; 4446 mHandler.sendMessage(msg); 4447 } 4448 4449 public void dispatchCloseSystemDialogs(String reason) { 4450 Message msg = Message.obtain(); 4451 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 4452 msg.obj = reason; 4453 mHandler.sendMessage(msg); 4454 } 4455 4456 public void dispatchDragEvent(DragEvent event) { 4457 final int what; 4458 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 4459 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 4460 mHandler.removeMessages(what); 4461 } else { 4462 what = MSG_DISPATCH_DRAG_EVENT; 4463 } 4464 Message msg = mHandler.obtainMessage(what, event); 4465 mHandler.sendMessage(msg); 4466 } 4467 4468 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4469 int localValue, int localChanges) { 4470 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 4471 args.seq = seq; 4472 args.globalVisibility = globalVisibility; 4473 args.localValue = localValue; 4474 args.localChanges = localChanges; 4475 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 4476 } 4477 4478 public void dispatchCheckFocus() { 4479 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 4480 // This will result in a call to checkFocus() below. 4481 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 4482 } 4483 } 4484 4485 /** 4486 * Post a callback to send a 4487 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4488 * This event is send at most once every 4489 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 4490 */ 4491 private void postSendWindowContentChangedCallback(View source) { 4492 if (mSendWindowContentChangedAccessibilityEvent == null) { 4493 mSendWindowContentChangedAccessibilityEvent = 4494 new SendWindowContentChangedAccessibilityEvent(); 4495 } 4496 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource; 4497 if (oldSource == null) { 4498 mSendWindowContentChangedAccessibilityEvent.mSource = source; 4499 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 4500 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 4501 } else { 4502 mSendWindowContentChangedAccessibilityEvent.mSource = 4503 getCommonPredecessor(oldSource, source); 4504 } 4505 } 4506 4507 /** 4508 * Remove a posted callback to send a 4509 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4510 */ 4511 private void removeSendWindowContentChangedCallback() { 4512 if (mSendWindowContentChangedAccessibilityEvent != null) { 4513 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 4514 } 4515 } 4516 4517 public boolean showContextMenuForChild(View originalView) { 4518 return false; 4519 } 4520 4521 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 4522 return null; 4523 } 4524 4525 public void createContextMenu(ContextMenu menu) { 4526 } 4527 4528 public void childDrawableStateChanged(View child) { 4529 } 4530 4531 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 4532 if (mView == null) { 4533 return false; 4534 } 4535 mAccessibilityManager.sendAccessibilityEvent(event); 4536 return true; 4537 } 4538 4539 @Override 4540 public void childAccessibilityStateChanged(View child) { 4541 postSendWindowContentChangedCallback(child); 4542 } 4543 4544 private View getCommonPredecessor(View first, View second) { 4545 if (mAttachInfo != null) { 4546 if (mTempHashSet == null) { 4547 mTempHashSet = new HashSet<View>(); 4548 } 4549 HashSet<View> seen = mTempHashSet; 4550 seen.clear(); 4551 View firstCurrent = first; 4552 while (firstCurrent != null) { 4553 seen.add(firstCurrent); 4554 ViewParent firstCurrentParent = firstCurrent.mParent; 4555 if (firstCurrentParent instanceof View) { 4556 firstCurrent = (View) firstCurrentParent; 4557 } else { 4558 firstCurrent = null; 4559 } 4560 } 4561 View secondCurrent = second; 4562 while (secondCurrent != null) { 4563 if (seen.contains(secondCurrent)) { 4564 seen.clear(); 4565 return secondCurrent; 4566 } 4567 ViewParent secondCurrentParent = secondCurrent.mParent; 4568 if (secondCurrentParent instanceof View) { 4569 secondCurrent = (View) secondCurrentParent; 4570 } else { 4571 secondCurrent = null; 4572 } 4573 } 4574 seen.clear(); 4575 } 4576 return null; 4577 } 4578 4579 void checkThread() { 4580 if (mThread != Thread.currentThread()) { 4581 throw new CalledFromWrongThreadException( 4582 "Only the original thread that created a view hierarchy can touch its views."); 4583 } 4584 } 4585 4586 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4587 // ViewAncestor never intercepts touch event, so this can be a no-op 4588 } 4589 4590 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 4591 boolean immediate) { 4592 return scrollToRectOrFocus(rectangle, immediate); 4593 } 4594 4595 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 4596 // Do nothing. 4597 } 4598 4599 class TakenSurfaceHolder extends BaseSurfaceHolder { 4600 @Override 4601 public boolean onAllowLockCanvas() { 4602 return mDrawingAllowed; 4603 } 4604 4605 @Override 4606 public void onRelayoutContainer() { 4607 // Not currently interesting -- from changing between fixed and layout size. 4608 } 4609 4610 public void setFormat(int format) { 4611 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4612 } 4613 4614 public void setType(int type) { 4615 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4616 } 4617 4618 @Override 4619 public void onUpdateSurface() { 4620 // We take care of format and type changes on our own. 4621 throw new IllegalStateException("Shouldn't be here"); 4622 } 4623 4624 public boolean isCreating() { 4625 return mIsCreating; 4626 } 4627 4628 @Override 4629 public void setFixedSize(int width, int height) { 4630 throw new UnsupportedOperationException( 4631 "Currently only support sizing from layout"); 4632 } 4633 4634 public void setKeepScreenOn(boolean screenOn) { 4635 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4636 } 4637 } 4638 4639 static class InputMethodCallback extends IInputMethodCallback.Stub { 4640 private WeakReference<ViewRootImpl> mViewAncestor; 4641 4642 public InputMethodCallback(ViewRootImpl viewAncestor) { 4643 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4644 } 4645 4646 public void finishedEvent(int seq, boolean handled) { 4647 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4648 if (viewAncestor != null) { 4649 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4650 } 4651 } 4652 4653 public void sessionCreated(IInputMethodSession session) { 4654 // Stub -- not for use in the client. 4655 } 4656 } 4657 4658 static class W extends IWindow.Stub { 4659 private final WeakReference<ViewRootImpl> mViewAncestor; 4660 4661 W(ViewRootImpl viewAncestor) { 4662 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4663 } 4664 4665 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets, 4666 boolean reportDraw, Configuration newConfig) { 4667 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4668 if (viewAncestor != null) { 4669 viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, 4670 newConfig); 4671 } 4672 } 4673 4674 public void dispatchAppVisibility(boolean visible) { 4675 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4676 if (viewAncestor != null) { 4677 viewAncestor.dispatchAppVisibility(visible); 4678 } 4679 } 4680 4681 public void dispatchScreenState(boolean on) { 4682 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4683 if (viewAncestor != null) { 4684 viewAncestor.dispatchScreenStateChange(on); 4685 } 4686 } 4687 4688 public void dispatchGetNewSurface() { 4689 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4690 if (viewAncestor != null) { 4691 viewAncestor.dispatchGetNewSurface(); 4692 } 4693 } 4694 4695 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4696 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4697 if (viewAncestor != null) { 4698 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4699 } 4700 } 4701 4702 private static int checkCallingPermission(String permission) { 4703 try { 4704 return ActivityManagerNative.getDefault().checkPermission( 4705 permission, Binder.getCallingPid(), Binder.getCallingUid()); 4706 } catch (RemoteException e) { 4707 return PackageManager.PERMISSION_DENIED; 4708 } 4709 } 4710 4711 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 4712 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4713 if (viewAncestor != null) { 4714 final View view = viewAncestor.mView; 4715 if (view != null) { 4716 if (checkCallingPermission(Manifest.permission.DUMP) != 4717 PackageManager.PERMISSION_GRANTED) { 4718 throw new SecurityException("Insufficient permissions to invoke" 4719 + " executeCommand() from pid=" + Binder.getCallingPid() 4720 + ", uid=" + Binder.getCallingUid()); 4721 } 4722 4723 OutputStream clientStream = null; 4724 try { 4725 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 4726 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 4727 } catch (IOException e) { 4728 e.printStackTrace(); 4729 } finally { 4730 if (clientStream != null) { 4731 try { 4732 clientStream.close(); 4733 } catch (IOException e) { 4734 e.printStackTrace(); 4735 } 4736 } 4737 } 4738 } 4739 } 4740 } 4741 4742 public void closeSystemDialogs(String reason) { 4743 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4744 if (viewAncestor != null) { 4745 viewAncestor.dispatchCloseSystemDialogs(reason); 4746 } 4747 } 4748 4749 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 4750 boolean sync) { 4751 if (sync) { 4752 try { 4753 sWindowSession.wallpaperOffsetsComplete(asBinder()); 4754 } catch (RemoteException e) { 4755 } 4756 } 4757 } 4758 4759 public void dispatchWallpaperCommand(String action, int x, int y, 4760 int z, Bundle extras, boolean sync) { 4761 if (sync) { 4762 try { 4763 sWindowSession.wallpaperCommandComplete(asBinder(), null); 4764 } catch (RemoteException e) { 4765 } 4766 } 4767 } 4768 4769 /* Drag/drop */ 4770 public void dispatchDragEvent(DragEvent event) { 4771 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4772 if (viewAncestor != null) { 4773 viewAncestor.dispatchDragEvent(event); 4774 } 4775 } 4776 4777 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4778 int localValue, int localChanges) { 4779 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4780 if (viewAncestor != null) { 4781 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 4782 localValue, localChanges); 4783 } 4784 } 4785 } 4786 4787 /** 4788 * Maintains state information for a single trackball axis, generating 4789 * discrete (DPAD) movements based on raw trackball motion. 4790 */ 4791 static final class TrackballAxis { 4792 /** 4793 * The maximum amount of acceleration we will apply. 4794 */ 4795 static final float MAX_ACCELERATION = 20; 4796 4797 /** 4798 * The maximum amount of time (in milliseconds) between events in order 4799 * for us to consider the user to be doing fast trackball movements, 4800 * and thus apply an acceleration. 4801 */ 4802 static final long FAST_MOVE_TIME = 150; 4803 4804 /** 4805 * Scaling factor to the time (in milliseconds) between events to how 4806 * much to multiple/divide the current acceleration. When movement 4807 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4808 * FAST_MOVE_TIME it divides it. 4809 */ 4810 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4811 4812 float position; 4813 float absPosition; 4814 float acceleration = 1; 4815 long lastMoveTime = 0; 4816 int step; 4817 int dir; 4818 int nonAccelMovement; 4819 4820 void reset(int _step) { 4821 position = 0; 4822 acceleration = 1; 4823 lastMoveTime = 0; 4824 step = _step; 4825 dir = 0; 4826 } 4827 4828 /** 4829 * Add trackball movement into the state. If the direction of movement 4830 * has been reversed, the state is reset before adding the 4831 * movement (so that you don't have to compensate for any previously 4832 * collected movement before see the result of the movement in the 4833 * new direction). 4834 * 4835 * @return Returns the absolute value of the amount of movement 4836 * collected so far. 4837 */ 4838 float collect(float off, long time, String axis) { 4839 long normTime; 4840 if (off > 0) { 4841 normTime = (long)(off * FAST_MOVE_TIME); 4842 if (dir < 0) { 4843 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4844 position = 0; 4845 step = 0; 4846 acceleration = 1; 4847 lastMoveTime = 0; 4848 } 4849 dir = 1; 4850 } else if (off < 0) { 4851 normTime = (long)((-off) * FAST_MOVE_TIME); 4852 if (dir > 0) { 4853 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4854 position = 0; 4855 step = 0; 4856 acceleration = 1; 4857 lastMoveTime = 0; 4858 } 4859 dir = -1; 4860 } else { 4861 normTime = 0; 4862 } 4863 4864 // The number of milliseconds between each movement that is 4865 // considered "normal" and will not result in any acceleration 4866 // or deceleration, scaled by the offset we have here. 4867 if (normTime > 0) { 4868 long delta = time - lastMoveTime; 4869 lastMoveTime = time; 4870 float acc = acceleration; 4871 if (delta < normTime) { 4872 // The user is scrolling rapidly, so increase acceleration. 4873 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4874 if (scale > 1) acc *= scale; 4875 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4876 + off + " normTime=" + normTime + " delta=" + delta 4877 + " scale=" + scale + " acc=" + acc); 4878 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4879 } else { 4880 // The user is scrolling slowly, so decrease acceleration. 4881 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4882 if (scale > 1) acc /= scale; 4883 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4884 + off + " normTime=" + normTime + " delta=" + delta 4885 + " scale=" + scale + " acc=" + acc); 4886 acceleration = acc > 1 ? acc : 1; 4887 } 4888 } 4889 position += off; 4890 return (absPosition = Math.abs(position)); 4891 } 4892 4893 /** 4894 * Generate the number of discrete movement events appropriate for 4895 * the currently collected trackball movement. 4896 * 4897 * @param precision The minimum movement required to generate the 4898 * first discrete movement. 4899 * 4900 * @return Returns the number of discrete movements, either positive 4901 * or negative, or 0 if there is not enough trackball movement yet 4902 * for a discrete movement. 4903 */ 4904 int generate(float precision) { 4905 int movement = 0; 4906 nonAccelMovement = 0; 4907 do { 4908 final int dir = position >= 0 ? 1 : -1; 4909 switch (step) { 4910 // If we are going to execute the first step, then we want 4911 // to do this as soon as possible instead of waiting for 4912 // a full movement, in order to make things look responsive. 4913 case 0: 4914 if (absPosition < precision) { 4915 return movement; 4916 } 4917 movement += dir; 4918 nonAccelMovement += dir; 4919 step = 1; 4920 break; 4921 // If we have generated the first movement, then we need 4922 // to wait for the second complete trackball motion before 4923 // generating the second discrete movement. 4924 case 1: 4925 if (absPosition < 2) { 4926 return movement; 4927 } 4928 movement += dir; 4929 nonAccelMovement += dir; 4930 position += dir > 0 ? -2 : 2; 4931 absPosition = Math.abs(position); 4932 step = 2; 4933 break; 4934 // After the first two, we generate discrete movements 4935 // consistently with the trackball, applying an acceleration 4936 // if the trackball is moving quickly. This is a simple 4937 // acceleration on top of what we already compute based 4938 // on how quickly the wheel is being turned, to apply 4939 // a longer increasing acceleration to continuous movement 4940 // in one direction. 4941 default: 4942 if (absPosition < 1) { 4943 return movement; 4944 } 4945 movement += dir; 4946 position += dir >= 0 ? -1 : 1; 4947 absPosition = Math.abs(position); 4948 float acc = acceleration; 4949 acc *= 1.1f; 4950 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4951 break; 4952 } 4953 } while (true); 4954 } 4955 } 4956 4957 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 4958 public CalledFromWrongThreadException(String msg) { 4959 super(msg); 4960 } 4961 } 4962 4963 private SurfaceHolder mHolder = new SurfaceHolder() { 4964 // we only need a SurfaceHolder for opengl. it would be nice 4965 // to implement everything else though, especially the callback 4966 // support (opengl doesn't make use of it right now, but eventually 4967 // will). 4968 public Surface getSurface() { 4969 return mSurface; 4970 } 4971 4972 public boolean isCreating() { 4973 return false; 4974 } 4975 4976 public void addCallback(Callback callback) { 4977 } 4978 4979 public void removeCallback(Callback callback) { 4980 } 4981 4982 public void setFixedSize(int width, int height) { 4983 } 4984 4985 public void setSizeFromLayout() { 4986 } 4987 4988 public void setFormat(int format) { 4989 } 4990 4991 public void setType(int type) { 4992 } 4993 4994 public void setKeepScreenOn(boolean screenOn) { 4995 } 4996 4997 public Canvas lockCanvas() { 4998 return null; 4999 } 5000 5001 public Canvas lockCanvas(Rect dirty) { 5002 return null; 5003 } 5004 5005 public void unlockCanvasAndPost(Canvas canvas) { 5006 } 5007 public Rect getSurfaceFrame() { 5008 return null; 5009 } 5010 }; 5011 5012 static RunQueue getRunQueue() { 5013 RunQueue rq = sRunQueues.get(); 5014 if (rq != null) { 5015 return rq; 5016 } 5017 rq = new RunQueue(); 5018 sRunQueues.set(rq); 5019 return rq; 5020 } 5021 5022 /** 5023 * The run queue is used to enqueue pending work from Views when no Handler is 5024 * attached. The work is executed during the next call to performTraversals on 5025 * the thread. 5026 * @hide 5027 */ 5028 static final class RunQueue { 5029 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 5030 5031 void post(Runnable action) { 5032 postDelayed(action, 0); 5033 } 5034 5035 void postDelayed(Runnable action, long delayMillis) { 5036 HandlerAction handlerAction = new HandlerAction(); 5037 handlerAction.action = action; 5038 handlerAction.delay = delayMillis; 5039 5040 synchronized (mActions) { 5041 mActions.add(handlerAction); 5042 } 5043 } 5044 5045 void removeCallbacks(Runnable action) { 5046 final HandlerAction handlerAction = new HandlerAction(); 5047 handlerAction.action = action; 5048 5049 synchronized (mActions) { 5050 final ArrayList<HandlerAction> actions = mActions; 5051 5052 while (actions.remove(handlerAction)) { 5053 // Keep going 5054 } 5055 } 5056 } 5057 5058 void executeActions(Handler handler) { 5059 synchronized (mActions) { 5060 final ArrayList<HandlerAction> actions = mActions; 5061 final int count = actions.size(); 5062 5063 for (int i = 0; i < count; i++) { 5064 final HandlerAction handlerAction = actions.get(i); 5065 handler.postDelayed(handlerAction.action, handlerAction.delay); 5066 } 5067 5068 actions.clear(); 5069 } 5070 } 5071 5072 private static class HandlerAction { 5073 Runnable action; 5074 long delay; 5075 5076 @Override 5077 public boolean equals(Object o) { 5078 if (this == o) return true; 5079 if (o == null || getClass() != o.getClass()) return false; 5080 5081 HandlerAction that = (HandlerAction) o; 5082 return !(action != null ? !action.equals(that.action) : that.action != null); 5083 5084 } 5085 5086 @Override 5087 public int hashCode() { 5088 int result = action != null ? action.hashCode() : 0; 5089 result = 31 * result + (int) (delay ^ (delay >>> 32)); 5090 return result; 5091 } 5092 } 5093 } 5094 5095 /** 5096 * Class for managing the accessibility interaction connection 5097 * based on the global accessibility state. 5098 */ 5099 final class AccessibilityInteractionConnectionManager 5100 implements AccessibilityStateChangeListener { 5101 public void onAccessibilityStateChanged(boolean enabled) { 5102 if (enabled) { 5103 ensureConnection(); 5104 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 5105 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 5106 View focusedView = mView.findFocus(); 5107 if (focusedView != null && focusedView != mView) { 5108 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5109 } 5110 } 5111 } else { 5112 ensureNoConnection(); 5113 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 5114 } 5115 } 5116 5117 public void ensureConnection() { 5118 if (mAttachInfo != null) { 5119 final boolean registered = 5120 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5121 if (!registered) { 5122 mAttachInfo.mAccessibilityWindowId = 5123 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 5124 new AccessibilityInteractionConnection(ViewRootImpl.this)); 5125 } 5126 } 5127 } 5128 5129 public void ensureNoConnection() { 5130 final boolean registered = 5131 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5132 if (registered) { 5133 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 5134 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 5135 } 5136 } 5137 } 5138 5139 /** 5140 * This class is an interface this ViewAncestor provides to the 5141 * AccessibilityManagerService to the latter can interact with 5142 * the view hierarchy in this ViewAncestor. 5143 */ 5144 static final class AccessibilityInteractionConnection 5145 extends IAccessibilityInteractionConnection.Stub { 5146 private final WeakReference<ViewRootImpl> mViewRootImpl; 5147 5148 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 5149 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 5150 } 5151 5152 @Override 5153 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 5154 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5155 int flags, int interrogatingPid, long interrogatingTid) { 5156 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5157 if (viewRootImpl != null && viewRootImpl.mView != null) { 5158 viewRootImpl.getAccessibilityInteractionController() 5159 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 5160 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5161 } else { 5162 // We cannot make the call and notify the caller so it does not wait. 5163 try { 5164 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5165 } catch (RemoteException re) { 5166 /* best effort - ignore */ 5167 } 5168 } 5169 } 5170 5171 @Override 5172 public void performAccessibilityAction(long accessibilityNodeId, int action, 5173 Bundle arguments, int interactionId, 5174 IAccessibilityInteractionConnectionCallback callback, int flags, 5175 int interogatingPid, long interrogatingTid) { 5176 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5177 if (viewRootImpl != null && viewRootImpl.mView != null) { 5178 viewRootImpl.getAccessibilityInteractionController() 5179 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 5180 interactionId, callback, flags, interogatingPid, interrogatingTid); 5181 } else { 5182 // We cannot make the call and notify the caller so it does not wait. 5183 try { 5184 callback.setPerformAccessibilityActionResult(false, interactionId); 5185 } catch (RemoteException re) { 5186 /* best effort - ignore */ 5187 } 5188 } 5189 } 5190 5191 @Override 5192 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId, 5193 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5194 int flags, int interrogatingPid, long interrogatingTid) { 5195 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5196 if (viewRootImpl != null && viewRootImpl.mView != null) { 5197 viewRootImpl.getAccessibilityInteractionController() 5198 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId, 5199 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5200 } else { 5201 // We cannot make the call and notify the caller so it does not wait. 5202 try { 5203 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5204 } catch (RemoteException re) { 5205 /* best effort - ignore */ 5206 } 5207 } 5208 } 5209 5210 @Override 5211 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 5212 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5213 int flags, int interrogatingPid, long interrogatingTid) { 5214 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5215 if (viewRootImpl != null && viewRootImpl.mView != null) { 5216 viewRootImpl.getAccessibilityInteractionController() 5217 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 5218 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5219 } else { 5220 // We cannot make the call and notify the caller so it does not wait. 5221 try { 5222 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5223 } catch (RemoteException re) { 5224 /* best effort - ignore */ 5225 } 5226 } 5227 } 5228 5229 @Override 5230 public void findFocus(long accessibilityNodeId, int interactionId, int focusType, 5231 IAccessibilityInteractionConnectionCallback callback, int flags, 5232 int interrogatingPid, long interrogatingTid) { 5233 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5234 if (viewRootImpl != null && viewRootImpl.mView != null) { 5235 viewRootImpl.getAccessibilityInteractionController() 5236 .findFocusClientThread(accessibilityNodeId, interactionId, focusType, 5237 callback, flags, interrogatingPid, interrogatingTid); 5238 } else { 5239 // We cannot make the call and notify the caller so it does not wait. 5240 try { 5241 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5242 } catch (RemoteException re) { 5243 /* best effort - ignore */ 5244 } 5245 } 5246 } 5247 5248 @Override 5249 public void focusSearch(long accessibilityNodeId, int interactionId, int direction, 5250 IAccessibilityInteractionConnectionCallback callback, int flags, 5251 int interrogatingPid, long interrogatingTid) { 5252 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5253 if (viewRootImpl != null && viewRootImpl.mView != null) { 5254 viewRootImpl.getAccessibilityInteractionController() 5255 .focusSearchClientThread(accessibilityNodeId, interactionId, direction, 5256 callback, flags, interrogatingPid, interrogatingTid); 5257 } else { 5258 // We cannot make the call and notify the caller so it does not wait. 5259 try { 5260 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5261 } catch (RemoteException re) { 5262 /* best effort - ignore */ 5263 } 5264 } 5265 } 5266 } 5267 5268 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 5269 public View mSource; 5270 5271 public void run() { 5272 if (mSource != null) { 5273 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 5274 mSource.resetAccessibilityStateChanged(); 5275 mSource = null; 5276 } 5277 } 5278 } 5279} 5280