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