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