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