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