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