ViewRootImpl.java revision cf67578c7f99492273a8f8446dd18ddc5af2ae76
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.findAccessibilityFocus(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 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 3799 } 3800 if (mAttachInfo != null) { 3801 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 3802 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 3803 mAttachInfo.mGlobalSystemUiVisibility = visibility; 3804 mView.dispatchSystemUiVisibilityChanged(visibility); 3805 } 3806 } 3807 } 3808 3809 public void handleDispatchDoneAnimating() { 3810 if (mWindowsAnimating) { 3811 mWindowsAnimating = false; 3812 if (!mDirty.isEmpty() || mIsAnimating) { 3813 scheduleTraversals(); 3814 } 3815 } 3816 } 3817 3818 public void getLastTouchPoint(Point outLocation) { 3819 outLocation.x = (int) mLastTouchPoint.x; 3820 outLocation.y = (int) mLastTouchPoint.y; 3821 } 3822 3823 public void setDragFocus(View newDragTarget) { 3824 if (mCurrentDragView != newDragTarget) { 3825 mCurrentDragView = newDragTarget; 3826 } 3827 } 3828 3829 private AudioManager getAudioManager() { 3830 if (mView == null) { 3831 throw new IllegalStateException("getAudioManager called when there is no mView"); 3832 } 3833 if (mAudioManager == null) { 3834 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 3835 } 3836 return mAudioManager; 3837 } 3838 3839 public AccessibilityInteractionController getAccessibilityInteractionController() { 3840 if (mView == null) { 3841 throw new IllegalStateException("getAccessibilityInteractionController" 3842 + " called when there is no mView"); 3843 } 3844 if (mAccessibilityInteractionController == null) { 3845 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 3846 } 3847 return mAccessibilityInteractionController; 3848 } 3849 3850 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 3851 boolean insetsPending) throws RemoteException { 3852 3853 float appScale = mAttachInfo.mApplicationScale; 3854 boolean restore = false; 3855 if (params != null && mTranslator != null) { 3856 restore = true; 3857 params.backup(); 3858 mTranslator.translateWindowLayout(params); 3859 } 3860 if (params != null) { 3861 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 3862 } 3863 mPendingConfiguration.seq = 0; 3864 //Log.d(TAG, ">>>>>> CALLING relayout"); 3865 if (params != null && mOrigWindowType != params.type) { 3866 // For compatibility with old apps, don't crash here. 3867 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 3868 Slog.w(TAG, "Window type can not be changed after " 3869 + "the window is added; ignoring change of " + mView); 3870 params.type = mOrigWindowType; 3871 } 3872 } 3873 int relayoutResult = sWindowSession.relayout( 3874 mWindow, mSeq, params, 3875 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 3876 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 3877 viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0, 3878 mWinFrame, mPendingSystemInsets, mPendingContentInsets, mPendingVisibleInsets, 3879 mPendingConfiguration, mSurface); 3880 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 3881 if (restore) { 3882 params.restore(); 3883 } 3884 3885 if (mTranslator != null) { 3886 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 3887 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 3888 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 3889 } 3890 return relayoutResult; 3891 } 3892 3893 /** 3894 * {@inheritDoc} 3895 */ 3896 public void playSoundEffect(int effectId) { 3897 checkThread(); 3898 3899 try { 3900 final AudioManager audioManager = getAudioManager(); 3901 3902 switch (effectId) { 3903 case SoundEffectConstants.CLICK: 3904 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 3905 return; 3906 case SoundEffectConstants.NAVIGATION_DOWN: 3907 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 3908 return; 3909 case SoundEffectConstants.NAVIGATION_LEFT: 3910 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 3911 return; 3912 case SoundEffectConstants.NAVIGATION_RIGHT: 3913 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 3914 return; 3915 case SoundEffectConstants.NAVIGATION_UP: 3916 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 3917 return; 3918 default: 3919 throw new IllegalArgumentException("unknown effect id " + effectId + 3920 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 3921 } 3922 } catch (IllegalStateException e) { 3923 // Exception thrown by getAudioManager() when mView is null 3924 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 3925 e.printStackTrace(); 3926 } 3927 } 3928 3929 /** 3930 * {@inheritDoc} 3931 */ 3932 public boolean performHapticFeedback(int effectId, boolean always) { 3933 try { 3934 return sWindowSession.performHapticFeedback(mWindow, effectId, always); 3935 } catch (RemoteException e) { 3936 return false; 3937 } 3938 } 3939 3940 /** 3941 * {@inheritDoc} 3942 */ 3943 public View focusSearch(View focused, int direction) { 3944 checkThread(); 3945 if (!(mView instanceof ViewGroup)) { 3946 return null; 3947 } 3948 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 3949 } 3950 3951 public void debug() { 3952 mView.debug(); 3953 } 3954 3955 public void dumpGfxInfo(int[] info) { 3956 if (mView != null) { 3957 getGfxInfo(mView, info); 3958 } else { 3959 info[0] = info[1] = 0; 3960 } 3961 } 3962 3963 private static void getGfxInfo(View view, int[] info) { 3964 DisplayList displayList = view.mDisplayList; 3965 info[0]++; 3966 if (displayList != null) { 3967 info[1] += displayList.getSize(); 3968 } 3969 3970 if (view instanceof ViewGroup) { 3971 ViewGroup group = (ViewGroup) view; 3972 3973 int count = group.getChildCount(); 3974 for (int i = 0; i < count; i++) { 3975 getGfxInfo(group.getChildAt(i), info); 3976 } 3977 } 3978 } 3979 3980 public void die(boolean immediate) { 3981 if (immediate) { 3982 doDie(); 3983 } else { 3984 if (!mIsDrawing) { 3985 destroyHardwareRenderer(); 3986 } else { 3987 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 3988 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 3989 } 3990 mHandler.sendEmptyMessage(MSG_DIE); 3991 } 3992 } 3993 3994 void doDie() { 3995 checkThread(); 3996 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 3997 synchronized (this) { 3998 if (mAdded) { 3999 dispatchDetachedFromWindow(); 4000 } 4001 4002 if (mAdded && !mFirst) { 4003 destroyHardwareRenderer(); 4004 4005 if (mView != null) { 4006 int viewVisibility = mView.getVisibility(); 4007 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 4008 if (mWindowAttributesChanged || viewVisibilityChanged) { 4009 // If layout params have been changed, first give them 4010 // to the window manager to make sure it has the correct 4011 // animation info. 4012 try { 4013 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 4014 & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) { 4015 sWindowSession.finishDrawing(mWindow); 4016 } 4017 } catch (RemoteException e) { 4018 } 4019 } 4020 4021 mSurface.release(); 4022 } 4023 } 4024 4025 mAdded = false; 4026 } 4027 } 4028 4029 public void requestUpdateConfiguration(Configuration config) { 4030 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 4031 mHandler.sendMessage(msg); 4032 } 4033 4034 public void loadSystemProperties() { 4035 boolean layout = SystemProperties.getBoolean( 4036 View.DEBUG_LAYOUT_PROPERTY, false); 4037 if (layout != mAttachInfo.mDebugLayout) { 4038 mAttachInfo.mDebugLayout = layout; 4039 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 4040 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 4041 } 4042 } 4043 } 4044 4045 private void destroyHardwareRenderer() { 4046 AttachInfo attachInfo = mAttachInfo; 4047 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 4048 4049 if (hardwareRenderer != null) { 4050 if (mView != null) { 4051 hardwareRenderer.destroyHardwareResources(mView); 4052 } 4053 hardwareRenderer.destroy(true); 4054 hardwareRenderer.setRequested(false); 4055 4056 attachInfo.mHardwareRenderer = null; 4057 attachInfo.mHardwareAccelerated = false; 4058 } 4059 } 4060 4061 void dispatchImeFinishedEvent(int seq, boolean handled) { 4062 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT); 4063 msg.arg1 = seq; 4064 msg.arg2 = handled ? 1 : 0; 4065 msg.setAsynchronous(true); 4066 mHandler.sendMessage(msg); 4067 } 4068 4069 public void dispatchFinishInputConnection(InputConnection connection) { 4070 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 4071 mHandler.sendMessage(msg); 4072 } 4073 4074 public void dispatchResized(int w, int h, Rect systemInsets, Rect contentInsets, 4075 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4076 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w 4077 + " h=" + h + " systemInsets=" + systemInsets.toShortString() 4078 + " contentInsets=" + contentInsets.toShortString() 4079 + " visibleInsets=" + visibleInsets.toShortString() 4080 + " reportDraw=" + reportDraw); 4081 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT :MSG_RESIZED); 4082 if (mTranslator != null) { 4083 mTranslator.translateRectInScreenToAppWindow(contentInsets); 4084 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 4085 w *= mTranslator.applicationInvertedScale; 4086 h *= mTranslator.applicationInvertedScale; 4087 } 4088 msg.arg1 = w; 4089 msg.arg2 = h; 4090 ResizedInfo ri = new ResizedInfo(); 4091 ri.systemInsets = new Rect(systemInsets); 4092 ri.contentInsets = new Rect(contentInsets); 4093 ri.visibleInsets = new Rect(visibleInsets); 4094 ri.newConfig = newConfig; 4095 msg.obj = ri; 4096 mHandler.sendMessage(msg); 4097 } 4098 4099 /** 4100 * Represents a pending input event that is waiting in a queue. 4101 * 4102 * Input events are processed in serial order by the timestamp specified by 4103 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 4104 * one input event to the application at a time and waits for the application 4105 * to finish handling it before delivering the next one. 4106 * 4107 * However, because the application or IME can synthesize and inject multiple 4108 * key events at a time without going through the input dispatcher, we end up 4109 * needing a queue on the application's side. 4110 */ 4111 private static final class QueuedInputEvent { 4112 public static final int FLAG_DELIVER_POST_IME = 1; 4113 4114 public QueuedInputEvent mNext; 4115 4116 public InputEvent mEvent; 4117 public InputEventReceiver mReceiver; 4118 public int mFlags; 4119 4120 // Used for latency calculations. 4121 public long mReceiveTimeNanos; 4122 public long mDeliverTimeNanos; 4123 public long mDeliverPostImeTimeNanos; 4124 } 4125 4126 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 4127 InputEventReceiver receiver, int flags) { 4128 QueuedInputEvent q = mQueuedInputEventPool; 4129 if (q != null) { 4130 mQueuedInputEventPoolSize -= 1; 4131 mQueuedInputEventPool = q.mNext; 4132 q.mNext = null; 4133 } else { 4134 q = new QueuedInputEvent(); 4135 } 4136 4137 q.mEvent = event; 4138 q.mReceiver = receiver; 4139 q.mFlags = flags; 4140 return q; 4141 } 4142 4143 private void recycleQueuedInputEvent(QueuedInputEvent q) { 4144 q.mEvent = null; 4145 q.mReceiver = null; 4146 4147 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 4148 mQueuedInputEventPoolSize += 1; 4149 q.mNext = mQueuedInputEventPool; 4150 mQueuedInputEventPool = q; 4151 } 4152 } 4153 4154 void enqueueInputEvent(InputEvent event) { 4155 enqueueInputEvent(event, null, 0, false); 4156 } 4157 4158 void enqueueInputEvent(InputEvent event, 4159 InputEventReceiver receiver, int flags, boolean processImmediately) { 4160 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 4161 4162 if (ViewDebug.DEBUG_LATENCY) { 4163 q.mReceiveTimeNanos = System.nanoTime(); 4164 q.mDeliverTimeNanos = 0; 4165 q.mDeliverPostImeTimeNanos = 0; 4166 } 4167 4168 // Always enqueue the input event in order, regardless of its time stamp. 4169 // We do this because the application or the IME may inject key events 4170 // in response to touch events and we want to ensure that the injected keys 4171 // are processed in the order they were received and we cannot trust that 4172 // the time stamp of injected events are monotonic. 4173 QueuedInputEvent last = mFirstPendingInputEvent; 4174 if (last == null) { 4175 mFirstPendingInputEvent = q; 4176 } else { 4177 while (last.mNext != null) { 4178 last = last.mNext; 4179 } 4180 last.mNext = q; 4181 } 4182 4183 if (processImmediately) { 4184 doProcessInputEvents(); 4185 } else { 4186 scheduleProcessInputEvents(); 4187 } 4188 } 4189 4190 private void scheduleProcessInputEvents() { 4191 if (!mProcessInputEventsScheduled) { 4192 mProcessInputEventsScheduled = true; 4193 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 4194 msg.setAsynchronous(true); 4195 mHandler.sendMessage(msg); 4196 } 4197 } 4198 4199 void doProcessInputEvents() { 4200 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 4201 QueuedInputEvent q = mFirstPendingInputEvent; 4202 mFirstPendingInputEvent = q.mNext; 4203 q.mNext = null; 4204 mCurrentInputEvent = q; 4205 deliverInputEvent(q); 4206 } 4207 4208 // We are done processing all input events that we can process right now 4209 // so we can clear the pending flag immediately. 4210 if (mProcessInputEventsScheduled) { 4211 mProcessInputEventsScheduled = false; 4212 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 4213 } 4214 } 4215 4216 private void finishInputEvent(QueuedInputEvent q, boolean handled) { 4217 if (q != mCurrentInputEvent) { 4218 throw new IllegalStateException("finished input event out of order"); 4219 } 4220 4221 if (ViewDebug.DEBUG_LATENCY) { 4222 final long now = System.nanoTime(); 4223 final long eventTime = q.mEvent.getEventTimeNano(); 4224 final StringBuilder msg = new StringBuilder(); 4225 msg.append("Spent "); 4226 msg.append((now - q.mReceiveTimeNanos) * 0.000001f); 4227 msg.append("ms processing "); 4228 if (q.mEvent instanceof KeyEvent) { 4229 final KeyEvent keyEvent = (KeyEvent)q.mEvent; 4230 msg.append("key event, action="); 4231 msg.append(KeyEvent.actionToString(keyEvent.getAction())); 4232 } else { 4233 final MotionEvent motionEvent = (MotionEvent)q.mEvent; 4234 msg.append("motion event, action="); 4235 msg.append(MotionEvent.actionToString(motionEvent.getAction())); 4236 msg.append(", historySize="); 4237 msg.append(motionEvent.getHistorySize()); 4238 } 4239 msg.append(", handled="); 4240 msg.append(handled); 4241 msg.append(", received at +"); 4242 msg.append((q.mReceiveTimeNanos - eventTime) * 0.000001f); 4243 if (q.mDeliverTimeNanos != 0) { 4244 msg.append("ms, delivered at +"); 4245 msg.append((q.mDeliverTimeNanos - eventTime) * 0.000001f); 4246 } 4247 if (q.mDeliverPostImeTimeNanos != 0) { 4248 msg.append("ms, delivered post IME at +"); 4249 msg.append((q.mDeliverPostImeTimeNanos - eventTime) * 0.000001f); 4250 } 4251 msg.append("ms, finished at +"); 4252 msg.append((now - eventTime) * 0.000001f); 4253 msg.append("ms."); 4254 Log.d(ViewDebug.DEBUG_LATENCY_TAG, msg.toString()); 4255 } 4256 4257 if (q.mReceiver != null) { 4258 q.mReceiver.finishInputEvent(q.mEvent, handled); 4259 } else { 4260 q.mEvent.recycleIfNeededAfterDispatch(); 4261 } 4262 4263 recycleQueuedInputEvent(q); 4264 4265 mCurrentInputEvent = null; 4266 if (mFirstPendingInputEvent != null) { 4267 scheduleProcessInputEvents(); 4268 } 4269 } 4270 4271 void scheduleConsumeBatchedInput() { 4272 if (!mConsumeBatchedInputScheduled) { 4273 mConsumeBatchedInputScheduled = true; 4274 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 4275 mConsumedBatchedInputRunnable, null); 4276 } 4277 } 4278 4279 void unscheduleConsumeBatchedInput() { 4280 if (mConsumeBatchedInputScheduled) { 4281 mConsumeBatchedInputScheduled = false; 4282 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4283 mConsumedBatchedInputRunnable, null); 4284 } 4285 } 4286 4287 void doConsumeBatchedInput(long frameTimeNanos) { 4288 if (mConsumeBatchedInputScheduled) { 4289 mConsumeBatchedInputScheduled = false; 4290 if (mInputEventReceiver != null) { 4291 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos); 4292 } 4293 doProcessInputEvents(); 4294 } 4295 } 4296 4297 final class TraversalRunnable implements Runnable { 4298 @Override 4299 public void run() { 4300 doTraversal(); 4301 } 4302 } 4303 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 4304 4305 final class WindowInputEventReceiver extends InputEventReceiver { 4306 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 4307 super(inputChannel, looper); 4308 } 4309 4310 @Override 4311 public void onInputEvent(InputEvent event) { 4312 enqueueInputEvent(event, this, 0, true); 4313 } 4314 4315 @Override 4316 public void onBatchedInputEventPending() { 4317 scheduleConsumeBatchedInput(); 4318 } 4319 4320 @Override 4321 public void dispose() { 4322 unscheduleConsumeBatchedInput(); 4323 super.dispose(); 4324 } 4325 } 4326 WindowInputEventReceiver mInputEventReceiver; 4327 4328 final class ConsumeBatchedInputRunnable implements Runnable { 4329 @Override 4330 public void run() { 4331 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 4332 } 4333 } 4334 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 4335 new ConsumeBatchedInputRunnable(); 4336 boolean mConsumeBatchedInputScheduled; 4337 4338 final class InvalidateOnAnimationRunnable implements Runnable { 4339 private boolean mPosted; 4340 private ArrayList<View> mViews = new ArrayList<View>(); 4341 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 4342 new ArrayList<AttachInfo.InvalidateInfo>(); 4343 private View[] mTempViews; 4344 private AttachInfo.InvalidateInfo[] mTempViewRects; 4345 4346 public void addView(View view) { 4347 synchronized (this) { 4348 mViews.add(view); 4349 postIfNeededLocked(); 4350 } 4351 } 4352 4353 public void addViewRect(AttachInfo.InvalidateInfo info) { 4354 synchronized (this) { 4355 mViewRects.add(info); 4356 postIfNeededLocked(); 4357 } 4358 } 4359 4360 public void removeView(View view) { 4361 synchronized (this) { 4362 mViews.remove(view); 4363 4364 for (int i = mViewRects.size(); i-- > 0; ) { 4365 AttachInfo.InvalidateInfo info = mViewRects.get(i); 4366 if (info.target == view) { 4367 mViewRects.remove(i); 4368 info.release(); 4369 } 4370 } 4371 4372 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 4373 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 4374 mPosted = false; 4375 } 4376 } 4377 } 4378 4379 @Override 4380 public void run() { 4381 final int viewCount; 4382 final int viewRectCount; 4383 synchronized (this) { 4384 mPosted = false; 4385 4386 viewCount = mViews.size(); 4387 if (viewCount != 0) { 4388 mTempViews = mViews.toArray(mTempViews != null 4389 ? mTempViews : new View[viewCount]); 4390 mViews.clear(); 4391 } 4392 4393 viewRectCount = mViewRects.size(); 4394 if (viewRectCount != 0) { 4395 mTempViewRects = mViewRects.toArray(mTempViewRects != null 4396 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 4397 mViewRects.clear(); 4398 } 4399 } 4400 4401 for (int i = 0; i < viewCount; i++) { 4402 mTempViews[i].invalidate(); 4403 } 4404 4405 for (int i = 0; i < viewRectCount; i++) { 4406 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 4407 info.target.invalidate(info.left, info.top, info.right, info.bottom); 4408 info.release(); 4409 } 4410 } 4411 4412 private void postIfNeededLocked() { 4413 if (!mPosted) { 4414 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 4415 mPosted = true; 4416 } 4417 } 4418 } 4419 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 4420 new InvalidateOnAnimationRunnable(); 4421 4422 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 4423 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 4424 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4425 } 4426 4427 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 4428 long delayMilliseconds) { 4429 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 4430 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4431 } 4432 4433 public void dispatchInvalidateOnAnimation(View view) { 4434 mInvalidateOnAnimationRunnable.addView(view); 4435 } 4436 4437 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 4438 mInvalidateOnAnimationRunnable.addViewRect(info); 4439 } 4440 4441 public void enqueueDisplayList(DisplayList displayList) { 4442 mDisplayLists.add(displayList); 4443 4444 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4445 Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST); 4446 mHandler.sendMessage(msg); 4447 } 4448 4449 public void dequeueDisplayList(DisplayList displayList) { 4450 if (mDisplayLists.remove(displayList)) { 4451 displayList.invalidate(); 4452 if (mDisplayLists.size() == 0) { 4453 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4454 } 4455 } 4456 } 4457 4458 public void cancelInvalidate(View view) { 4459 mHandler.removeMessages(MSG_INVALIDATE, view); 4460 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 4461 // them to the pool 4462 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 4463 mInvalidateOnAnimationRunnable.removeView(view); 4464 } 4465 4466 public void dispatchKey(KeyEvent event) { 4467 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 4468 msg.setAsynchronous(true); 4469 mHandler.sendMessage(msg); 4470 } 4471 4472 public void dispatchKeyFromIme(KeyEvent event) { 4473 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 4474 msg.setAsynchronous(true); 4475 mHandler.sendMessage(msg); 4476 } 4477 4478 public void dispatchUnhandledKey(KeyEvent event) { 4479 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 4480 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 4481 final int keyCode = event.getKeyCode(); 4482 final int metaState = event.getMetaState(); 4483 4484 // Check for fallback actions specified by the key character map. 4485 KeyCharacterMap.FallbackAction fallbackAction = 4486 kcm.getFallbackAction(keyCode, metaState); 4487 if (fallbackAction != null) { 4488 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 4489 KeyEvent fallbackEvent = KeyEvent.obtain( 4490 event.getDownTime(), event.getEventTime(), 4491 event.getAction(), fallbackAction.keyCode, 4492 event.getRepeatCount(), fallbackAction.metaState, 4493 event.getDeviceId(), event.getScanCode(), 4494 flags, event.getSource(), null); 4495 fallbackAction.recycle(); 4496 4497 dispatchKey(fallbackEvent); 4498 } 4499 } 4500 } 4501 4502 public void dispatchAppVisibility(boolean visible) { 4503 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 4504 msg.arg1 = visible ? 1 : 0; 4505 mHandler.sendMessage(msg); 4506 } 4507 4508 public void dispatchScreenStateChange(boolean on) { 4509 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 4510 msg.arg1 = on ? 1 : 0; 4511 mHandler.sendMessage(msg); 4512 } 4513 4514 public void dispatchGetNewSurface() { 4515 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 4516 mHandler.sendMessage(msg); 4517 } 4518 4519 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4520 Message msg = Message.obtain(); 4521 msg.what = MSG_WINDOW_FOCUS_CHANGED; 4522 msg.arg1 = hasFocus ? 1 : 0; 4523 msg.arg2 = inTouchMode ? 1 : 0; 4524 mHandler.sendMessage(msg); 4525 } 4526 4527 public void dispatchCloseSystemDialogs(String reason) { 4528 Message msg = Message.obtain(); 4529 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 4530 msg.obj = reason; 4531 mHandler.sendMessage(msg); 4532 } 4533 4534 public void dispatchDragEvent(DragEvent event) { 4535 final int what; 4536 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 4537 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 4538 mHandler.removeMessages(what); 4539 } else { 4540 what = MSG_DISPATCH_DRAG_EVENT; 4541 } 4542 Message msg = mHandler.obtainMessage(what, event); 4543 mHandler.sendMessage(msg); 4544 } 4545 4546 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4547 int localValue, int localChanges) { 4548 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 4549 args.seq = seq; 4550 args.globalVisibility = globalVisibility; 4551 args.localValue = localValue; 4552 args.localChanges = localChanges; 4553 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 4554 } 4555 4556 public void dispatchDoneAnimating() { 4557 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 4558 } 4559 4560 public void dispatchCheckFocus() { 4561 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 4562 // This will result in a call to checkFocus() below. 4563 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 4564 } 4565 } 4566 4567 /** 4568 * Post a callback to send a 4569 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4570 * This event is send at most once every 4571 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 4572 */ 4573 private void postSendWindowContentChangedCallback(View source) { 4574 if (mSendWindowContentChangedAccessibilityEvent == null) { 4575 mSendWindowContentChangedAccessibilityEvent = 4576 new SendWindowContentChangedAccessibilityEvent(); 4577 } 4578 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource; 4579 if (oldSource == null) { 4580 mSendWindowContentChangedAccessibilityEvent.mSource = source; 4581 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 4582 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 4583 } else { 4584 mSendWindowContentChangedAccessibilityEvent.mSource = 4585 getCommonPredecessor(oldSource, source); 4586 } 4587 } 4588 4589 /** 4590 * Remove a posted callback to send a 4591 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4592 */ 4593 private void removeSendWindowContentChangedCallback() { 4594 if (mSendWindowContentChangedAccessibilityEvent != null) { 4595 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 4596 } 4597 } 4598 4599 public boolean showContextMenuForChild(View originalView) { 4600 return false; 4601 } 4602 4603 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 4604 return null; 4605 } 4606 4607 public void createContextMenu(ContextMenu menu) { 4608 } 4609 4610 public void childDrawableStateChanged(View child) { 4611 } 4612 4613 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 4614 if (mView == null) { 4615 return false; 4616 } 4617 mAccessibilityManager.sendAccessibilityEvent(event); 4618 return true; 4619 } 4620 4621 @Override 4622 public void childAccessibilityStateChanged(View child) { 4623 postSendWindowContentChangedCallback(child); 4624 } 4625 4626 private View getCommonPredecessor(View first, View second) { 4627 if (mAttachInfo != null) { 4628 if (mTempHashSet == null) { 4629 mTempHashSet = new HashSet<View>(); 4630 } 4631 HashSet<View> seen = mTempHashSet; 4632 seen.clear(); 4633 View firstCurrent = first; 4634 while (firstCurrent != null) { 4635 seen.add(firstCurrent); 4636 ViewParent firstCurrentParent = firstCurrent.mParent; 4637 if (firstCurrentParent instanceof View) { 4638 firstCurrent = (View) firstCurrentParent; 4639 } else { 4640 firstCurrent = null; 4641 } 4642 } 4643 View secondCurrent = second; 4644 while (secondCurrent != null) { 4645 if (seen.contains(secondCurrent)) { 4646 seen.clear(); 4647 return secondCurrent; 4648 } 4649 ViewParent secondCurrentParent = secondCurrent.mParent; 4650 if (secondCurrentParent instanceof View) { 4651 secondCurrent = (View) secondCurrentParent; 4652 } else { 4653 secondCurrent = null; 4654 } 4655 } 4656 seen.clear(); 4657 } 4658 return null; 4659 } 4660 4661 void checkThread() { 4662 if (mThread != Thread.currentThread()) { 4663 throw new CalledFromWrongThreadException( 4664 "Only the original thread that created a view hierarchy can touch its views."); 4665 } 4666 } 4667 4668 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4669 // ViewAncestor never intercepts touch event, so this can be a no-op 4670 } 4671 4672 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 4673 boolean immediate) { 4674 return scrollToRectOrFocus(rectangle, immediate); 4675 } 4676 4677 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 4678 // Do nothing. 4679 } 4680 4681 class TakenSurfaceHolder extends BaseSurfaceHolder { 4682 @Override 4683 public boolean onAllowLockCanvas() { 4684 return mDrawingAllowed; 4685 } 4686 4687 @Override 4688 public void onRelayoutContainer() { 4689 // Not currently interesting -- from changing between fixed and layout size. 4690 } 4691 4692 public void setFormat(int format) { 4693 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4694 } 4695 4696 public void setType(int type) { 4697 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4698 } 4699 4700 @Override 4701 public void onUpdateSurface() { 4702 // We take care of format and type changes on our own. 4703 throw new IllegalStateException("Shouldn't be here"); 4704 } 4705 4706 public boolean isCreating() { 4707 return mIsCreating; 4708 } 4709 4710 @Override 4711 public void setFixedSize(int width, int height) { 4712 throw new UnsupportedOperationException( 4713 "Currently only support sizing from layout"); 4714 } 4715 4716 public void setKeepScreenOn(boolean screenOn) { 4717 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4718 } 4719 } 4720 4721 static class InputMethodCallback extends IInputMethodCallback.Stub { 4722 private WeakReference<ViewRootImpl> mViewAncestor; 4723 4724 public InputMethodCallback(ViewRootImpl viewAncestor) { 4725 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4726 } 4727 4728 public void finishedEvent(int seq, boolean handled) { 4729 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4730 if (viewAncestor != null) { 4731 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4732 } 4733 } 4734 4735 public void sessionCreated(IInputMethodSession session) { 4736 // Stub -- not for use in the client. 4737 } 4738 } 4739 4740 static class W extends IWindow.Stub { 4741 private final WeakReference<ViewRootImpl> mViewAncestor; 4742 4743 W(ViewRootImpl viewAncestor) { 4744 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4745 } 4746 4747 public void resized(int w, int h, Rect systemInsets, Rect contentInsets, 4748 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4749 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4750 if (viewAncestor != null) { 4751 viewAncestor.dispatchResized(w, h, systemInsets, contentInsets, 4752 visibleInsets, reportDraw, newConfig); 4753 } 4754 } 4755 4756 public void dispatchAppVisibility(boolean visible) { 4757 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4758 if (viewAncestor != null) { 4759 viewAncestor.dispatchAppVisibility(visible); 4760 } 4761 } 4762 4763 public void dispatchScreenState(boolean on) { 4764 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4765 if (viewAncestor != null) { 4766 viewAncestor.dispatchScreenStateChange(on); 4767 } 4768 } 4769 4770 public void dispatchGetNewSurface() { 4771 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4772 if (viewAncestor != null) { 4773 viewAncestor.dispatchGetNewSurface(); 4774 } 4775 } 4776 4777 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4778 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4779 if (viewAncestor != null) { 4780 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4781 } 4782 } 4783 4784 private static int checkCallingPermission(String permission) { 4785 try { 4786 return ActivityManagerNative.getDefault().checkPermission( 4787 permission, Binder.getCallingPid(), Binder.getCallingUid()); 4788 } catch (RemoteException e) { 4789 return PackageManager.PERMISSION_DENIED; 4790 } 4791 } 4792 4793 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 4794 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4795 if (viewAncestor != null) { 4796 final View view = viewAncestor.mView; 4797 if (view != null) { 4798 if (checkCallingPermission(Manifest.permission.DUMP) != 4799 PackageManager.PERMISSION_GRANTED) { 4800 throw new SecurityException("Insufficient permissions to invoke" 4801 + " executeCommand() from pid=" + Binder.getCallingPid() 4802 + ", uid=" + Binder.getCallingUid()); 4803 } 4804 4805 OutputStream clientStream = null; 4806 try { 4807 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 4808 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 4809 } catch (IOException e) { 4810 e.printStackTrace(); 4811 } finally { 4812 if (clientStream != null) { 4813 try { 4814 clientStream.close(); 4815 } catch (IOException e) { 4816 e.printStackTrace(); 4817 } 4818 } 4819 } 4820 } 4821 } 4822 } 4823 4824 public void closeSystemDialogs(String reason) { 4825 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4826 if (viewAncestor != null) { 4827 viewAncestor.dispatchCloseSystemDialogs(reason); 4828 } 4829 } 4830 4831 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 4832 boolean sync) { 4833 if (sync) { 4834 try { 4835 sWindowSession.wallpaperOffsetsComplete(asBinder()); 4836 } catch (RemoteException e) { 4837 } 4838 } 4839 } 4840 4841 public void dispatchWallpaperCommand(String action, int x, int y, 4842 int z, Bundle extras, boolean sync) { 4843 if (sync) { 4844 try { 4845 sWindowSession.wallpaperCommandComplete(asBinder(), null); 4846 } catch (RemoteException e) { 4847 } 4848 } 4849 } 4850 4851 /* Drag/drop */ 4852 public void dispatchDragEvent(DragEvent event) { 4853 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4854 if (viewAncestor != null) { 4855 viewAncestor.dispatchDragEvent(event); 4856 } 4857 } 4858 4859 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4860 int localValue, int localChanges) { 4861 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4862 if (viewAncestor != null) { 4863 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 4864 localValue, localChanges); 4865 } 4866 } 4867 4868 public void doneAnimating() { 4869 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4870 if (viewAncestor != null) { 4871 viewAncestor.dispatchDoneAnimating(); 4872 } 4873 } 4874 } 4875 4876 /** 4877 * Maintains state information for a single trackball axis, generating 4878 * discrete (DPAD) movements based on raw trackball motion. 4879 */ 4880 static final class TrackballAxis { 4881 /** 4882 * The maximum amount of acceleration we will apply. 4883 */ 4884 static final float MAX_ACCELERATION = 20; 4885 4886 /** 4887 * The maximum amount of time (in milliseconds) between events in order 4888 * for us to consider the user to be doing fast trackball movements, 4889 * and thus apply an acceleration. 4890 */ 4891 static final long FAST_MOVE_TIME = 150; 4892 4893 /** 4894 * Scaling factor to the time (in milliseconds) between events to how 4895 * much to multiple/divide the current acceleration. When movement 4896 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4897 * FAST_MOVE_TIME it divides it. 4898 */ 4899 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4900 4901 float position; 4902 float absPosition; 4903 float acceleration = 1; 4904 long lastMoveTime = 0; 4905 int step; 4906 int dir; 4907 int nonAccelMovement; 4908 4909 void reset(int _step) { 4910 position = 0; 4911 acceleration = 1; 4912 lastMoveTime = 0; 4913 step = _step; 4914 dir = 0; 4915 } 4916 4917 /** 4918 * Add trackball movement into the state. If the direction of movement 4919 * has been reversed, the state is reset before adding the 4920 * movement (so that you don't have to compensate for any previously 4921 * collected movement before see the result of the movement in the 4922 * new direction). 4923 * 4924 * @return Returns the absolute value of the amount of movement 4925 * collected so far. 4926 */ 4927 float collect(float off, long time, String axis) { 4928 long normTime; 4929 if (off > 0) { 4930 normTime = (long)(off * FAST_MOVE_TIME); 4931 if (dir < 0) { 4932 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4933 position = 0; 4934 step = 0; 4935 acceleration = 1; 4936 lastMoveTime = 0; 4937 } 4938 dir = 1; 4939 } else if (off < 0) { 4940 normTime = (long)((-off) * FAST_MOVE_TIME); 4941 if (dir > 0) { 4942 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4943 position = 0; 4944 step = 0; 4945 acceleration = 1; 4946 lastMoveTime = 0; 4947 } 4948 dir = -1; 4949 } else { 4950 normTime = 0; 4951 } 4952 4953 // The number of milliseconds between each movement that is 4954 // considered "normal" and will not result in any acceleration 4955 // or deceleration, scaled by the offset we have here. 4956 if (normTime > 0) { 4957 long delta = time - lastMoveTime; 4958 lastMoveTime = time; 4959 float acc = acceleration; 4960 if (delta < normTime) { 4961 // The user is scrolling rapidly, so increase acceleration. 4962 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4963 if (scale > 1) acc *= scale; 4964 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4965 + off + " normTime=" + normTime + " delta=" + delta 4966 + " scale=" + scale + " acc=" + acc); 4967 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4968 } else { 4969 // The user is scrolling slowly, so decrease acceleration. 4970 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4971 if (scale > 1) acc /= scale; 4972 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4973 + off + " normTime=" + normTime + " delta=" + delta 4974 + " scale=" + scale + " acc=" + acc); 4975 acceleration = acc > 1 ? acc : 1; 4976 } 4977 } 4978 position += off; 4979 return (absPosition = Math.abs(position)); 4980 } 4981 4982 /** 4983 * Generate the number of discrete movement events appropriate for 4984 * the currently collected trackball movement. 4985 * 4986 * @param precision The minimum movement required to generate the 4987 * first discrete movement. 4988 * 4989 * @return Returns the number of discrete movements, either positive 4990 * or negative, or 0 if there is not enough trackball movement yet 4991 * for a discrete movement. 4992 */ 4993 int generate(float precision) { 4994 int movement = 0; 4995 nonAccelMovement = 0; 4996 do { 4997 final int dir = position >= 0 ? 1 : -1; 4998 switch (step) { 4999 // If we are going to execute the first step, then we want 5000 // to do this as soon as possible instead of waiting for 5001 // a full movement, in order to make things look responsive. 5002 case 0: 5003 if (absPosition < precision) { 5004 return movement; 5005 } 5006 movement += dir; 5007 nonAccelMovement += dir; 5008 step = 1; 5009 break; 5010 // If we have generated the first movement, then we need 5011 // to wait for the second complete trackball motion before 5012 // generating the second discrete movement. 5013 case 1: 5014 if (absPosition < 2) { 5015 return movement; 5016 } 5017 movement += dir; 5018 nonAccelMovement += dir; 5019 position += dir > 0 ? -2 : 2; 5020 absPosition = Math.abs(position); 5021 step = 2; 5022 break; 5023 // After the first two, we generate discrete movements 5024 // consistently with the trackball, applying an acceleration 5025 // if the trackball is moving quickly. This is a simple 5026 // acceleration on top of what we already compute based 5027 // on how quickly the wheel is being turned, to apply 5028 // a longer increasing acceleration to continuous movement 5029 // in one direction. 5030 default: 5031 if (absPosition < 1) { 5032 return movement; 5033 } 5034 movement += dir; 5035 position += dir >= 0 ? -1 : 1; 5036 absPosition = Math.abs(position); 5037 float acc = acceleration; 5038 acc *= 1.1f; 5039 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 5040 break; 5041 } 5042 } while (true); 5043 } 5044 } 5045 5046 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 5047 public CalledFromWrongThreadException(String msg) { 5048 super(msg); 5049 } 5050 } 5051 5052 private SurfaceHolder mHolder = new SurfaceHolder() { 5053 // we only need a SurfaceHolder for opengl. it would be nice 5054 // to implement everything else though, especially the callback 5055 // support (opengl doesn't make use of it right now, but eventually 5056 // will). 5057 public Surface getSurface() { 5058 return mSurface; 5059 } 5060 5061 public boolean isCreating() { 5062 return false; 5063 } 5064 5065 public void addCallback(Callback callback) { 5066 } 5067 5068 public void removeCallback(Callback callback) { 5069 } 5070 5071 public void setFixedSize(int width, int height) { 5072 } 5073 5074 public void setSizeFromLayout() { 5075 } 5076 5077 public void setFormat(int format) { 5078 } 5079 5080 public void setType(int type) { 5081 } 5082 5083 public void setKeepScreenOn(boolean screenOn) { 5084 } 5085 5086 public Canvas lockCanvas() { 5087 return null; 5088 } 5089 5090 public Canvas lockCanvas(Rect dirty) { 5091 return null; 5092 } 5093 5094 public void unlockCanvasAndPost(Canvas canvas) { 5095 } 5096 public Rect getSurfaceFrame() { 5097 return null; 5098 } 5099 }; 5100 5101 static RunQueue getRunQueue() { 5102 RunQueue rq = sRunQueues.get(); 5103 if (rq != null) { 5104 return rq; 5105 } 5106 rq = new RunQueue(); 5107 sRunQueues.set(rq); 5108 return rq; 5109 } 5110 5111 /** 5112 * The run queue is used to enqueue pending work from Views when no Handler is 5113 * attached. The work is executed during the next call to performTraversals on 5114 * the thread. 5115 * @hide 5116 */ 5117 static final class RunQueue { 5118 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 5119 5120 void post(Runnable action) { 5121 postDelayed(action, 0); 5122 } 5123 5124 void postDelayed(Runnable action, long delayMillis) { 5125 HandlerAction handlerAction = new HandlerAction(); 5126 handlerAction.action = action; 5127 handlerAction.delay = delayMillis; 5128 5129 synchronized (mActions) { 5130 mActions.add(handlerAction); 5131 } 5132 } 5133 5134 void removeCallbacks(Runnable action) { 5135 final HandlerAction handlerAction = new HandlerAction(); 5136 handlerAction.action = action; 5137 5138 synchronized (mActions) { 5139 final ArrayList<HandlerAction> actions = mActions; 5140 5141 while (actions.remove(handlerAction)) { 5142 // Keep going 5143 } 5144 } 5145 } 5146 5147 void executeActions(Handler handler) { 5148 synchronized (mActions) { 5149 final ArrayList<HandlerAction> actions = mActions; 5150 final int count = actions.size(); 5151 5152 for (int i = 0; i < count; i++) { 5153 final HandlerAction handlerAction = actions.get(i); 5154 handler.postDelayed(handlerAction.action, handlerAction.delay); 5155 } 5156 5157 actions.clear(); 5158 } 5159 } 5160 5161 private static class HandlerAction { 5162 Runnable action; 5163 long delay; 5164 5165 @Override 5166 public boolean equals(Object o) { 5167 if (this == o) return true; 5168 if (o == null || getClass() != o.getClass()) return false; 5169 5170 HandlerAction that = (HandlerAction) o; 5171 return !(action != null ? !action.equals(that.action) : that.action != null); 5172 5173 } 5174 5175 @Override 5176 public int hashCode() { 5177 int result = action != null ? action.hashCode() : 0; 5178 result = 31 * result + (int) (delay ^ (delay >>> 32)); 5179 return result; 5180 } 5181 } 5182 } 5183 5184 /** 5185 * Class for managing the accessibility interaction connection 5186 * based on the global accessibility state. 5187 */ 5188 final class AccessibilityInteractionConnectionManager 5189 implements AccessibilityStateChangeListener { 5190 public void onAccessibilityStateChanged(boolean enabled) { 5191 if (enabled) { 5192 ensureConnection(); 5193 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 5194 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 5195 View focusedView = mView.findFocus(); 5196 if (focusedView != null && focusedView != mView) { 5197 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5198 } 5199 } 5200 } else { 5201 ensureNoConnection(); 5202 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 5203 } 5204 } 5205 5206 public void ensureConnection() { 5207 if (mAttachInfo != null) { 5208 final boolean registered = 5209 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5210 if (!registered) { 5211 mAttachInfo.mAccessibilityWindowId = 5212 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 5213 new AccessibilityInteractionConnection(ViewRootImpl.this)); 5214 } 5215 } 5216 } 5217 5218 public void ensureNoConnection() { 5219 final boolean registered = 5220 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5221 if (registered) { 5222 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 5223 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 5224 } 5225 } 5226 } 5227 5228 /** 5229 * This class is an interface this ViewAncestor provides to the 5230 * AccessibilityManagerService to the latter can interact with 5231 * the view hierarchy in this ViewAncestor. 5232 */ 5233 static final class AccessibilityInteractionConnection 5234 extends IAccessibilityInteractionConnection.Stub { 5235 private final WeakReference<ViewRootImpl> mViewRootImpl; 5236 5237 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 5238 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 5239 } 5240 5241 @Override 5242 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 5243 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5244 int flags, int interrogatingPid, long interrogatingTid) { 5245 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5246 if (viewRootImpl != null && viewRootImpl.mView != null) { 5247 viewRootImpl.getAccessibilityInteractionController() 5248 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 5249 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5250 } else { 5251 // We cannot make the call and notify the caller so it does not wait. 5252 try { 5253 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5254 } catch (RemoteException re) { 5255 /* best effort - ignore */ 5256 } 5257 } 5258 } 5259 5260 @Override 5261 public void performAccessibilityAction(long accessibilityNodeId, int action, 5262 Bundle arguments, int interactionId, 5263 IAccessibilityInteractionConnectionCallback callback, int flags, 5264 int interogatingPid, long interrogatingTid) { 5265 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5266 if (viewRootImpl != null && viewRootImpl.mView != null) { 5267 viewRootImpl.getAccessibilityInteractionController() 5268 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 5269 interactionId, callback, flags, interogatingPid, interrogatingTid); 5270 } else { 5271 // We cannot make the call and notify the caller so it does not wait. 5272 try { 5273 callback.setPerformAccessibilityActionResult(false, interactionId); 5274 } catch (RemoteException re) { 5275 /* best effort - ignore */ 5276 } 5277 } 5278 } 5279 5280 @Override 5281 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId, 5282 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5283 int flags, int interrogatingPid, long interrogatingTid) { 5284 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5285 if (viewRootImpl != null && viewRootImpl.mView != null) { 5286 viewRootImpl.getAccessibilityInteractionController() 5287 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId, 5288 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5289 } else { 5290 // We cannot make the call and notify the caller so it does not wait. 5291 try { 5292 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5293 } catch (RemoteException re) { 5294 /* best effort - ignore */ 5295 } 5296 } 5297 } 5298 5299 @Override 5300 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 5301 int interactionId, IAccessibilityInteractionConnectionCallback callback, 5302 int flags, int interrogatingPid, long interrogatingTid) { 5303 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5304 if (viewRootImpl != null && viewRootImpl.mView != null) { 5305 viewRootImpl.getAccessibilityInteractionController() 5306 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 5307 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5308 } else { 5309 // We cannot make the call and notify the caller so it does not wait. 5310 try { 5311 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5312 } catch (RemoteException re) { 5313 /* best effort - ignore */ 5314 } 5315 } 5316 } 5317 5318 @Override 5319 public void findFocus(long accessibilityNodeId, int interactionId, int focusType, 5320 IAccessibilityInteractionConnectionCallback callback, int flags, 5321 int interrogatingPid, long interrogatingTid) { 5322 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5323 if (viewRootImpl != null && viewRootImpl.mView != null) { 5324 viewRootImpl.getAccessibilityInteractionController() 5325 .findFocusClientThread(accessibilityNodeId, interactionId, focusType, 5326 callback, flags, interrogatingPid, interrogatingTid); 5327 } else { 5328 // We cannot make the call and notify the caller so it does not wait. 5329 try { 5330 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5331 } catch (RemoteException re) { 5332 /* best effort - ignore */ 5333 } 5334 } 5335 } 5336 5337 @Override 5338 public void focusSearch(long accessibilityNodeId, int interactionId, int direction, 5339 IAccessibilityInteractionConnectionCallback callback, int flags, 5340 int interrogatingPid, long interrogatingTid) { 5341 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5342 if (viewRootImpl != null && viewRootImpl.mView != null) { 5343 viewRootImpl.getAccessibilityInteractionController() 5344 .focusSearchClientThread(accessibilityNodeId, interactionId, direction, 5345 callback, flags, interrogatingPid, interrogatingTid); 5346 } else { 5347 // We cannot make the call and notify the caller so it does not wait. 5348 try { 5349 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5350 } catch (RemoteException re) { 5351 /* best effort - ignore */ 5352 } 5353 } 5354 } 5355 } 5356 5357 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 5358 public View mSource; 5359 5360 public void run() { 5361 if (mSource != null) { 5362 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 5363 mSource.resetAccessibilityStateChanged(); 5364 mSource = null; 5365 } 5366 } 5367 } 5368} 5369