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