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