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