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