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