ViewRootImpl.java revision b13de07f0b26953115f4315bc7417ca87c70594b
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.app.ActivityManagerNative; 22import android.content.ClipDescription; 23import android.content.ComponentCallbacks; 24import android.content.Context; 25import android.content.pm.PackageManager; 26import android.content.res.CompatibilityInfo; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.graphics.Canvas; 30import android.graphics.Matrix; 31import android.graphics.Paint; 32import android.graphics.PixelFormat; 33import android.graphics.Point; 34import android.graphics.PointF; 35import android.graphics.PorterDuff; 36import android.graphics.Rect; 37import android.graphics.Region; 38import android.graphics.drawable.Drawable; 39import android.hardware.display.DisplayManager; 40import android.hardware.display.DisplayManager.DisplayListener; 41import android.media.AudioManager; 42import android.os.Binder; 43import android.os.Build; 44import android.os.Bundle; 45import android.os.Debug; 46import android.os.Handler; 47import android.os.Looper; 48import android.os.Message; 49import android.os.ParcelFileDescriptor; 50import android.os.Process; 51import android.os.RemoteException; 52import android.os.SystemClock; 53import android.os.SystemProperties; 54import android.os.Trace; 55import android.util.AndroidRuntimeException; 56import android.util.DisplayMetrics; 57import android.util.Log; 58import android.util.Slog; 59import android.util.TypedValue; 60import android.view.Surface.OutOfResourcesException; 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.AccessibilityManager.HighTextContrastChangeListener; 67import android.view.accessibility.AccessibilityNodeInfo; 68import android.view.accessibility.AccessibilityNodeProvider; 69import android.view.accessibility.IAccessibilityInteractionConnection; 70import android.view.accessibility.IAccessibilityInteractionConnectionCallback; 71import android.view.animation.AccelerateDecelerateInterpolator; 72import android.view.animation.Interpolator; 73import android.view.inputmethod.InputConnection; 74import android.view.inputmethod.InputMethodManager; 75import android.widget.Scroller; 76 77import com.android.internal.R; 78import com.android.internal.os.SomeArgs; 79import com.android.internal.policy.PolicyManager; 80import com.android.internal.view.BaseSurfaceHolder; 81import com.android.internal.view.RootViewSurfaceTaker; 82 83import java.io.FileDescriptor; 84import java.io.IOException; 85import java.io.OutputStream; 86import java.io.PrintWriter; 87import java.lang.ref.WeakReference; 88import java.util.ArrayList; 89import java.util.HashSet; 90 91/** 92 * The top of a view hierarchy, implementing the needed protocol between View 93 * and the WindowManager. This is for the most part an internal implementation 94 * detail of {@link WindowManagerGlobal}. 95 * 96 * {@hide} 97 */ 98@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"}) 99public final class ViewRootImpl implements ViewParent, 100 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks { 101 private static final String TAG = "ViewRootImpl"; 102 private static final boolean DBG = false; 103 private static final boolean LOCAL_LOGV = false; 104 /** @noinspection PointlessBooleanExpression*/ 105 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV; 106 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV; 107 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV; 108 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV; 109 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV; 110 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV; 111 private static final boolean DEBUG_IMF = false || LOCAL_LOGV; 112 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV; 113 private static final boolean DEBUG_FPS = false; 114 private static final boolean DEBUG_INPUT_STAGES = false || LOCAL_LOGV; 115 116 /** 117 * Set this system property to true to force the view hierarchy to render 118 * at 60 Hz. This can be used to measure the potential framerate. 119 */ 120 private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering"; 121 private static final String PROPERTY_MEDIA_DISABLED = "config.disable_media"; 122 123 // property used by emulator to determine display shape 124 public static final String PROPERTY_EMULATOR_CIRCULAR = "ro.emulator.circular"; 125 126 /** 127 * Maximum time we allow the user to roll the trackball enough to generate 128 * a key event, before resetting the counters. 129 */ 130 static final int MAX_TRACKBALL_DELAY = 250; 131 132 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>(); 133 134 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>(); 135 static boolean sFirstDrawComplete = false; 136 137 static final ArrayList<ComponentCallbacks> sConfigCallbacks 138 = new ArrayList<ComponentCallbacks>(); 139 140 final Context mContext; 141 final IWindowSession mWindowSession; 142 final Display mDisplay; 143 final DisplayManager mDisplayManager; 144 final String mBasePackageName; 145 146 final int[] mTmpLocation = new int[2]; 147 148 final TypedValue mTmpValue = new TypedValue(); 149 150 final Thread mThread; 151 152 final WindowLeaked mLocation; 153 154 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams(); 155 156 final W mWindow; 157 158 final int mTargetSdkVersion; 159 160 int mSeq; 161 162 View mView; 163 164 View mAccessibilityFocusedHost; 165 AccessibilityNodeInfo mAccessibilityFocusedVirtualView; 166 167 int mViewVisibility; 168 boolean mAppVisible = true; 169 int mOrigWindowType = -1; 170 171 // Set to true if the owner of this window is in the stopped state, 172 // so the window should no longer be active. 173 boolean mStopped = false; 174 175 boolean mLastInCompatMode = false; 176 177 SurfaceHolder.Callback2 mSurfaceHolderCallback; 178 BaseSurfaceHolder mSurfaceHolder; 179 boolean mIsCreating; 180 boolean mDrawingAllowed; 181 182 final Region mTransparentRegion; 183 final Region mPreviousTransparentRegion; 184 185 int mWidth; 186 int mHeight; 187 Rect mDirty; 188 boolean mIsAnimating; 189 190 CompatibilityInfo.Translator mTranslator; 191 192 final View.AttachInfo mAttachInfo; 193 InputChannel mInputChannel; 194 InputQueue.Callback mInputQueueCallback; 195 InputQueue mInputQueue; 196 FallbackEventHandler mFallbackEventHandler; 197 Choreographer mChoreographer; 198 199 final Rect mTempRect; // used in the transaction to not thrash the heap. 200 final Rect mVisRect; // used to retrieve visible rect of focused view. 201 202 boolean mTraversalScheduled; 203 int mTraversalBarrier; 204 boolean mWillDrawSoon; 205 /** Set to true while in performTraversals for detecting when die(true) is called from internal 206 * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */ 207 boolean mIsInTraversal; 208 boolean mApplyInsetsRequested; 209 boolean mLayoutRequested; 210 boolean mFirst; 211 boolean mReportNextDraw; 212 boolean mFullRedrawNeeded; 213 boolean mNewSurfaceNeeded; 214 boolean mHasHadWindowFocus; 215 boolean mLastWasImTarget; 216 boolean mWindowsAnimating; 217 boolean mDrawDuringWindowsAnimating; 218 boolean mIsDrawing; 219 int mLastSystemUiVisibility; 220 int mClientWindowLayoutFlags; 221 boolean mLastOverscanRequested; 222 223 // Pool of queued input events. 224 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10; 225 private QueuedInputEvent mQueuedInputEventPool; 226 private int mQueuedInputEventPoolSize; 227 228 /* Input event queue. 229 * Pending input events are input events waiting to be delivered to the input stages 230 * and handled by the application. 231 */ 232 QueuedInputEvent mPendingInputEventHead; 233 QueuedInputEvent mPendingInputEventTail; 234 int mPendingInputEventCount; 235 boolean mProcessInputEventsScheduled; 236 boolean mUnbufferedInputDispatch; 237 String mPendingInputEventQueueLengthCounterName = "pq"; 238 239 InputStage mFirstInputStage; 240 InputStage mFirstPostImeInputStage; 241 InputStage mSyntheticInputStage; 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 final Surface mSurface = new Surface(); 249 250 boolean mAdded; 251 boolean mAddedTouchMode; 252 253 final DisplayAdjustments mDisplayAdjustments; 254 255 // These are accessed by multiple threads. 256 final Rect mWinFrame; // frame given by window manager. 257 258 final Rect mPendingOverscanInsets = new Rect(); 259 final Rect mPendingVisibleInsets = new Rect(); 260 final Rect mPendingStableInsets = new Rect(); 261 final Rect mPendingContentInsets = new Rect(); 262 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets 263 = new ViewTreeObserver.InternalInsetsInfo(); 264 265 final Rect mDispatchContentInsets = new Rect(); 266 final Rect mDispatchStableInsets = new Rect(); 267 268 final Configuration mLastConfiguration = new Configuration(); 269 final Configuration mPendingConfiguration = new Configuration(); 270 271 boolean mScrollMayChange; 272 int mSoftInputMode; 273 WeakReference<View> mLastScrolledFocus; 274 int mScrollY; 275 int mCurScrollY; 276 Scroller mScroller; 277 HardwareLayer mResizeBuffer; 278 long mResizeBufferStartTime; 279 int mResizeBufferDuration; 280 // Used to block the creation of the ResizeBuffer due to invalidations in 281 // the previous DisplayList tree that must prevent re-execution. 282 // Currently this means a functor was detached. 283 boolean mBlockResizeBuffer; 284 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator(); 285 private ArrayList<LayoutTransition> mPendingTransitions; 286 287 final ViewConfiguration mViewConfiguration; 288 289 /* Drag/drop */ 290 ClipDescription mDragDescription; 291 View mCurrentDragView; 292 volatile Object mLocalDragState; 293 final PointF mDragPoint = new PointF(); 294 final PointF mLastTouchPoint = new PointF(); 295 296 private boolean mProfileRendering; 297 private Choreographer.FrameCallback mRenderProfiler; 298 private boolean mRenderProfilingEnabled; 299 300 private boolean mMediaDisabled; 301 302 // Variables to track frames per second, enabled via DEBUG_FPS flag 303 private long mFpsStartTime = -1; 304 private long mFpsPrevTime = -1; 305 private int mFpsNumFrames; 306 307 /** 308 * see {@link #playSoundEffect(int)} 309 */ 310 AudioManager mAudioManager; 311 312 final AccessibilityManager mAccessibilityManager; 313 314 AccessibilityInteractionController mAccessibilityInteractionController; 315 316 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager; 317 HighContrastTextManager mHighContrastTextManager; 318 319 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent; 320 321 HashSet<View> mTempHashSet; 322 323 private final int mDensity; 324 private final int mNoncompatDensity; 325 326 private boolean mInLayout = false; 327 ArrayList<View> mLayoutRequesters = new ArrayList<View>(); 328 boolean mHandlingLayoutInLayoutRequest = false; 329 330 private int mViewLayoutDirectionInitial; 331 332 /** Set to true once doDie() has been called. */ 333 private boolean mRemoved; 334 335 private boolean mIsEmulator; 336 private boolean mIsCircularEmulator; 337 private final boolean mWindowIsRound; 338 339 /** 340 * Consistency verifier for debugging purposes. 341 */ 342 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 343 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 344 new InputEventConsistencyVerifier(this, 0) : null; 345 346 static final class SystemUiVisibilityInfo { 347 int seq; 348 int globalVisibility; 349 int localValue; 350 int localChanges; 351 } 352 353 public ViewRootImpl(Context context, Display display) { 354 mContext = context; 355 mWindowSession = WindowManagerGlobal.getWindowSession(); 356 mDisplay = display; 357 mBasePackageName = context.getBasePackageName(); 358 359 mDisplayAdjustments = display.getDisplayAdjustments(); 360 361 mThread = Thread.currentThread(); 362 mLocation = new WindowLeaked(null); 363 mLocation.fillInStackTrace(); 364 mWidth = -1; 365 mHeight = -1; 366 mDirty = new Rect(); 367 mTempRect = new Rect(); 368 mVisRect = new Rect(); 369 mWinFrame = new Rect(); 370 mWindow = new W(this); 371 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion; 372 mViewVisibility = View.GONE; 373 mTransparentRegion = new Region(); 374 mPreviousTransparentRegion = new Region(); 375 mFirst = true; // true for the first time the view is added 376 mAdded = false; 377 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this); 378 mAccessibilityManager = AccessibilityManager.getInstance(context); 379 mAccessibilityInteractionConnectionManager = 380 new AccessibilityInteractionConnectionManager(); 381 mAccessibilityManager.addAccessibilityStateChangeListener( 382 mAccessibilityInteractionConnectionManager); 383 mHighContrastTextManager = new HighContrastTextManager(); 384 mAccessibilityManager.addHighTextContrastStateChangeListener( 385 mHighContrastTextManager); 386 mViewConfiguration = ViewConfiguration.get(context); 387 mDensity = context.getResources().getDisplayMetrics().densityDpi; 388 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi; 389 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context); 390 mChoreographer = Choreographer.getInstance(); 391 mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE); 392 loadSystemProperties(); 393 mWindowIsRound = context.getResources().getBoolean( 394 com.android.internal.R.bool.config_windowIsRound); 395 } 396 397 public static void addFirstDrawHandler(Runnable callback) { 398 synchronized (sFirstDrawHandlers) { 399 if (!sFirstDrawComplete) { 400 sFirstDrawHandlers.add(callback); 401 } 402 } 403 } 404 405 public static void addConfigCallback(ComponentCallbacks callback) { 406 synchronized (sConfigCallbacks) { 407 sConfigCallbacks.add(callback); 408 } 409 } 410 411 // FIXME for perf testing only 412 private boolean mProfile = false; 413 414 /** 415 * Call this to profile the next traversal call. 416 * FIXME for perf testing only. Remove eventually 417 */ 418 public void profile() { 419 mProfile = true; 420 } 421 422 /** 423 * Indicates whether we are in touch mode. Calling this method triggers an IPC 424 * call and should be avoided whenever possible. 425 * 426 * @return True, if the device is in touch mode, false otherwise. 427 * 428 * @hide 429 */ 430 static boolean isInTouchMode() { 431 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession(); 432 if (windowSession != null) { 433 try { 434 return windowSession.getInTouchMode(); 435 } catch (RemoteException e) { 436 } 437 } 438 return false; 439 } 440 441 /** 442 * We have one child 443 */ 444 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) { 445 synchronized (this) { 446 if (mView == null) { 447 mView = view; 448 449 mAttachInfo.mDisplayState = mDisplay.getState(); 450 mDisplayManager.registerDisplayListener(mDisplayListener, mHandler); 451 452 mViewLayoutDirectionInitial = mView.getRawLayoutDirection(); 453 mFallbackEventHandler.setView(view); 454 mWindowAttributes.copyFrom(attrs); 455 if (mWindowAttributes.packageName == null) { 456 mWindowAttributes.packageName = mBasePackageName; 457 } 458 attrs = mWindowAttributes; 459 // Keep track of the actual window flags supplied by the client. 460 mClientWindowLayoutFlags = attrs.flags; 461 462 setAccessibilityFocus(null, null); 463 464 if (view instanceof RootViewSurfaceTaker) { 465 mSurfaceHolderCallback = 466 ((RootViewSurfaceTaker)view).willYouTakeTheSurface(); 467 if (mSurfaceHolderCallback != null) { 468 mSurfaceHolder = new TakenSurfaceHolder(); 469 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN); 470 } 471 } 472 473 // Compute surface insets required to draw at specified Z value. 474 // TODO: Use real shadow insets for a constant max Z. 475 final int surfaceInset = (int) Math.ceil(view.getZ() * 2); 476 attrs.surfaceInsets.set(surfaceInset, surfaceInset, surfaceInset, surfaceInset); 477 478 CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo(); 479 mTranslator = compatibilityInfo.getTranslator(); 480 mDisplayAdjustments.setActivityToken(attrs.token); 481 482 // If the application owns the surface, don't enable hardware acceleration 483 if (mSurfaceHolder == null) { 484 enableHardwareAcceleration(attrs); 485 } 486 487 boolean restore = false; 488 if (mTranslator != null) { 489 mSurface.setCompatibilityTranslator(mTranslator); 490 restore = true; 491 attrs.backup(); 492 mTranslator.translateWindowLayout(attrs); 493 } 494 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs); 495 496 if (!compatibilityInfo.supportsScreen()) { 497 attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW; 498 mLastInCompatMode = true; 499 } 500 501 mSoftInputMode = attrs.softInputMode; 502 mWindowAttributesChanged = true; 503 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED; 504 mAttachInfo.mRootView = view; 505 mAttachInfo.mScalingRequired = mTranslator != null; 506 mAttachInfo.mApplicationScale = 507 mTranslator == null ? 1.0f : mTranslator.applicationScale; 508 if (panelParentView != null) { 509 mAttachInfo.mPanelParentWindowToken 510 = panelParentView.getApplicationWindowToken(); 511 } 512 mAdded = true; 513 int res; /* = WindowManagerImpl.ADD_OKAY; */ 514 515 // Schedule the first layout -before- adding to the window 516 // manager, to make sure we do the relayout before receiving 517 // any other events from the system. 518 requestLayout(); 519 if ((mWindowAttributes.inputFeatures 520 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { 521 mInputChannel = new InputChannel(); 522 } 523 try { 524 mOrigWindowType = mWindowAttributes.type; 525 mAttachInfo.mRecomputeGlobalAttributes = true; 526 collectViewAttributes(); 527 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes, 528 getHostVisibility(), mDisplay.getDisplayId(), 529 mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mInputChannel); 530 } catch (RemoteException e) { 531 mAdded = false; 532 mView = null; 533 mAttachInfo.mRootView = null; 534 mInputChannel = null; 535 mFallbackEventHandler.setView(null); 536 unscheduleTraversals(); 537 setAccessibilityFocus(null, null); 538 throw new RuntimeException("Adding window failed", e); 539 } finally { 540 if (restore) { 541 attrs.restore(); 542 } 543 } 544 545 if (mTranslator != null) { 546 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets); 547 } 548 mPendingOverscanInsets.set(0, 0, 0, 0); 549 mPendingContentInsets.set(mAttachInfo.mContentInsets); 550 mPendingStableInsets.set(mAttachInfo.mStableInsets); 551 mPendingVisibleInsets.set(0, 0, 0, 0); 552 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow); 553 if (res < WindowManagerGlobal.ADD_OKAY) { 554 mAttachInfo.mRootView = null; 555 mAdded = false; 556 mFallbackEventHandler.setView(null); 557 unscheduleTraversals(); 558 setAccessibilityFocus(null, null); 559 switch (res) { 560 case WindowManagerGlobal.ADD_BAD_APP_TOKEN: 561 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN: 562 throw new WindowManager.BadTokenException( 563 "Unable to add window -- token " + attrs.token 564 + " is not valid; is your activity running?"); 565 case WindowManagerGlobal.ADD_NOT_APP_TOKEN: 566 throw new WindowManager.BadTokenException( 567 "Unable to add window -- token " + attrs.token 568 + " is not for an application"); 569 case WindowManagerGlobal.ADD_APP_EXITING: 570 throw new WindowManager.BadTokenException( 571 "Unable to add window -- app for token " + attrs.token 572 + " is exiting"); 573 case WindowManagerGlobal.ADD_DUPLICATE_ADD: 574 throw new WindowManager.BadTokenException( 575 "Unable to add window -- window " + mWindow 576 + " has already been added"); 577 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED: 578 // Silently ignore -- we would have just removed it 579 // right away, anyway. 580 return; 581 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON: 582 throw new WindowManager.BadTokenException( 583 "Unable to add window " + mWindow + 584 " -- another window of this type already exists"); 585 case WindowManagerGlobal.ADD_PERMISSION_DENIED: 586 throw new WindowManager.BadTokenException( 587 "Unable to add window " + mWindow + 588 " -- permission denied for this window type"); 589 case WindowManagerGlobal.ADD_INVALID_DISPLAY: 590 throw new WindowManager.InvalidDisplayException( 591 "Unable to add window " + mWindow + 592 " -- the specified display can not be found"); 593 } 594 throw new RuntimeException( 595 "Unable to add window -- unknown error code " + res); 596 } 597 598 if (view instanceof RootViewSurfaceTaker) { 599 mInputQueueCallback = 600 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue(); 601 } 602 if (mInputChannel != null) { 603 if (mInputQueueCallback != null) { 604 mInputQueue = new InputQueue(); 605 mInputQueueCallback.onInputQueueCreated(mInputQueue); 606 } 607 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel, 608 Looper.myLooper()); 609 } 610 611 view.assignParent(this); 612 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0; 613 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0; 614 615 if (mAccessibilityManager.isEnabled()) { 616 mAccessibilityInteractionConnectionManager.ensureConnection(); 617 } 618 619 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 620 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES); 621 } 622 623 // Set up the input pipeline. 624 CharSequence counterSuffix = attrs.getTitle(); 625 mSyntheticInputStage = new SyntheticInputStage(); 626 InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage); 627 InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage, 628 "aq:native-post-ime:" + counterSuffix); 629 InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage); 630 InputStage imeStage = new ImeInputStage(earlyPostImeStage, 631 "aq:ime:" + counterSuffix); 632 InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage); 633 InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage, 634 "aq:native-pre-ime:" + counterSuffix); 635 636 mFirstInputStage = nativePreImeStage; 637 mFirstPostImeInputStage = earlyPostImeStage; 638 mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix; 639 } 640 } 641 } 642 643 /** Whether the window is in local focus mode or not */ 644 private boolean isInLocalFocusMode() { 645 return (mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE) != 0; 646 } 647 648 void destroyHardwareResources() { 649 if (mAttachInfo.mHardwareRenderer != null) { 650 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView); 651 mAttachInfo.mHardwareRenderer.destroy(); 652 } 653 } 654 655 public void detachFunctor(long functor) { 656 // TODO: Make the resize buffer some other way to not need this block 657 mBlockResizeBuffer = true; 658 if (mAttachInfo.mHardwareRenderer != null) { 659 // Fence so that any pending invokeFunctor() messages will be processed 660 // before we return from detachFunctor. 661 mAttachInfo.mHardwareRenderer.stopDrawing(); 662 } 663 } 664 665 /** 666 * Schedules the functor for execution in either kModeProcess or 667 * kModeProcessNoContext, depending on whether or not there is an EGLContext. 668 * 669 * @param functor The native functor to invoke 670 * @param waitForCompletion If true, this will not return until the functor 671 * has invoked. If false, the functor may be invoked 672 * asynchronously. 673 */ 674 public void invokeFunctor(long functor, boolean waitForCompletion) { 675 ThreadedRenderer.invokeFunctor(functor, waitForCompletion); 676 } 677 678 public void registerAnimatingRenderNode(RenderNode animator) { 679 if (mAttachInfo.mHardwareRenderer != null) { 680 mAttachInfo.mHardwareRenderer.registerAnimatingRenderNode(animator); 681 } else { 682 if (mAttachInfo.mPendingAnimatingRenderNodes == null) { 683 mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>(); 684 } 685 mAttachInfo.mPendingAnimatingRenderNodes.add(animator); 686 } 687 } 688 689 private void enableHardwareAcceleration(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 (fakeHwAccelerated) { 720 // This is exclusively for the preview windows the window manager 721 // shows for launching applications, so they will look more like 722 // the app being launched. 723 mAttachInfo.mHardwareAccelerationRequested = true; 724 } else if (!HardwareRenderer.sRendererDisabled 725 || (HardwareRenderer.sSystemRendererDisabled && forceHwAccelerated)) { 726 if (mAttachInfo.mHardwareRenderer != null) { 727 mAttachInfo.mHardwareRenderer.destroy(); 728 } 729 730 final Rect insets = attrs.surfaceInsets; 731 final boolean hasSurfaceInsets = insets.left != 0 || insets.right != 0 732 || insets.top != 0 || insets.bottom != 0; 733 final boolean translucent = attrs.format != PixelFormat.OPAQUE || hasSurfaceInsets; 734 mAttachInfo.mHardwareRenderer = HardwareRenderer.create(mContext, translucent); 735 if (mAttachInfo.mHardwareRenderer != null) { 736 mAttachInfo.mHardwareRenderer.setName(attrs.getTitle().toString()); 737 mAttachInfo.mHardwareAccelerated = 738 mAttachInfo.mHardwareAccelerationRequested = true; 739 } 740 } 741 } 742 } 743 744 public View getView() { 745 return mView; 746 } 747 748 final WindowLeaked getLocation() { 749 return mLocation; 750 } 751 752 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) { 753 synchronized (this) { 754 final int oldInsetLeft = mWindowAttributes.surfaceInsets.left; 755 final int oldInsetTop = mWindowAttributes.surfaceInsets.top; 756 final int oldInsetRight = mWindowAttributes.surfaceInsets.right; 757 final int oldInsetBottom = mWindowAttributes.surfaceInsets.bottom; 758 final int oldSoftInputMode = mWindowAttributes.softInputMode; 759 760 // Keep track of the actual window flags supplied by the client. 761 mClientWindowLayoutFlags = attrs.flags; 762 763 // Preserve compatible window flag if exists. 764 final int compatibleWindowFlag = mWindowAttributes.privateFlags 765 & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW; 766 767 // Transfer over system UI visibility values as they carry current state. 768 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility; 769 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility; 770 771 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs); 772 if ((mWindowAttributesChangesFlag 773 & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) { 774 // Recompute system ui visibility. 775 mAttachInfo.mRecomputeGlobalAttributes = true; 776 } 777 if (mWindowAttributes.packageName == null) { 778 mWindowAttributes.packageName = mBasePackageName; 779 } 780 mWindowAttributes.privateFlags |= compatibleWindowFlag; 781 782 // Restore old surface insets. 783 mWindowAttributes.surfaceInsets.set( 784 oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom); 785 786 applyKeepScreenOnFlag(mWindowAttributes); 787 788 if (newView) { 789 mSoftInputMode = attrs.softInputMode; 790 requestLayout(); 791 } 792 793 // Don't lose the mode we last auto-computed. 794 if ((attrs.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 795 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 796 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode 797 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 798 | (oldSoftInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST); 799 } 800 801 mWindowAttributesChanged = true; 802 scheduleTraversals(); 803 } 804 } 805 806 void handleAppVisibility(boolean visible) { 807 if (mAppVisible != visible) { 808 mAppVisible = visible; 809 scheduleTraversals(); 810 if (!mAppVisible) { 811 WindowManagerGlobal.trimForeground(); 812 } 813 } 814 } 815 816 void handleGetNewSurface() { 817 mNewSurfaceNeeded = true; 818 mFullRedrawNeeded = true; 819 scheduleTraversals(); 820 } 821 822 private final DisplayListener mDisplayListener = new DisplayListener() { 823 @Override 824 public void onDisplayChanged(int displayId) { 825 if (mView != null && mDisplay.getDisplayId() == displayId) { 826 final int oldDisplayState = mAttachInfo.mDisplayState; 827 final int newDisplayState = mDisplay.getState(); 828 if (oldDisplayState != newDisplayState) { 829 mAttachInfo.mDisplayState = newDisplayState; 830 if (oldDisplayState != Display.STATE_UNKNOWN) { 831 final int oldScreenState = toViewScreenState(oldDisplayState); 832 final int newScreenState = toViewScreenState(newDisplayState); 833 if (oldScreenState != newScreenState) { 834 mView.dispatchScreenStateChanged(newScreenState); 835 } 836 if (oldDisplayState == Display.STATE_OFF) { 837 // Draw was suppressed so we need to for it to happen here. 838 mFullRedrawNeeded = true; 839 scheduleTraversals(); 840 } 841 } 842 } 843 } 844 } 845 846 @Override 847 public void onDisplayRemoved(int displayId) { 848 } 849 850 @Override 851 public void onDisplayAdded(int displayId) { 852 } 853 854 private int toViewScreenState(int displayState) { 855 return displayState == Display.STATE_OFF ? 856 View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON; 857 } 858 }; 859 860 @Override 861 public void requestFitSystemWindows() { 862 checkThread(); 863 mApplyInsetsRequested = true; 864 scheduleTraversals(); 865 } 866 867 @Override 868 public void requestLayout() { 869 if (!mHandlingLayoutInLayoutRequest) { 870 checkThread(); 871 mLayoutRequested = true; 872 scheduleTraversals(); 873 } 874 } 875 876 @Override 877 public boolean isLayoutRequested() { 878 return mLayoutRequested; 879 } 880 881 void invalidate() { 882 mDirty.set(0, 0, mWidth, mHeight); 883 if (!mWillDrawSoon) { 884 scheduleTraversals(); 885 } 886 } 887 888 void invalidateWorld(View view) { 889 view.invalidate(); 890 if (view instanceof ViewGroup) { 891 ViewGroup parent = (ViewGroup) view; 892 for (int i = 0; i < parent.getChildCount(); i++) { 893 invalidateWorld(parent.getChildAt(i)); 894 } 895 } 896 } 897 898 @Override 899 public void invalidateChild(View child, Rect dirty) { 900 invalidateChildInParent(null, dirty); 901 } 902 903 @Override 904 public ViewParent invalidateChildInParent(int[] location, Rect dirty) { 905 checkThread(); 906 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty); 907 908 if (dirty == null) { 909 invalidate(); 910 return null; 911 } else if (dirty.isEmpty() && !mIsAnimating) { 912 return null; 913 } 914 915 if (mCurScrollY != 0 || mTranslator != null) { 916 mTempRect.set(dirty); 917 dirty = mTempRect; 918 if (mCurScrollY != 0) { 919 dirty.offset(0, -mCurScrollY); 920 } 921 if (mTranslator != null) { 922 mTranslator.translateRectInAppWindowToScreen(dirty); 923 } 924 if (mAttachInfo.mScalingRequired) { 925 dirty.inset(-1, -1); 926 } 927 } 928 929 final Rect localDirty = mDirty; 930 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) { 931 mAttachInfo.mSetIgnoreDirtyState = true; 932 mAttachInfo.mIgnoreDirtyState = true; 933 } 934 935 // Add the new dirty rect to the current one 936 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom); 937 // Intersect with the bounds of the window to skip 938 // updates that lie outside of the visible region 939 final float appScale = mAttachInfo.mApplicationScale; 940 final boolean intersected = localDirty.intersect(0, 0, 941 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 942 if (!intersected) { 943 localDirty.setEmpty(); 944 } 945 if (!mWillDrawSoon && (intersected || mIsAnimating)) { 946 scheduleTraversals(); 947 } 948 949 return null; 950 } 951 952 void setStopped(boolean stopped) { 953 if (mStopped != stopped) { 954 mStopped = stopped; 955 if (!stopped) { 956 scheduleTraversals(); 957 } 958 } 959 } 960 961 @Override 962 public ViewParent getParent() { 963 return null; 964 } 965 966 @Override 967 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 968 if (child != mView) { 969 throw new RuntimeException("child is not mine, honest!"); 970 } 971 // Note: don't apply scroll offset, because we want to know its 972 // visibility in the virtual canvas being given to the view hierarchy. 973 return r.intersect(0, 0, mWidth, mHeight); 974 } 975 976 @Override 977 public void bringChildToFront(View child) { 978 } 979 980 int getHostVisibility() { 981 return mAppVisible ? mView.getVisibility() : View.GONE; 982 } 983 984 void disposeResizeBuffer() { 985 if (mResizeBuffer != null) { 986 mResizeBuffer.destroy(); 987 mResizeBuffer = null; 988 } 989 } 990 991 /** 992 * Add LayoutTransition to the list of transitions to be started in the next traversal. 993 * This list will be cleared after the transitions on the list are start()'ed. These 994 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup 995 * happens during the layout phase of traversal, which we want to complete before any of the 996 * animations are started (because those animations may side-effect properties that layout 997 * depends upon, like the bounding rectangles of the affected views). So we add the transition 998 * to the list and it is started just prior to starting the drawing phase of traversal. 999 * 1000 * @param transition The LayoutTransition to be started on the next traversal. 1001 * 1002 * @hide 1003 */ 1004 public void requestTransitionStart(LayoutTransition transition) { 1005 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) { 1006 if (mPendingTransitions == null) { 1007 mPendingTransitions = new ArrayList<LayoutTransition>(); 1008 } 1009 mPendingTransitions.add(transition); 1010 } 1011 } 1012 1013 /** 1014 * Notifies the HardwareRenderer that a new frame will be coming soon. 1015 * Currently only {@link ThreadedRenderer} cares about this, and uses 1016 * this knowledge to adjust the scheduling of off-thread animations 1017 */ 1018 void notifyRendererOfFramePending() { 1019 if (mAttachInfo.mHardwareRenderer != null) { 1020 mAttachInfo.mHardwareRenderer.notifyFramePending(); 1021 } 1022 } 1023 1024 void scheduleTraversals() { 1025 if (!mTraversalScheduled) { 1026 mTraversalScheduled = true; 1027 mTraversalBarrier = mHandler.getLooper().postSyncBarrier(); 1028 mChoreographer.postCallback( 1029 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 1030 if (!mUnbufferedInputDispatch) { 1031 scheduleConsumeBatchedInput(); 1032 } 1033 notifyRendererOfFramePending(); 1034 } 1035 } 1036 1037 void unscheduleTraversals() { 1038 if (mTraversalScheduled) { 1039 mTraversalScheduled = false; 1040 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 1041 mChoreographer.removeCallbacks( 1042 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 1043 } 1044 } 1045 1046 void doTraversal() { 1047 if (mTraversalScheduled) { 1048 mTraversalScheduled = false; 1049 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 1050 1051 if (mProfile) { 1052 Debug.startMethodTracing("ViewAncestor"); 1053 } 1054 1055 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals"); 1056 try { 1057 performTraversals(); 1058 } finally { 1059 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 1060 } 1061 1062 if (mProfile) { 1063 Debug.stopMethodTracing(); 1064 mProfile = false; 1065 } 1066 } 1067 } 1068 1069 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) { 1070 // Update window's global keep screen on flag: if a view has requested 1071 // that the screen be kept on, then it is always set; otherwise, it is 1072 // set to whatever the client last requested for the global state. 1073 if (mAttachInfo.mKeepScreenOn) { 1074 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 1075 } else { 1076 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) 1077 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1078 } 1079 } 1080 1081 private boolean collectViewAttributes() { 1082 if (mAttachInfo.mRecomputeGlobalAttributes) { 1083 //Log.i(TAG, "Computing view hierarchy attributes!"); 1084 mAttachInfo.mRecomputeGlobalAttributes = false; 1085 boolean oldScreenOn = mAttachInfo.mKeepScreenOn; 1086 mAttachInfo.mKeepScreenOn = false; 1087 mAttachInfo.mSystemUiVisibility = 0; 1088 mAttachInfo.mHasSystemUiListeners = false; 1089 mView.dispatchCollectViewAttributes(mAttachInfo, 0); 1090 mAttachInfo.mSystemUiVisibility &= ~mAttachInfo.mDisabledSystemUiVisibility; 1091 WindowManager.LayoutParams params = mWindowAttributes; 1092 mAttachInfo.mSystemUiVisibility |= getImpliedSystemUiVisibility(params); 1093 if (mAttachInfo.mKeepScreenOn != oldScreenOn 1094 || mAttachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility 1095 || mAttachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) { 1096 applyKeepScreenOnFlag(params); 1097 params.subtreeSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1098 params.hasSystemUiListeners = mAttachInfo.mHasSystemUiListeners; 1099 mView.dispatchWindowSystemUiVisiblityChanged(mAttachInfo.mSystemUiVisibility); 1100 return true; 1101 } 1102 } 1103 return false; 1104 } 1105 1106 private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) { 1107 int vis = 0; 1108 // Translucent decor window flags imply stable system ui visibility. 1109 if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) { 1110 vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 1111 } 1112 if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) { 1113 vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; 1114 } 1115 return vis; 1116 } 1117 1118 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp, 1119 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) { 1120 int childWidthMeasureSpec; 1121 int childHeightMeasureSpec; 1122 boolean windowSizeMayChange = false; 1123 1124 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG, 1125 "Measuring " + host + " in display " + desiredWindowWidth 1126 + "x" + desiredWindowHeight + "..."); 1127 1128 boolean goodMeasure = false; 1129 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) { 1130 // On large screens, we don't want to allow dialogs to just 1131 // stretch to fill the entire width of the screen to display 1132 // one line of text. First try doing the layout at a smaller 1133 // size to see if it will fit. 1134 final DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1135 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true); 1136 int baseSize = 0; 1137 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) { 1138 baseSize = (int)mTmpValue.getDimension(packageMetrics); 1139 } 1140 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize); 1141 if (baseSize != 0 && desiredWindowWidth > baseSize) { 1142 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1143 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1144 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1145 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1146 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1147 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1148 goodMeasure = true; 1149 } else { 1150 // Didn't fit in that size... try expanding a bit. 1151 baseSize = (baseSize+desiredWindowWidth)/2; 1152 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize=" 1153 + baseSize); 1154 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1155 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1156 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1157 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1158 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1159 if (DEBUG_DIALOG) Log.v(TAG, "Good!"); 1160 goodMeasure = true; 1161 } 1162 } 1163 } 1164 } 1165 1166 if (!goodMeasure) { 1167 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); 1168 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1169 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1170 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) { 1171 windowSizeMayChange = true; 1172 } 1173 } 1174 1175 if (DBG) { 1176 System.out.println("======================================"); 1177 System.out.println("performTraversals -- after measure"); 1178 host.debug(); 1179 } 1180 1181 return windowSizeMayChange; 1182 } 1183 1184 /** 1185 * Modifies the input matrix such that it maps view-local coordinates to 1186 * on-screen coordinates. 1187 * 1188 * @param m input matrix to modify 1189 */ 1190 void transformMatrixToGlobal(Matrix m) { 1191 m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 1192 } 1193 1194 /** 1195 * Modifies the input matrix such that it maps on-screen coordinates to 1196 * view-local coordinates. 1197 * 1198 * @param m input matrix to modify 1199 */ 1200 void transformMatrixToLocal(Matrix m) { 1201 m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop); 1202 } 1203 1204 void dispatchApplyInsets(View host) { 1205 mDispatchContentInsets.set(mAttachInfo.mContentInsets); 1206 mDispatchStableInsets.set(mAttachInfo.mStableInsets); 1207 final boolean isRound = (mIsEmulator && mIsCircularEmulator) || mWindowIsRound; 1208 host.dispatchApplyWindowInsets(new WindowInsets( 1209 mDispatchContentInsets, null /* windowDecorInsets */, 1210 mDispatchStableInsets, isRound)); 1211 } 1212 1213 private void performTraversals() { 1214 // cache mView since it is used so much below... 1215 final View host = mView; 1216 1217 if (DBG) { 1218 System.out.println("======================================"); 1219 System.out.println("performTraversals"); 1220 host.debug(); 1221 } 1222 1223 if (host == null || !mAdded) 1224 return; 1225 1226 mIsInTraversal = true; 1227 mWillDrawSoon = true; 1228 boolean windowSizeMayChange = false; 1229 boolean newSurface = false; 1230 boolean surfaceChanged = false; 1231 WindowManager.LayoutParams lp = mWindowAttributes; 1232 1233 int desiredWindowWidth; 1234 int desiredWindowHeight; 1235 1236 final int viewVisibility = getHostVisibility(); 1237 boolean viewVisibilityChanged = mViewVisibility != viewVisibility 1238 || mNewSurfaceNeeded; 1239 1240 WindowManager.LayoutParams params = null; 1241 if (mWindowAttributesChanged) { 1242 mWindowAttributesChanged = false; 1243 surfaceChanged = true; 1244 params = lp; 1245 } 1246 CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo(); 1247 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) { 1248 params = lp; 1249 mFullRedrawNeeded = true; 1250 mLayoutRequested = true; 1251 if (mLastInCompatMode) { 1252 params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW; 1253 mLastInCompatMode = false; 1254 } else { 1255 params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW; 1256 mLastInCompatMode = true; 1257 } 1258 } 1259 1260 mWindowAttributesChangesFlag = 0; 1261 1262 Rect frame = mWinFrame; 1263 if (mFirst) { 1264 mFullRedrawNeeded = true; 1265 mLayoutRequested = true; 1266 1267 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL 1268 || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) { 1269 // NOTE -- system code, won't try to do compat mode. 1270 Point size = new Point(); 1271 mDisplay.getRealSize(size); 1272 desiredWindowWidth = size.x; 1273 desiredWindowHeight = size.y; 1274 } else { 1275 DisplayMetrics packageMetrics = 1276 mView.getContext().getResources().getDisplayMetrics(); 1277 desiredWindowWidth = packageMetrics.widthPixels; 1278 desiredWindowHeight = packageMetrics.heightPixels; 1279 } 1280 1281 // We used to use the following condition to choose 32 bits drawing caches: 1282 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888 1283 // However, windows are now always 32 bits by default, so choose 32 bits 1284 mAttachInfo.mUse32BitDrawingCache = true; 1285 mAttachInfo.mHasWindowFocus = false; 1286 mAttachInfo.mWindowVisibility = viewVisibility; 1287 mAttachInfo.mRecomputeGlobalAttributes = false; 1288 viewVisibilityChanged = false; 1289 mLastConfiguration.setTo(host.getResources().getConfiguration()); 1290 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1291 // Set the layout direction if it has not been set before (inherit is the default) 1292 if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 1293 host.setLayoutDirection(mLastConfiguration.getLayoutDirection()); 1294 } 1295 host.dispatchAttachedToWindow(mAttachInfo, 0); 1296 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true); 1297 dispatchApplyInsets(host); 1298 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn); 1299 1300 } else { 1301 desiredWindowWidth = frame.width(); 1302 desiredWindowHeight = frame.height(); 1303 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) { 1304 if (DEBUG_ORIENTATION) Log.v(TAG, 1305 "View " + host + " resized to: " + frame); 1306 mFullRedrawNeeded = true; 1307 mLayoutRequested = true; 1308 windowSizeMayChange = true; 1309 } 1310 } 1311 1312 if (viewVisibilityChanged) { 1313 mAttachInfo.mWindowVisibility = viewVisibility; 1314 host.dispatchWindowVisibilityChanged(viewVisibility); 1315 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) { 1316 destroyHardwareResources(); 1317 } 1318 if (viewVisibility == View.GONE) { 1319 // After making a window gone, we will count it as being 1320 // shown for the first time the next time it gets focus. 1321 mHasHadWindowFocus = false; 1322 } 1323 } 1324 1325 // Execute enqueued actions on every traversal in case a detached view enqueued an action 1326 getRunQueue().executeActions(mAttachInfo.mHandler); 1327 1328 boolean insetsChanged = false; 1329 1330 boolean layoutRequested = mLayoutRequested && !mStopped; 1331 if (layoutRequested) { 1332 1333 final Resources res = mView.getContext().getResources(); 1334 1335 if (mFirst) { 1336 // make sure touch mode code executes by setting cached value 1337 // to opposite of the added touch mode. 1338 mAttachInfo.mInTouchMode = !mAddedTouchMode; 1339 ensureTouchModeLocally(mAddedTouchMode); 1340 } else { 1341 if (!mPendingOverscanInsets.equals(mAttachInfo.mOverscanInsets)) { 1342 insetsChanged = true; 1343 } 1344 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) { 1345 insetsChanged = true; 1346 } 1347 if (!mPendingStableInsets.equals(mAttachInfo.mStableInsets)) { 1348 insetsChanged = true; 1349 } 1350 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) { 1351 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1352 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1353 + mAttachInfo.mVisibleInsets); 1354 } 1355 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT 1356 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) { 1357 windowSizeMayChange = true; 1358 1359 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL 1360 || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) { 1361 // NOTE -- system code, won't try to do compat mode. 1362 Point size = new Point(); 1363 mDisplay.getRealSize(size); 1364 desiredWindowWidth = size.x; 1365 desiredWindowHeight = size.y; 1366 } else { 1367 DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1368 desiredWindowWidth = packageMetrics.widthPixels; 1369 desiredWindowHeight = packageMetrics.heightPixels; 1370 } 1371 } 1372 } 1373 1374 // Ask host how big it wants to be 1375 windowSizeMayChange |= measureHierarchy(host, lp, res, 1376 desiredWindowWidth, desiredWindowHeight); 1377 } 1378 1379 if (collectViewAttributes()) { 1380 params = lp; 1381 } 1382 if (mAttachInfo.mForceReportNewAttributes) { 1383 mAttachInfo.mForceReportNewAttributes = false; 1384 params = lp; 1385 } 1386 1387 if (mFirst || mAttachInfo.mViewVisibilityChanged) { 1388 mAttachInfo.mViewVisibilityChanged = false; 1389 int resizeMode = mSoftInputMode & 1390 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST; 1391 // If we are in auto resize mode, then we need to determine 1392 // what mode to use now. 1393 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 1394 final int N = mAttachInfo.mScrollContainers.size(); 1395 for (int i=0; i<N; i++) { 1396 if (mAttachInfo.mScrollContainers.get(i).isShown()) { 1397 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; 1398 } 1399 } 1400 if (resizeMode == 0) { 1401 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN; 1402 } 1403 if ((lp.softInputMode & 1404 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) { 1405 lp.softInputMode = (lp.softInputMode & 1406 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) | 1407 resizeMode; 1408 params = lp; 1409 } 1410 } 1411 } 1412 1413 if (params != null) { 1414 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 1415 if (!PixelFormat.formatHasAlpha(params.format)) { 1416 params.format = PixelFormat.TRANSLUCENT; 1417 } 1418 } 1419 mAttachInfo.mOverscanRequested = (params.flags 1420 & WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN) != 0; 1421 } 1422 1423 if (mApplyInsetsRequested) { 1424 mApplyInsetsRequested = false; 1425 mLastOverscanRequested = mAttachInfo.mOverscanRequested; 1426 dispatchApplyInsets(host); 1427 if (mLayoutRequested) { 1428 // Short-circuit catching a new layout request here, so 1429 // we don't need to go through two layout passes when things 1430 // change due to fitting system windows, which can happen a lot. 1431 windowSizeMayChange |= measureHierarchy(host, lp, 1432 mView.getContext().getResources(), 1433 desiredWindowWidth, desiredWindowHeight); 1434 } 1435 } 1436 1437 if (layoutRequested) { 1438 // Clear this now, so that if anything requests a layout in the 1439 // rest of this function we will catch it and re-run a full 1440 // layout pass. 1441 mLayoutRequested = false; 1442 } 1443 1444 boolean windowShouldResize = layoutRequested && windowSizeMayChange 1445 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) 1446 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT && 1447 frame.width() < desiredWindowWidth && frame.width() != mWidth) 1448 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT && 1449 frame.height() < desiredWindowHeight && frame.height() != mHeight)); 1450 1451 // Determine whether to compute insets. 1452 // If there are no inset listeners remaining then we may still need to compute 1453 // insets in case the old insets were non-empty and must be reset. 1454 final boolean computesInternalInsets = 1455 mAttachInfo.mTreeObserver.hasComputeInternalInsetsListeners() 1456 || mAttachInfo.mHasNonEmptyGivenInternalInsets; 1457 1458 boolean insetsPending = false; 1459 int relayoutResult = 0; 1460 1461 if (mFirst || windowShouldResize || insetsChanged || 1462 viewVisibilityChanged || params != null) { 1463 1464 if (viewVisibility == View.VISIBLE) { 1465 // If this window is giving internal insets to the window 1466 // manager, and it is being added or changing its visibility, 1467 // then we want to first give the window manager "fake" 1468 // insets to cause it to effectively ignore the content of 1469 // the window during layout. This avoids it briefly causing 1470 // other windows to resize/move based on the raw frame of the 1471 // window, waiting until we can finish laying out this window 1472 // and get back to the window manager with the ultimately 1473 // computed insets. 1474 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged); 1475 } 1476 1477 if (mSurfaceHolder != null) { 1478 mSurfaceHolder.mSurfaceLock.lock(); 1479 mDrawingAllowed = true; 1480 } 1481 1482 boolean hwInitialized = false; 1483 boolean contentInsetsChanged = false; 1484 boolean hadSurface = mSurface.isValid(); 1485 1486 try { 1487 if (DEBUG_LAYOUT) { 1488 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" + 1489 host.getMeasuredHeight() + ", params=" + params); 1490 } 1491 1492 if (mAttachInfo.mHardwareRenderer != null) { 1493 // relayoutWindow may decide to destroy mSurface. As that decision 1494 // happens in WindowManager service, we need to be defensive here 1495 // and stop using the surface in case it gets destroyed. 1496 mAttachInfo.mHardwareRenderer.pauseSurface(mSurface); 1497 } 1498 final int surfaceGenerationId = mSurface.getGenerationId(); 1499 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending); 1500 if (!mDrawDuringWindowsAnimating && 1501 (relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) { 1502 mWindowsAnimating = true; 1503 } 1504 1505 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString() 1506 + " overscan=" + mPendingOverscanInsets.toShortString() 1507 + " content=" + mPendingContentInsets.toShortString() 1508 + " visible=" + mPendingVisibleInsets.toShortString() 1509 + " visible=" + mPendingStableInsets.toShortString() 1510 + " surface=" + mSurface); 1511 1512 if (mPendingConfiguration.seq != 0) { 1513 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: " 1514 + mPendingConfiguration); 1515 updateConfiguration(mPendingConfiguration, !mFirst); 1516 mPendingConfiguration.seq = 0; 1517 } 1518 1519 final boolean overscanInsetsChanged = !mPendingOverscanInsets.equals( 1520 mAttachInfo.mOverscanInsets); 1521 contentInsetsChanged = !mPendingContentInsets.equals( 1522 mAttachInfo.mContentInsets); 1523 final boolean visibleInsetsChanged = !mPendingVisibleInsets.equals( 1524 mAttachInfo.mVisibleInsets); 1525 final boolean stableInsetsChanged = !mPendingStableInsets.equals( 1526 mAttachInfo.mStableInsets); 1527 if (contentInsetsChanged) { 1528 if (mWidth > 0 && mHeight > 0 && lp != null && 1529 ((lp.systemUiVisibility|lp.subtreeSystemUiVisibility) 1530 & View.SYSTEM_UI_LAYOUT_FLAGS) == 0 && 1531 mSurface != null && mSurface.isValid() && 1532 !mAttachInfo.mTurnOffWindowResizeAnim && 1533 mAttachInfo.mHardwareRenderer != null && 1534 mAttachInfo.mHardwareRenderer.isEnabled() && 1535 lp != null && !PixelFormat.formatHasAlpha(lp.format) 1536 && !mBlockResizeBuffer) { 1537 1538 disposeResizeBuffer(); 1539 1540// TODO: Again.... 1541// if (mResizeBuffer == null) { 1542// mResizeBuffer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 1543// mWidth, mHeight); 1544// } 1545// mResizeBuffer.prepare(mWidth, mHeight, false); 1546// RenderNode layerRenderNode = mResizeBuffer.startRecording(); 1547// HardwareCanvas layerCanvas = layerRenderNode.start(mWidth, mHeight); 1548// try { 1549// final int restoreCount = layerCanvas.save(); 1550// 1551// int yoff; 1552// final boolean scrolling = mScroller != null 1553// && mScroller.computeScrollOffset(); 1554// if (scrolling) { 1555// yoff = mScroller.getCurrY(); 1556// mScroller.abortAnimation(); 1557// } else { 1558// yoff = mScrollY; 1559// } 1560// 1561// layerCanvas.translate(0, -yoff); 1562// if (mTranslator != null) { 1563// mTranslator.translateCanvas(layerCanvas); 1564// } 1565// 1566// RenderNode renderNode = mView.mRenderNode; 1567// if (renderNode != null && renderNode.isValid()) { 1568// layerCanvas.drawDisplayList(renderNode, null, 1569// RenderNode.FLAG_CLIP_CHILDREN); 1570// } else { 1571// mView.draw(layerCanvas); 1572// } 1573// 1574// drawAccessibilityFocusedDrawableIfNeeded(layerCanvas); 1575// 1576// mResizeBufferStartTime = SystemClock.uptimeMillis(); 1577// mResizeBufferDuration = mView.getResources().getInteger( 1578// com.android.internal.R.integer.config_mediumAnimTime); 1579// 1580// layerCanvas.restoreToCount(restoreCount); 1581// layerRenderNode.end(layerCanvas); 1582// layerRenderNode.setCaching(true); 1583// layerRenderNode.setLeftTopRightBottom(0, 0, mWidth, mHeight); 1584// mTempRect.set(0, 0, mWidth, mHeight); 1585// } finally { 1586// mResizeBuffer.endRecording(mTempRect); 1587// } 1588// mAttachInfo.mHardwareRenderer.flushLayerUpdates(); 1589 } 1590 mAttachInfo.mContentInsets.set(mPendingContentInsets); 1591 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: " 1592 + mAttachInfo.mContentInsets); 1593 } 1594 if (overscanInsetsChanged) { 1595 mAttachInfo.mOverscanInsets.set(mPendingOverscanInsets); 1596 if (DEBUG_LAYOUT) Log.v(TAG, "Overscan insets changing to: " 1597 + mAttachInfo.mOverscanInsets); 1598 // Need to relayout with content insets. 1599 contentInsetsChanged = true; 1600 } 1601 if (stableInsetsChanged) { 1602 mAttachInfo.mStableInsets.set(mPendingStableInsets); 1603 if (DEBUG_LAYOUT) Log.v(TAG, "Decor insets changing to: " 1604 + mAttachInfo.mStableInsets); 1605 // Need to relayout with content insets. 1606 contentInsetsChanged = true; 1607 } 1608 if (contentInsetsChanged || mLastSystemUiVisibility != 1609 mAttachInfo.mSystemUiVisibility || mApplyInsetsRequested 1610 || mLastOverscanRequested != mAttachInfo.mOverscanRequested) { 1611 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1612 mLastOverscanRequested = mAttachInfo.mOverscanRequested; 1613 mApplyInsetsRequested = false; 1614 dispatchApplyInsets(host); 1615 } 1616 if (visibleInsetsChanged) { 1617 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1618 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1619 + mAttachInfo.mVisibleInsets); 1620 } 1621 1622 if (!hadSurface) { 1623 if (mSurface.isValid()) { 1624 // If we are creating a new surface, then we need to 1625 // completely redraw it. Also, when we get to the 1626 // point of drawing it we will hold off and schedule 1627 // a new traversal instead. This is so we can tell the 1628 // window manager about all of the windows being displayed 1629 // before actually drawing them, so it can display then 1630 // all at once. 1631 newSurface = true; 1632 mFullRedrawNeeded = true; 1633 mPreviousTransparentRegion.setEmpty(); 1634 1635 if (mAttachInfo.mHardwareRenderer != null) { 1636 try { 1637 hwInitialized = mAttachInfo.mHardwareRenderer.initialize( 1638 mSurface); 1639 } catch (OutOfResourcesException e) { 1640 handleOutOfResourcesException(e); 1641 return; 1642 } 1643 } 1644 } 1645 } else if (!mSurface.isValid()) { 1646 // If the surface has been removed, then reset the scroll 1647 // positions. 1648 if (mLastScrolledFocus != null) { 1649 mLastScrolledFocus.clear(); 1650 } 1651 mScrollY = mCurScrollY = 0; 1652 if (mView instanceof RootViewSurfaceTaker) { 1653 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY); 1654 } 1655 if (mScroller != null) { 1656 mScroller.abortAnimation(); 1657 } 1658 disposeResizeBuffer(); 1659 // Our surface is gone 1660 if (mAttachInfo.mHardwareRenderer != null && 1661 mAttachInfo.mHardwareRenderer.isEnabled()) { 1662 mAttachInfo.mHardwareRenderer.destroy(); 1663 } 1664 } else if (surfaceGenerationId != mSurface.getGenerationId() && 1665 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) { 1666 mFullRedrawNeeded = true; 1667 try { 1668 mAttachInfo.mHardwareRenderer.updateSurface(mSurface); 1669 } catch (OutOfResourcesException e) { 1670 handleOutOfResourcesException(e); 1671 return; 1672 } 1673 } 1674 } catch (RemoteException e) { 1675 } 1676 1677 if (DEBUG_ORIENTATION) Log.v( 1678 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface); 1679 1680 mAttachInfo.mWindowLeft = frame.left; 1681 mAttachInfo.mWindowTop = frame.top; 1682 1683 // !!FIXME!! This next section handles the case where we did not get the 1684 // window size we asked for. We should avoid this by getting a maximum size from 1685 // the window session beforehand. 1686 if (mWidth != frame.width() || mHeight != frame.height()) { 1687 mWidth = frame.width(); 1688 mHeight = frame.height(); 1689 } 1690 1691 if (mSurfaceHolder != null) { 1692 // The app owns the surface; tell it about what is going on. 1693 if (mSurface.isValid()) { 1694 // XXX .copyFrom() doesn't work! 1695 //mSurfaceHolder.mSurface.copyFrom(mSurface); 1696 mSurfaceHolder.mSurface = mSurface; 1697 } 1698 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight); 1699 mSurfaceHolder.mSurfaceLock.unlock(); 1700 if (mSurface.isValid()) { 1701 if (!hadSurface) { 1702 mSurfaceHolder.ungetCallbacks(); 1703 1704 mIsCreating = true; 1705 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder); 1706 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1707 if (callbacks != null) { 1708 for (SurfaceHolder.Callback c : callbacks) { 1709 c.surfaceCreated(mSurfaceHolder); 1710 } 1711 } 1712 surfaceChanged = true; 1713 } 1714 if (surfaceChanged) { 1715 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder, 1716 lp.format, mWidth, mHeight); 1717 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1718 if (callbacks != null) { 1719 for (SurfaceHolder.Callback c : callbacks) { 1720 c.surfaceChanged(mSurfaceHolder, lp.format, 1721 mWidth, mHeight); 1722 } 1723 } 1724 } 1725 mIsCreating = false; 1726 } else if (hadSurface) { 1727 mSurfaceHolder.ungetCallbacks(); 1728 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1729 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder); 1730 if (callbacks != null) { 1731 for (SurfaceHolder.Callback c : callbacks) { 1732 c.surfaceDestroyed(mSurfaceHolder); 1733 } 1734 } 1735 mSurfaceHolder.mSurfaceLock.lock(); 1736 try { 1737 mSurfaceHolder.mSurface = new Surface(); 1738 } finally { 1739 mSurfaceHolder.mSurfaceLock.unlock(); 1740 } 1741 } 1742 } 1743 1744 if (mAttachInfo.mHardwareRenderer != null && 1745 mAttachInfo.mHardwareRenderer.isEnabled()) { 1746 if (hwInitialized || 1747 mWidth != mAttachInfo.mHardwareRenderer.getWidth() || 1748 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) { 1749 mAttachInfo.mHardwareRenderer.setup( 1750 mWidth, mHeight, mWindowAttributes.surfaceInsets); 1751 if (!hwInitialized) { 1752 mAttachInfo.mHardwareRenderer.invalidate(mSurface); 1753 mFullRedrawNeeded = true; 1754 } 1755 } 1756 } 1757 1758 if (!mStopped) { 1759 boolean focusChangedDueToTouchMode = ensureTouchModeLocally( 1760 (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0); 1761 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth() 1762 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) { 1763 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); 1764 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height); 1765 1766 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth=" 1767 + mWidth + " measuredWidth=" + host.getMeasuredWidth() 1768 + " mHeight=" + mHeight 1769 + " measuredHeight=" + host.getMeasuredHeight() 1770 + " coveredInsetsChanged=" + contentInsetsChanged); 1771 1772 // Ask host how big it wants to be 1773 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1774 1775 // Implementation of weights from WindowManager.LayoutParams 1776 // We just grow the dimensions as needed and re-measure if 1777 // needs be 1778 int width = host.getMeasuredWidth(); 1779 int height = host.getMeasuredHeight(); 1780 boolean measureAgain = false; 1781 1782 if (lp.horizontalWeight > 0.0f) { 1783 width += (int) ((mWidth - width) * lp.horizontalWeight); 1784 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, 1785 MeasureSpec.EXACTLY); 1786 measureAgain = true; 1787 } 1788 if (lp.verticalWeight > 0.0f) { 1789 height += (int) ((mHeight - height) * lp.verticalWeight); 1790 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, 1791 MeasureSpec.EXACTLY); 1792 measureAgain = true; 1793 } 1794 1795 if (measureAgain) { 1796 if (DEBUG_LAYOUT) Log.v(TAG, 1797 "And hey let's measure once more: width=" + width 1798 + " height=" + height); 1799 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1800 } 1801 1802 layoutRequested = true; 1803 } 1804 } 1805 } else { 1806 // Not the first pass and no window/insets/visibility change but the window 1807 // may have moved and we need check that and if so to update the left and right 1808 // in the attach info. We translate only the window frame since on window move 1809 // the window manager tells us only for the new frame but the insets are the 1810 // same and we do not want to translate them more than once. 1811 1812 // TODO: Well, we are checking whether the frame has changed similarly 1813 // to how this is done for the insets. This is however incorrect since 1814 // the insets and the frame are translated. For example, the old frame 1815 // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new 1816 // reported frame is (2, 2 - 2, 2) which implies no change but this is not 1817 // true since we are comparing a not translated value to a translated one. 1818 // This scenario is rare but we may want to fix that. 1819 1820 final boolean windowMoved = (mAttachInfo.mWindowLeft != frame.left 1821 || mAttachInfo.mWindowTop != frame.top); 1822 if (windowMoved) { 1823 if (mTranslator != null) { 1824 mTranslator.translateRectInScreenToAppWinFrame(frame); 1825 } 1826 mAttachInfo.mWindowLeft = frame.left; 1827 mAttachInfo.mWindowTop = frame.top; 1828 } 1829 } 1830 1831 final boolean didLayout = layoutRequested && !mStopped; 1832 boolean triggerGlobalLayoutListener = didLayout 1833 || mAttachInfo.mRecomputeGlobalAttributes; 1834 if (didLayout) { 1835 performLayout(lp, desiredWindowWidth, desiredWindowHeight); 1836 1837 // By this point all views have been sized and positioned 1838 // We can compute the transparent area 1839 1840 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 1841 // start out transparent 1842 // TODO: AVOID THAT CALL BY CACHING THE RESULT? 1843 host.getLocationInWindow(mTmpLocation); 1844 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1], 1845 mTmpLocation[0] + host.mRight - host.mLeft, 1846 mTmpLocation[1] + host.mBottom - host.mTop); 1847 1848 host.gatherTransparentRegion(mTransparentRegion); 1849 if (mTranslator != null) { 1850 mTranslator.translateRegionInWindowToScreen(mTransparentRegion); 1851 } 1852 1853 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) { 1854 mPreviousTransparentRegion.set(mTransparentRegion); 1855 mFullRedrawNeeded = true; 1856 // reconfigure window manager 1857 try { 1858 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion); 1859 } catch (RemoteException e) { 1860 } 1861 } 1862 } 1863 1864 if (DBG) { 1865 System.out.println("======================================"); 1866 System.out.println("performTraversals -- after setFrame"); 1867 host.debug(); 1868 } 1869 } 1870 1871 if (triggerGlobalLayoutListener) { 1872 mAttachInfo.mRecomputeGlobalAttributes = false; 1873 mAttachInfo.mTreeObserver.dispatchOnGlobalLayout(); 1874 } 1875 1876 if (computesInternalInsets) { 1877 // Clear the original insets. 1878 final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets; 1879 insets.reset(); 1880 1881 // Compute new insets in place. 1882 mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets); 1883 mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty(); 1884 1885 // Tell the window manager. 1886 if (insetsPending || !mLastGivenInsets.equals(insets)) { 1887 mLastGivenInsets.set(insets); 1888 1889 // Translate insets to screen coordinates if needed. 1890 final Rect contentInsets; 1891 final Rect visibleInsets; 1892 final Region touchableRegion; 1893 if (mTranslator != null) { 1894 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets); 1895 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets); 1896 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion); 1897 } else { 1898 contentInsets = insets.contentInsets; 1899 visibleInsets = insets.visibleInsets; 1900 touchableRegion = insets.touchableRegion; 1901 } 1902 1903 try { 1904 mWindowSession.setInsets(mWindow, insets.mTouchableInsets, 1905 contentInsets, visibleInsets, touchableRegion); 1906 } catch (RemoteException e) { 1907 } 1908 } 1909 } 1910 1911 boolean skipDraw = false; 1912 1913 if (mFirst) { 1914 // handle first focus request 1915 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()=" 1916 + mView.hasFocus()); 1917 if (mView != null) { 1918 if (!mView.hasFocus()) { 1919 mView.requestFocus(View.FOCUS_FORWARD); 1920 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view=" 1921 + mView.findFocus()); 1922 } else { 1923 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view=" 1924 + mView.findFocus()); 1925 } 1926 } 1927 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) { 1928 // The first time we relayout the window, if the system is 1929 // doing window animations, we want to hold of on any future 1930 // draws until the animation is done. 1931 mWindowsAnimating = true; 1932 } 1933 } else if (mWindowsAnimating) { 1934 skipDraw = true; 1935 } 1936 1937 mFirst = false; 1938 mWillDrawSoon = false; 1939 mNewSurfaceNeeded = false; 1940 mViewVisibility = viewVisibility; 1941 1942 if (mAttachInfo.mHasWindowFocus && !isInLocalFocusMode()) { 1943 final boolean imTarget = WindowManager.LayoutParams 1944 .mayUseInputMethod(mWindowAttributes.flags); 1945 if (imTarget != mLastWasImTarget) { 1946 mLastWasImTarget = imTarget; 1947 InputMethodManager imm = InputMethodManager.peekInstance(); 1948 if (imm != null && imTarget) { 1949 imm.startGettingWindowFocus(mView); 1950 imm.onWindowFocus(mView, mView.findFocus(), 1951 mWindowAttributes.softInputMode, 1952 !mHasHadWindowFocus, mWindowAttributes.flags); 1953 } 1954 } 1955 } 1956 1957 // Remember if we must report the next draw. 1958 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 1959 mReportNextDraw = true; 1960 } 1961 1962 boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() || 1963 viewVisibility != View.VISIBLE; 1964 1965 if (!cancelDraw && !newSurface) { 1966 if (!skipDraw || mReportNextDraw) { 1967 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1968 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1969 mPendingTransitions.get(i).startChangingAnimations(); 1970 } 1971 mPendingTransitions.clear(); 1972 } 1973 1974 performDraw(); 1975 } 1976 } else { 1977 if (viewVisibility == View.VISIBLE) { 1978 // Try again 1979 scheduleTraversals(); 1980 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1981 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1982 mPendingTransitions.get(i).endChangingAnimations(); 1983 } 1984 mPendingTransitions.clear(); 1985 } 1986 } 1987 1988 mIsInTraversal = false; 1989 } 1990 1991 private void handleOutOfResourcesException(Surface.OutOfResourcesException e) { 1992 Log.e(TAG, "OutOfResourcesException initializing HW surface", e); 1993 try { 1994 if (!mWindowSession.outOfMemory(mWindow) && 1995 Process.myUid() != Process.SYSTEM_UID) { 1996 Slog.w(TAG, "No processes killed for memory; killing self"); 1997 Process.killProcess(Process.myPid()); 1998 } 1999 } catch (RemoteException ex) { 2000 } 2001 mLayoutRequested = true; // ask wm for a new surface next time. 2002 } 2003 2004 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) { 2005 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure"); 2006 try { 2007 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); 2008 } finally { 2009 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2010 } 2011 } 2012 2013 /** 2014 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy 2015 * is currently undergoing a layout pass. 2016 * 2017 * @return whether the view hierarchy is currently undergoing a layout pass 2018 */ 2019 boolean isInLayout() { 2020 return mInLayout; 2021 } 2022 2023 /** 2024 * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently 2025 * undergoing a layout pass. requestLayout() should not generally be called during layout, 2026 * unless the container hierarchy knows what it is doing (i.e., it is fine as long as 2027 * all children in that container hierarchy are measured and laid out at the end of the layout 2028 * pass for that container). If requestLayout() is called anyway, we handle it correctly 2029 * by registering all requesters during a frame as it proceeds. At the end of the frame, 2030 * we check all of those views to see if any still have pending layout requests, which 2031 * indicates that they were not correctly handled by their container hierarchy. If that is 2032 * the case, we clear all such flags in the tree, to remove the buggy flag state that leads 2033 * to blank containers, and force a second request/measure/layout pass in this frame. If 2034 * more requestLayout() calls are received during that second layout pass, we post those 2035 * requests to the next frame to avoid possible infinite loops. 2036 * 2037 * <p>The return value from this method indicates whether the request should proceed 2038 * (if it is a request during the first layout pass) or should be skipped and posted to the 2039 * next frame (if it is a request during the second layout pass).</p> 2040 * 2041 * @param view the view that requested the layout. 2042 * 2043 * @return true if request should proceed, false otherwise. 2044 */ 2045 boolean requestLayoutDuringLayout(final View view) { 2046 if (view.mParent == null || view.mAttachInfo == null) { 2047 // Would not normally trigger another layout, so just let it pass through as usual 2048 return true; 2049 } 2050 if (!mLayoutRequesters.contains(view)) { 2051 mLayoutRequesters.add(view); 2052 } 2053 if (!mHandlingLayoutInLayoutRequest) { 2054 // Let the request proceed normally; it will be processed in a second layout pass 2055 // if necessary 2056 return true; 2057 } else { 2058 // Don't let the request proceed during the second layout pass. 2059 // It will post to the next frame instead. 2060 return false; 2061 } 2062 } 2063 2064 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth, 2065 int desiredWindowHeight) { 2066 mLayoutRequested = false; 2067 mScrollMayChange = true; 2068 mInLayout = true; 2069 2070 final View host = mView; 2071 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) { 2072 Log.v(TAG, "Laying out " + host + " to (" + 2073 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")"); 2074 } 2075 2076 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout"); 2077 try { 2078 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 2079 2080 mInLayout = false; 2081 int numViewsRequestingLayout = mLayoutRequesters.size(); 2082 if (numViewsRequestingLayout > 0) { 2083 // requestLayout() was called during layout. 2084 // If no layout-request flags are set on the requesting views, there is no problem. 2085 // If some requests are still pending, then we need to clear those flags and do 2086 // a full request/measure/layout pass to handle this situation. 2087 ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, 2088 false); 2089 if (validLayoutRequesters != null) { 2090 // Set this flag to indicate that any further requests are happening during 2091 // the second pass, which may result in posting those requests to the next 2092 // frame instead 2093 mHandlingLayoutInLayoutRequest = true; 2094 2095 // Process fresh layout requests, then measure and layout 2096 int numValidRequests = validLayoutRequesters.size(); 2097 for (int i = 0; i < numValidRequests; ++i) { 2098 final View view = validLayoutRequesters.get(i); 2099 Log.w("View", "requestLayout() improperly called by " + view + 2100 " during layout: running second layout pass"); 2101 view.requestLayout(); 2102 } 2103 measureHierarchy(host, lp, mView.getContext().getResources(), 2104 desiredWindowWidth, desiredWindowHeight); 2105 mInLayout = true; 2106 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 2107 2108 mHandlingLayoutInLayoutRequest = false; 2109 2110 // Check the valid requests again, this time without checking/clearing the 2111 // layout flags, since requests happening during the second pass get noop'd 2112 validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true); 2113 if (validLayoutRequesters != null) { 2114 final ArrayList<View> finalRequesters = validLayoutRequesters; 2115 // Post second-pass requests to the next frame 2116 getRunQueue().post(new Runnable() { 2117 @Override 2118 public void run() { 2119 int numValidRequests = finalRequesters.size(); 2120 for (int i = 0; i < numValidRequests; ++i) { 2121 final View view = finalRequesters.get(i); 2122 Log.w("View", "requestLayout() improperly called by " + view + 2123 " during second layout pass: posting in next frame"); 2124 view.requestLayout(); 2125 } 2126 } 2127 }); 2128 } 2129 } 2130 2131 } 2132 } finally { 2133 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2134 } 2135 mInLayout = false; 2136 } 2137 2138 /** 2139 * This method is called during layout when there have been calls to requestLayout() during 2140 * layout. It walks through the list of views that requested layout to determine which ones 2141 * still need it, based on visibility in the hierarchy and whether they have already been 2142 * handled (as is usually the case with ListView children). 2143 * 2144 * @param layoutRequesters The list of views that requested layout during layout 2145 * @param secondLayoutRequests Whether the requests were issued during the second layout pass. 2146 * If so, the FORCE_LAYOUT flag was not set on requesters. 2147 * @return A list of the actual views that still need to be laid out. 2148 */ 2149 private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters, 2150 boolean secondLayoutRequests) { 2151 2152 int numViewsRequestingLayout = layoutRequesters.size(); 2153 ArrayList<View> validLayoutRequesters = null; 2154 for (int i = 0; i < numViewsRequestingLayout; ++i) { 2155 View view = layoutRequesters.get(i); 2156 if (view != null && view.mAttachInfo != null && view.mParent != null && 2157 (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == 2158 View.PFLAG_FORCE_LAYOUT)) { 2159 boolean gone = false; 2160 View parent = view; 2161 // Only trigger new requests for views in a non-GONE hierarchy 2162 while (parent != null) { 2163 if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) { 2164 gone = true; 2165 break; 2166 } 2167 if (parent.mParent instanceof View) { 2168 parent = (View) parent.mParent; 2169 } else { 2170 parent = null; 2171 } 2172 } 2173 if (!gone) { 2174 if (validLayoutRequesters == null) { 2175 validLayoutRequesters = new ArrayList<View>(); 2176 } 2177 validLayoutRequesters.add(view); 2178 } 2179 } 2180 } 2181 if (!secondLayoutRequests) { 2182 // If we're checking the layout flags, then we need to clean them up also 2183 for (int i = 0; i < numViewsRequestingLayout; ++i) { 2184 View view = layoutRequesters.get(i); 2185 while (view != null && 2186 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) { 2187 view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT; 2188 if (view.mParent instanceof View) { 2189 view = (View) view.mParent; 2190 } else { 2191 view = null; 2192 } 2193 } 2194 } 2195 } 2196 layoutRequesters.clear(); 2197 return validLayoutRequesters; 2198 } 2199 2200 @Override 2201 public void requestTransparentRegion(View child) { 2202 // the test below should not fail unless someone is messing with us 2203 checkThread(); 2204 if (mView == child) { 2205 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS; 2206 // Need to make sure we re-evaluate the window attributes next 2207 // time around, to ensure the window has the correct format. 2208 mWindowAttributesChanged = true; 2209 mWindowAttributesChangesFlag = 0; 2210 requestLayout(); 2211 } 2212 } 2213 2214 /** 2215 * Figures out the measure spec for the root view in a window based on it's 2216 * layout params. 2217 * 2218 * @param windowSize 2219 * The available width or height of the window 2220 * 2221 * @param rootDimension 2222 * The layout params for one dimension (width or height) of the 2223 * window. 2224 * 2225 * @return The measure spec to use to measure the root view. 2226 */ 2227 private static int getRootMeasureSpec(int windowSize, int rootDimension) { 2228 int measureSpec; 2229 switch (rootDimension) { 2230 2231 case ViewGroup.LayoutParams.MATCH_PARENT: 2232 // Window can't resize. Force root view to be windowSize. 2233 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); 2234 break; 2235 case ViewGroup.LayoutParams.WRAP_CONTENT: 2236 // Window can resize. Set max size for root view. 2237 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST); 2238 break; 2239 default: 2240 // Window wants to be an exact size. Force root view to be that size. 2241 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY); 2242 break; 2243 } 2244 return measureSpec; 2245 } 2246 2247 int mHardwareXOffset; 2248 int mHardwareYOffset; 2249 int mResizeAlpha; 2250 final Paint mResizePaint = new Paint(); 2251 2252 @Override 2253 public void onHardwarePreDraw(HardwareCanvas canvas) { 2254 canvas.translate(-mHardwareXOffset, -mHardwareYOffset); 2255 } 2256 2257 @Override 2258 public void onHardwarePostDraw(HardwareCanvas canvas) { 2259 if (mResizeBuffer != null) { 2260 mResizePaint.setAlpha(mResizeAlpha); 2261 canvas.drawHardwareLayer(mResizeBuffer, mHardwareXOffset, mHardwareYOffset, 2262 mResizePaint); 2263 } 2264 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2265 } 2266 2267 /** 2268 * @hide 2269 */ 2270 void outputDisplayList(View view) { 2271 RenderNode renderNode = view.getDisplayList(); 2272 if (renderNode != null) { 2273 renderNode.output(); 2274 } 2275 } 2276 2277 /** 2278 * @see #PROPERTY_PROFILE_RENDERING 2279 */ 2280 private void profileRendering(boolean enabled) { 2281 if (mProfileRendering) { 2282 mRenderProfilingEnabled = enabled; 2283 2284 if (mRenderProfiler != null) { 2285 mChoreographer.removeFrameCallback(mRenderProfiler); 2286 } 2287 if (mRenderProfilingEnabled) { 2288 if (mRenderProfiler == null) { 2289 mRenderProfiler = new Choreographer.FrameCallback() { 2290 @Override 2291 public void doFrame(long frameTimeNanos) { 2292 mDirty.set(0, 0, mWidth, mHeight); 2293 scheduleTraversals(); 2294 if (mRenderProfilingEnabled) { 2295 mChoreographer.postFrameCallback(mRenderProfiler); 2296 } 2297 } 2298 }; 2299 } 2300 mChoreographer.postFrameCallback(mRenderProfiler); 2301 } else { 2302 mRenderProfiler = null; 2303 } 2304 } 2305 } 2306 2307 /** 2308 * Called from draw() when DEBUG_FPS is enabled 2309 */ 2310 private void trackFPS() { 2311 // Tracks frames per second drawn. First value in a series of draws may be bogus 2312 // because it down not account for the intervening idle time 2313 long nowTime = System.currentTimeMillis(); 2314 if (mFpsStartTime < 0) { 2315 mFpsStartTime = mFpsPrevTime = nowTime; 2316 mFpsNumFrames = 0; 2317 } else { 2318 ++mFpsNumFrames; 2319 String thisHash = Integer.toHexString(System.identityHashCode(this)); 2320 long frameTime = nowTime - mFpsPrevTime; 2321 long totalTime = nowTime - mFpsStartTime; 2322 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime); 2323 mFpsPrevTime = nowTime; 2324 if (totalTime > 1000) { 2325 float fps = (float) mFpsNumFrames * 1000 / totalTime; 2326 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps); 2327 mFpsStartTime = nowTime; 2328 mFpsNumFrames = 0; 2329 } 2330 } 2331 } 2332 2333 private void performDraw() { 2334 if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) { 2335 return; 2336 } 2337 2338 final boolean fullRedrawNeeded = mFullRedrawNeeded; 2339 mFullRedrawNeeded = false; 2340 2341 mIsDrawing = true; 2342 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw"); 2343 try { 2344 draw(fullRedrawNeeded); 2345 } finally { 2346 mIsDrawing = false; 2347 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2348 } 2349 2350 // For whatever reason we didn't create a HardwareRenderer, end any 2351 // hardware animations that are now dangling 2352 if (mAttachInfo.mPendingAnimatingRenderNodes != null) { 2353 final int count = mAttachInfo.mPendingAnimatingRenderNodes.size(); 2354 for (int i = 0; i < count; i++) { 2355 mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators(); 2356 } 2357 mAttachInfo.mPendingAnimatingRenderNodes.clear(); 2358 } 2359 2360 if (mReportNextDraw) { 2361 mReportNextDraw = false; 2362 if (mAttachInfo.mHardwareRenderer != null) { 2363 mAttachInfo.mHardwareRenderer.fence(); 2364 } 2365 2366 if (LOCAL_LOGV) { 2367 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle()); 2368 } 2369 if (mSurfaceHolder != null && mSurface.isValid()) { 2370 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder); 2371 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 2372 if (callbacks != null) { 2373 for (SurfaceHolder.Callback c : callbacks) { 2374 if (c instanceof SurfaceHolder.Callback2) { 2375 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 2376 mSurfaceHolder); 2377 } 2378 } 2379 } 2380 } 2381 try { 2382 mWindowSession.finishDrawing(mWindow); 2383 } catch (RemoteException e) { 2384 } 2385 } 2386 } 2387 2388 private void draw(boolean fullRedrawNeeded) { 2389 Surface surface = mSurface; 2390 if (!surface.isValid()) { 2391 return; 2392 } 2393 2394 if (DEBUG_FPS) { 2395 trackFPS(); 2396 } 2397 2398 if (!sFirstDrawComplete) { 2399 synchronized (sFirstDrawHandlers) { 2400 sFirstDrawComplete = true; 2401 final int count = sFirstDrawHandlers.size(); 2402 for (int i = 0; i< count; i++) { 2403 mHandler.post(sFirstDrawHandlers.get(i)); 2404 } 2405 } 2406 } 2407 2408 scrollToRectOrFocus(null, false); 2409 2410 if (mAttachInfo.mViewScrollChanged) { 2411 mAttachInfo.mViewScrollChanged = false; 2412 mAttachInfo.mTreeObserver.dispatchOnScrollChanged(); 2413 } 2414 2415 boolean animating = mScroller != null && mScroller.computeScrollOffset(); 2416 final int curScrollY; 2417 if (animating) { 2418 curScrollY = mScroller.getCurrY(); 2419 } else { 2420 curScrollY = mScrollY; 2421 } 2422 if (mCurScrollY != curScrollY) { 2423 mCurScrollY = curScrollY; 2424 fullRedrawNeeded = true; 2425 if (mView instanceof RootViewSurfaceTaker) { 2426 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY); 2427 } 2428 } 2429 2430 final float appScale = mAttachInfo.mApplicationScale; 2431 final boolean scalingRequired = mAttachInfo.mScalingRequired; 2432 2433 int resizeAlpha = 0; 2434 if (mResizeBuffer != null) { 2435 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime; 2436 if (deltaTime < mResizeBufferDuration) { 2437 float amt = deltaTime/(float) mResizeBufferDuration; 2438 amt = mResizeInterpolator.getInterpolation(amt); 2439 animating = true; 2440 resizeAlpha = 255 - (int)(amt*255); 2441 } else { 2442 disposeResizeBuffer(); 2443 } 2444 } 2445 2446 final Rect dirty = mDirty; 2447 if (mSurfaceHolder != null) { 2448 // The app owns the surface, we won't draw. 2449 dirty.setEmpty(); 2450 if (animating) { 2451 if (mScroller != null) { 2452 mScroller.abortAnimation(); 2453 } 2454 disposeResizeBuffer(); 2455 } 2456 return; 2457 } 2458 2459 if (fullRedrawNeeded) { 2460 mAttachInfo.mIgnoreDirtyState = true; 2461 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 2462 } 2463 2464 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2465 Log.v(TAG, "Draw " + mView + "/" 2466 + mWindowAttributes.getTitle() 2467 + ": dirty={" + dirty.left + "," + dirty.top 2468 + "," + dirty.right + "," + dirty.bottom + "} surface=" 2469 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" + 2470 appScale + ", width=" + mWidth + ", height=" + mHeight); 2471 } 2472 2473 mAttachInfo.mTreeObserver.dispatchOnDraw(); 2474 2475 int xOffset = 0; 2476 int yOffset = curScrollY; 2477 final WindowManager.LayoutParams params = mWindowAttributes; 2478 final Rect surfaceInsets = params != null ? params.surfaceInsets : null; 2479 if (surfaceInsets != null) { 2480 xOffset -= surfaceInsets.left; 2481 yOffset -= surfaceInsets.top; 2482 2483 // Offset dirty rect for surface insets. 2484 dirty.offset(surfaceInsets.left, surfaceInsets.right); 2485 } 2486 2487 boolean accessibilityFocusDirty = false; 2488 final Drawable drawable = mAttachInfo.mAccessibilityFocusDrawable; 2489 if (drawable != null) { 2490 final Rect bounds = mAttachInfo.mTmpInvalRect; 2491 final boolean hasFocus = getAccessibilityFocusedRect(bounds); 2492 if (!hasFocus) { 2493 bounds.setEmpty(); 2494 } 2495 if (!bounds.equals(drawable.getBounds())) { 2496 accessibilityFocusDirty = true; 2497 } 2498 } 2499 2500 if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) { 2501 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 2502 // If accessibility focus moved, always invalidate the root. 2503 boolean invalidateRoot = accessibilityFocusDirty; 2504 2505 // Draw with hardware renderer. 2506 mIsAnimating = false; 2507 2508 if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) { 2509 mHardwareYOffset = yOffset; 2510 mHardwareXOffset = xOffset; 2511 invalidateRoot = true; 2512 } 2513 mResizeAlpha = resizeAlpha; 2514 2515 if (invalidateRoot) { 2516 mAttachInfo.mHardwareRenderer.invalidateRoot(); 2517 } 2518 2519 dirty.setEmpty(); 2520 2521 mBlockResizeBuffer = false; 2522 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this); 2523 } else { 2524 // If we get here with a disabled & requested hardware renderer, something went 2525 // wrong (an invalidate posted right before we destroyed the hardware surface 2526 // for instance) so we should just bail out. Locking the surface with software 2527 // rendering at this point would lock it forever and prevent hardware renderer 2528 // from doing its job when it comes back. 2529 // Before we request a new frame we must however attempt to reinitiliaze the 2530 // hardware renderer if it's in requested state. This would happen after an 2531 // eglTerminate() for instance. 2532 if (mAttachInfo.mHardwareRenderer != null && 2533 !mAttachInfo.mHardwareRenderer.isEnabled() && 2534 mAttachInfo.mHardwareRenderer.isRequested()) { 2535 2536 try { 2537 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 2538 mWidth, mHeight, mSurface, surfaceInsets); 2539 } catch (OutOfResourcesException e) { 2540 handleOutOfResourcesException(e); 2541 return; 2542 } 2543 2544 mFullRedrawNeeded = true; 2545 scheduleTraversals(); 2546 return; 2547 } 2548 2549 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) { 2550 return; 2551 } 2552 } 2553 } 2554 2555 if (animating) { 2556 mFullRedrawNeeded = true; 2557 scheduleTraversals(); 2558 } 2559 } 2560 2561 /** 2562 * @return true if drawing was successful, false if an error occurred 2563 */ 2564 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff, 2565 boolean scalingRequired, Rect dirty) { 2566 2567 // Draw with software renderer. 2568 final Canvas canvas; 2569 try { 2570 final int left = dirty.left; 2571 final int top = dirty.top; 2572 final int right = dirty.right; 2573 final int bottom = dirty.bottom; 2574 2575 canvas = mSurface.lockCanvas(dirty); 2576 2577 // The dirty rectangle can be modified by Surface.lockCanvas() 2578 //noinspection ConstantConditions 2579 if (left != dirty.left || top != dirty.top || right != dirty.right 2580 || bottom != dirty.bottom) { 2581 attachInfo.mIgnoreDirtyState = true; 2582 } 2583 2584 // TODO: Do this in native 2585 canvas.setDensity(mDensity); 2586 } catch (Surface.OutOfResourcesException e) { 2587 handleOutOfResourcesException(e); 2588 return false; 2589 } catch (IllegalArgumentException e) { 2590 Log.e(TAG, "Could not lock surface", e); 2591 // Don't assume this is due to out of memory, it could be 2592 // something else, and if it is something else then we could 2593 // kill stuff (or ourself) for no reason. 2594 mLayoutRequested = true; // ask wm for a new surface next time. 2595 return false; 2596 } 2597 2598 try { 2599 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2600 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2601 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2602 //canvas.drawARGB(255, 255, 0, 0); 2603 } 2604 2605 // If this bitmap's format includes an alpha channel, we 2606 // need to clear it before drawing so that the child will 2607 // properly re-composite its drawing on a transparent 2608 // background. This automatically respects the clip/dirty region 2609 // or 2610 // If we are applying an offset, we need to clear the area 2611 // where the offset doesn't appear to avoid having garbage 2612 // left in the blank areas. 2613 if (!canvas.isOpaque() || yoff != 0 || xoff != 0) { 2614 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2615 } 2616 2617 dirty.setEmpty(); 2618 mIsAnimating = false; 2619 attachInfo.mDrawingTime = SystemClock.uptimeMillis(); 2620 mView.mPrivateFlags |= View.PFLAG_DRAWN; 2621 2622 if (DEBUG_DRAW) { 2623 Context cxt = mView.getContext(); 2624 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2625 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2626 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2627 } 2628 try { 2629 canvas.translate(-xoff, -yoff); 2630 if (mTranslator != null) { 2631 mTranslator.translateCanvas(canvas); 2632 } 2633 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0); 2634 attachInfo.mSetIgnoreDirtyState = false; 2635 2636 mView.draw(canvas); 2637 2638 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2639 } finally { 2640 if (!attachInfo.mSetIgnoreDirtyState) { 2641 // Only clear the flag if it was not set during the mView.draw() call 2642 attachInfo.mIgnoreDirtyState = false; 2643 } 2644 } 2645 } finally { 2646 try { 2647 surface.unlockCanvasAndPost(canvas); 2648 } catch (IllegalArgumentException e) { 2649 Log.e(TAG, "Could not unlock surface", e); 2650 mLayoutRequested = true; // ask wm for a new surface next time. 2651 //noinspection ReturnInsideFinallyBlock 2652 return false; 2653 } 2654 2655 if (LOCAL_LOGV) { 2656 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2657 } 2658 } 2659 return true; 2660 } 2661 2662 /** 2663 * We want to draw a highlight around the current accessibility focused. 2664 * Since adding a style for all possible view is not a viable option we 2665 * have this specialized drawing method. 2666 * 2667 * Note: We are doing this here to be able to draw the highlight for 2668 * virtual views in addition to real ones. 2669 * 2670 * @param canvas The canvas on which to draw. 2671 */ 2672 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) { 2673 final Rect bounds = mAttachInfo.mTmpInvalRect; 2674 if (getAccessibilityFocusedRect(bounds)) { 2675 final Drawable drawable = getAccessibilityFocusedDrawable(); 2676 if (drawable != null) { 2677 drawable.setBounds(bounds); 2678 drawable.draw(canvas); 2679 } 2680 } else if (mAttachInfo.mAccessibilityFocusDrawable != null) { 2681 mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0); 2682 } 2683 } 2684 2685 private boolean getAccessibilityFocusedRect(Rect bounds) { 2686 final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext); 2687 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 2688 return false; 2689 } 2690 2691 final View host = mAccessibilityFocusedHost; 2692 if (host == null || host.mAttachInfo == null) { 2693 return false; 2694 } 2695 2696 final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider(); 2697 if (provider == null) { 2698 host.getBoundsOnScreen(bounds); 2699 } else if (mAccessibilityFocusedVirtualView != null) { 2700 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds); 2701 } else { 2702 return false; 2703 } 2704 2705 final AttachInfo attachInfo = mAttachInfo; 2706 bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop); 2707 bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth, attachInfo.mViewRootImpl.mHeight); 2708 return !bounds.isEmpty(); 2709 } 2710 2711 private Drawable getAccessibilityFocusedDrawable() { 2712 // Lazily load the accessibility focus drawable. 2713 if (mAttachInfo.mAccessibilityFocusDrawable == null) { 2714 final TypedValue value = new TypedValue(); 2715 final boolean resolved = mView.mContext.getTheme().resolveAttribute( 2716 R.attr.accessibilityFocusedDrawable, value, true); 2717 if (resolved) { 2718 mAttachInfo.mAccessibilityFocusDrawable = 2719 mView.mContext.getDrawable(value.resourceId); 2720 } 2721 } 2722 return mAttachInfo.mAccessibilityFocusDrawable; 2723 } 2724 2725 /** 2726 * @hide 2727 */ 2728 public void setDrawDuringWindowsAnimating(boolean value) { 2729 mDrawDuringWindowsAnimating = value; 2730 if (value) { 2731 handleDispatchDoneAnimating(); 2732 } 2733 } 2734 2735 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2736 final Rect ci = mAttachInfo.mContentInsets; 2737 final Rect vi = mAttachInfo.mVisibleInsets; 2738 int scrollY = 0; 2739 boolean handled = false; 2740 2741 if (vi.left > ci.left || vi.top > ci.top 2742 || vi.right > ci.right || vi.bottom > ci.bottom) { 2743 // We'll assume that we aren't going to change the scroll 2744 // offset, since we want to avoid that unless it is actually 2745 // going to make the focus visible... otherwise we scroll 2746 // all over the place. 2747 scrollY = mScrollY; 2748 // We can be called for two different situations: during a draw, 2749 // to update the scroll position if the focus has changed (in which 2750 // case 'rectangle' is null), or in response to a 2751 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2752 // is non-null and we just want to scroll to whatever that 2753 // rectangle is). 2754 final View focus = mView.findFocus(); 2755 if (focus == null) { 2756 return false; 2757 } 2758 View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null; 2759 if (focus != lastScrolledFocus) { 2760 // If the focus has changed, then ignore any requests to scroll 2761 // to a rectangle; first we want to make sure the entire focus 2762 // view is visible. 2763 rectangle = null; 2764 } 2765 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2766 + " rectangle=" + rectangle + " ci=" + ci 2767 + " vi=" + vi); 2768 if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) { 2769 // Optimization: if the focus hasn't changed since last 2770 // time, and no layout has happened, then just leave things 2771 // as they are. 2772 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2773 + mScrollY + " vi=" + vi.toShortString()); 2774 } else { 2775 // We need to determine if the currently focused view is 2776 // within the visible part of the window and, if not, apply 2777 // a pan so it can be seen. 2778 mLastScrolledFocus = new WeakReference<View>(focus); 2779 mScrollMayChange = false; 2780 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2781 // Try to find the rectangle from the focus view. 2782 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2783 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2784 + mView.getWidth() + " h=" + mView.getHeight() 2785 + " ci=" + ci.toShortString() 2786 + " vi=" + vi.toShortString()); 2787 if (rectangle == null) { 2788 focus.getFocusedRect(mTempRect); 2789 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2790 + ": focusRect=" + mTempRect.toShortString()); 2791 if (mView instanceof ViewGroup) { 2792 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2793 focus, mTempRect); 2794 } 2795 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2796 "Focus in window: focusRect=" 2797 + mTempRect.toShortString() 2798 + " visRect=" + mVisRect.toShortString()); 2799 } else { 2800 mTempRect.set(rectangle); 2801 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2802 "Request scroll to rect: " 2803 + mTempRect.toShortString() 2804 + " visRect=" + mVisRect.toShortString()); 2805 } 2806 if (mTempRect.intersect(mVisRect)) { 2807 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2808 "Focus window visible rect: " 2809 + mTempRect.toShortString()); 2810 if (mTempRect.height() > 2811 (mView.getHeight()-vi.top-vi.bottom)) { 2812 // If the focus simply is not going to fit, then 2813 // best is probably just to leave things as-is. 2814 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2815 "Too tall; leaving scrollY=" + scrollY); 2816 } else if ((mTempRect.top-scrollY) < vi.top) { 2817 scrollY -= vi.top - (mTempRect.top-scrollY); 2818 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2819 "Top covered; scrollY=" + scrollY); 2820 } else if ((mTempRect.bottom-scrollY) 2821 > (mView.getHeight()-vi.bottom)) { 2822 scrollY += (mTempRect.bottom-scrollY) 2823 - (mView.getHeight()-vi.bottom); 2824 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2825 "Bottom covered; scrollY=" + scrollY); 2826 } 2827 handled = true; 2828 } 2829 } 2830 } 2831 } 2832 2833 if (scrollY != mScrollY) { 2834 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2835 + mScrollY + " , new=" + scrollY); 2836 if (!immediate && mResizeBuffer == null) { 2837 if (mScroller == null) { 2838 mScroller = new Scroller(mView.getContext()); 2839 } 2840 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2841 } else if (mScroller != null) { 2842 mScroller.abortAnimation(); 2843 } 2844 mScrollY = scrollY; 2845 } 2846 2847 return handled; 2848 } 2849 2850 /** 2851 * @hide 2852 */ 2853 public View getAccessibilityFocusedHost() { 2854 return mAccessibilityFocusedHost; 2855 } 2856 2857 /** 2858 * @hide 2859 */ 2860 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() { 2861 return mAccessibilityFocusedVirtualView; 2862 } 2863 2864 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) { 2865 // If we have a virtual view with accessibility focus we need 2866 // to clear the focus and invalidate the virtual view bounds. 2867 if (mAccessibilityFocusedVirtualView != null) { 2868 2869 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView; 2870 View focusHost = mAccessibilityFocusedHost; 2871 2872 // Wipe the state of the current accessibility focus since 2873 // the call into the provider to clear accessibility focus 2874 // will fire an accessibility event which will end up calling 2875 // this method and we want to have clean state when this 2876 // invocation happens. 2877 mAccessibilityFocusedHost = null; 2878 mAccessibilityFocusedVirtualView = null; 2879 2880 // Clear accessibility focus on the host after clearing state since 2881 // this method may be reentrant. 2882 focusHost.clearAccessibilityFocusNoCallbacks(); 2883 2884 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider(); 2885 if (provider != null) { 2886 // Invalidate the area of the cleared accessibility focus. 2887 focusNode.getBoundsInParent(mTempRect); 2888 focusHost.invalidate(mTempRect); 2889 // Clear accessibility focus in the virtual node. 2890 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 2891 focusNode.getSourceNodeId()); 2892 provider.performAction(virtualNodeId, 2893 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); 2894 } 2895 focusNode.recycle(); 2896 } 2897 if (mAccessibilityFocusedHost != null) { 2898 // Clear accessibility focus in the view. 2899 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(); 2900 } 2901 2902 // Set the new focus host and node. 2903 mAccessibilityFocusedHost = view; 2904 mAccessibilityFocusedVirtualView = node; 2905 2906 if (mAttachInfo.mHardwareRenderer != null) { 2907 mAttachInfo.mHardwareRenderer.invalidateRoot(); 2908 } 2909 } 2910 2911 @Override 2912 public void requestChildFocus(View child, View focused) { 2913 if (DEBUG_INPUT_RESIZE) { 2914 Log.v(TAG, "Request child focus: focus now " + focused); 2915 } 2916 checkThread(); 2917 scheduleTraversals(); 2918 } 2919 2920 @Override 2921 public void clearChildFocus(View child) { 2922 if (DEBUG_INPUT_RESIZE) { 2923 Log.v(TAG, "Clearing child focus"); 2924 } 2925 checkThread(); 2926 scheduleTraversals(); 2927 } 2928 2929 @Override 2930 public ViewParent getParentForAccessibility() { 2931 return null; 2932 } 2933 2934 @Override 2935 public void focusableViewAvailable(View v) { 2936 checkThread(); 2937 if (mView != null) { 2938 if (!mView.hasFocus()) { 2939 v.requestFocus(); 2940 } else { 2941 // the one case where will transfer focus away from the current one 2942 // is if the current view is a view group that prefers to give focus 2943 // to its children first AND the view is a descendant of it. 2944 View focused = mView.findFocus(); 2945 if (focused instanceof ViewGroup) { 2946 ViewGroup group = (ViewGroup) focused; 2947 if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 2948 && isViewDescendantOf(v, focused)) { 2949 v.requestFocus(); 2950 } 2951 } 2952 } 2953 } 2954 } 2955 2956 @Override 2957 public void recomputeViewAttributes(View child) { 2958 checkThread(); 2959 if (mView == child) { 2960 mAttachInfo.mRecomputeGlobalAttributes = true; 2961 if (!mWillDrawSoon) { 2962 scheduleTraversals(); 2963 } 2964 } 2965 } 2966 2967 void dispatchDetachedFromWindow() { 2968 if (mView != null && mView.mAttachInfo != null) { 2969 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false); 2970 mView.dispatchDetachedFromWindow(); 2971 } 2972 2973 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2974 mAccessibilityManager.removeAccessibilityStateChangeListener( 2975 mAccessibilityInteractionConnectionManager); 2976 mAccessibilityManager.removeHighTextContrastStateChangeListener( 2977 mHighContrastTextManager); 2978 removeSendWindowContentChangedCallback(); 2979 2980 destroyHardwareRenderer(); 2981 2982 setAccessibilityFocus(null, null); 2983 2984 mView.assignParent(null); 2985 mView = null; 2986 mAttachInfo.mRootView = null; 2987 2988 mSurface.release(); 2989 2990 if (mInputQueueCallback != null && mInputQueue != null) { 2991 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2992 mInputQueue.dispose(); 2993 mInputQueueCallback = null; 2994 mInputQueue = null; 2995 } 2996 if (mInputEventReceiver != null) { 2997 mInputEventReceiver.dispose(); 2998 mInputEventReceiver = null; 2999 } 3000 try { 3001 mWindowSession.remove(mWindow); 3002 } catch (RemoteException e) { 3003 } 3004 3005 // Dispose the input channel after removing the window so the Window Manager 3006 // doesn't interpret the input channel being closed as an abnormal termination. 3007 if (mInputChannel != null) { 3008 mInputChannel.dispose(); 3009 mInputChannel = null; 3010 } 3011 3012 mDisplayManager.unregisterDisplayListener(mDisplayListener); 3013 3014 unscheduleTraversals(); 3015 } 3016 3017 void updateConfiguration(Configuration config, boolean force) { 3018 if (DEBUG_CONFIGURATION) Log.v(TAG, 3019 "Applying new config to window " 3020 + mWindowAttributes.getTitle() 3021 + ": " + config); 3022 3023 CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo(); 3024 if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) { 3025 config = new Configuration(config); 3026 ci.applyToConfiguration(mNoncompatDensity, config); 3027 } 3028 3029 synchronized (sConfigCallbacks) { 3030 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 3031 sConfigCallbacks.get(i).onConfigurationChanged(config); 3032 } 3033 } 3034 if (mView != null) { 3035 // At this point the resources have been updated to 3036 // have the most recent config, whatever that is. Use 3037 // the one in them which may be newer. 3038 config = mView.getResources().getConfiguration(); 3039 if (force || mLastConfiguration.diff(config) != 0) { 3040 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection(); 3041 final int currentLayoutDirection = config.getLayoutDirection(); 3042 mLastConfiguration.setTo(config); 3043 if (lastLayoutDirection != currentLayoutDirection && 3044 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 3045 mView.setLayoutDirection(currentLayoutDirection); 3046 } 3047 mView.dispatchConfigurationChanged(config); 3048 } 3049 } 3050 } 3051 3052 /** 3053 * Return true if child is an ancestor of parent, (or equal to the parent). 3054 */ 3055 public static boolean isViewDescendantOf(View child, View parent) { 3056 if (child == parent) { 3057 return true; 3058 } 3059 3060 final ViewParent theParent = child.getParent(); 3061 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 3062 } 3063 3064 private static void forceLayout(View view) { 3065 view.forceLayout(); 3066 if (view instanceof ViewGroup) { 3067 ViewGroup group = (ViewGroup) view; 3068 final int count = group.getChildCount(); 3069 for (int i = 0; i < count; i++) { 3070 forceLayout(group.getChildAt(i)); 3071 } 3072 } 3073 } 3074 3075 private final static int MSG_INVALIDATE = 1; 3076 private final static int MSG_INVALIDATE_RECT = 2; 3077 private final static int MSG_DIE = 3; 3078 private final static int MSG_RESIZED = 4; 3079 private final static int MSG_RESIZED_REPORT = 5; 3080 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 3081 private final static int MSG_DISPATCH_INPUT_EVENT = 7; 3082 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 3083 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 3084 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 3085 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 3086 private final static int MSG_CHECK_FOCUS = 13; 3087 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 3088 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 3089 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 3090 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 3091 private final static int MSG_UPDATE_CONFIGURATION = 18; 3092 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 3093 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21; 3094 private final static int MSG_DISPATCH_DONE_ANIMATING = 22; 3095 private final static int MSG_INVALIDATE_WORLD = 23; 3096 private final static int MSG_WINDOW_MOVED = 24; 3097 private final static int MSG_SYNTHESIZE_INPUT_EVENT = 25; 3098 private final static int MSG_DISPATCH_WINDOW_SHOWN = 26; 3099 3100 final class ViewRootHandler extends Handler { 3101 @Override 3102 public String getMessageName(Message message) { 3103 switch (message.what) { 3104 case MSG_INVALIDATE: 3105 return "MSG_INVALIDATE"; 3106 case MSG_INVALIDATE_RECT: 3107 return "MSG_INVALIDATE_RECT"; 3108 case MSG_DIE: 3109 return "MSG_DIE"; 3110 case MSG_RESIZED: 3111 return "MSG_RESIZED"; 3112 case MSG_RESIZED_REPORT: 3113 return "MSG_RESIZED_REPORT"; 3114 case MSG_WINDOW_FOCUS_CHANGED: 3115 return "MSG_WINDOW_FOCUS_CHANGED"; 3116 case MSG_DISPATCH_INPUT_EVENT: 3117 return "MSG_DISPATCH_INPUT_EVENT"; 3118 case MSG_DISPATCH_APP_VISIBILITY: 3119 return "MSG_DISPATCH_APP_VISIBILITY"; 3120 case MSG_DISPATCH_GET_NEW_SURFACE: 3121 return "MSG_DISPATCH_GET_NEW_SURFACE"; 3122 case MSG_DISPATCH_KEY_FROM_IME: 3123 return "MSG_DISPATCH_KEY_FROM_IME"; 3124 case MSG_FINISH_INPUT_CONNECTION: 3125 return "MSG_FINISH_INPUT_CONNECTION"; 3126 case MSG_CHECK_FOCUS: 3127 return "MSG_CHECK_FOCUS"; 3128 case MSG_CLOSE_SYSTEM_DIALOGS: 3129 return "MSG_CLOSE_SYSTEM_DIALOGS"; 3130 case MSG_DISPATCH_DRAG_EVENT: 3131 return "MSG_DISPATCH_DRAG_EVENT"; 3132 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 3133 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 3134 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 3135 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 3136 case MSG_UPDATE_CONFIGURATION: 3137 return "MSG_UPDATE_CONFIGURATION"; 3138 case MSG_PROCESS_INPUT_EVENTS: 3139 return "MSG_PROCESS_INPUT_EVENTS"; 3140 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 3141 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 3142 case MSG_DISPATCH_DONE_ANIMATING: 3143 return "MSG_DISPATCH_DONE_ANIMATING"; 3144 case MSG_WINDOW_MOVED: 3145 return "MSG_WINDOW_MOVED"; 3146 case MSG_SYNTHESIZE_INPUT_EVENT: 3147 return "MSG_SYNTHESIZE_INPUT_EVENT"; 3148 case MSG_DISPATCH_WINDOW_SHOWN: 3149 return "MSG_DISPATCH_WINDOW_SHOWN"; 3150 } 3151 return super.getMessageName(message); 3152 } 3153 3154 @Override 3155 public void handleMessage(Message msg) { 3156 switch (msg.what) { 3157 case MSG_INVALIDATE: 3158 ((View) msg.obj).invalidate(); 3159 break; 3160 case MSG_INVALIDATE_RECT: 3161 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 3162 info.target.invalidate(info.left, info.top, info.right, info.bottom); 3163 info.recycle(); 3164 break; 3165 case MSG_PROCESS_INPUT_EVENTS: 3166 mProcessInputEventsScheduled = false; 3167 doProcessInputEvents(); 3168 break; 3169 case MSG_DISPATCH_APP_VISIBILITY: 3170 handleAppVisibility(msg.arg1 != 0); 3171 break; 3172 case MSG_DISPATCH_GET_NEW_SURFACE: 3173 handleGetNewSurface(); 3174 break; 3175 case MSG_RESIZED: { 3176 // Recycled in the fall through... 3177 SomeArgs args = (SomeArgs) msg.obj; 3178 if (mWinFrame.equals(args.arg1) 3179 && mPendingOverscanInsets.equals(args.arg5) 3180 && mPendingContentInsets.equals(args.arg2) 3181 && mPendingStableInsets.equals(args.arg6) 3182 && mPendingVisibleInsets.equals(args.arg3) 3183 && args.arg4 == null) { 3184 break; 3185 } 3186 } // fall through... 3187 case MSG_RESIZED_REPORT: 3188 if (mAdded) { 3189 SomeArgs args = (SomeArgs) msg.obj; 3190 3191 Configuration config = (Configuration) args.arg4; 3192 if (config != null) { 3193 updateConfiguration(config, false); 3194 } 3195 3196 mWinFrame.set((Rect) args.arg1); 3197 mPendingOverscanInsets.set((Rect) args.arg5); 3198 mPendingContentInsets.set((Rect) args.arg2); 3199 mPendingStableInsets.set((Rect) args.arg6); 3200 mPendingVisibleInsets.set((Rect) args.arg3); 3201 3202 args.recycle(); 3203 3204 if (msg.what == MSG_RESIZED_REPORT) { 3205 mReportNextDraw = true; 3206 } 3207 3208 if (mView != null) { 3209 forceLayout(mView); 3210 } 3211 3212 requestLayout(); 3213 } 3214 break; 3215 case MSG_WINDOW_MOVED: 3216 if (mAdded) { 3217 final int w = mWinFrame.width(); 3218 final int h = mWinFrame.height(); 3219 final int l = msg.arg1; 3220 final int t = msg.arg2; 3221 mWinFrame.left = l; 3222 mWinFrame.right = l + w; 3223 mWinFrame.top = t; 3224 mWinFrame.bottom = t + h; 3225 3226 if (mView != null) { 3227 forceLayout(mView); 3228 } 3229 requestLayout(); 3230 } 3231 break; 3232 case MSG_WINDOW_FOCUS_CHANGED: { 3233 if (mAdded) { 3234 boolean hasWindowFocus = msg.arg1 != 0; 3235 mAttachInfo.mHasWindowFocus = hasWindowFocus; 3236 3237 profileRendering(hasWindowFocus); 3238 3239 if (hasWindowFocus) { 3240 boolean inTouchMode = msg.arg2 != 0; 3241 ensureTouchModeLocally(inTouchMode); 3242 3243 if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){ 3244 mFullRedrawNeeded = true; 3245 try { 3246 final WindowManager.LayoutParams lp = mWindowAttributes; 3247 final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null; 3248 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 3249 mWidth, mHeight, mSurface, surfaceInsets); 3250 } catch (OutOfResourcesException e) { 3251 Log.e(TAG, "OutOfResourcesException locking surface", e); 3252 try { 3253 if (!mWindowSession.outOfMemory(mWindow)) { 3254 Slog.w(TAG, "No processes killed for memory; killing self"); 3255 Process.killProcess(Process.myPid()); 3256 } 3257 } catch (RemoteException ex) { 3258 } 3259 // Retry in a bit. 3260 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 3261 return; 3262 } 3263 } 3264 } 3265 3266 mLastWasImTarget = WindowManager.LayoutParams 3267 .mayUseInputMethod(mWindowAttributes.flags); 3268 3269 InputMethodManager imm = InputMethodManager.peekInstance(); 3270 if (mView != null) { 3271 if (hasWindowFocus && imm != null && mLastWasImTarget && 3272 !isInLocalFocusMode()) { 3273 imm.startGettingWindowFocus(mView); 3274 } 3275 mAttachInfo.mKeyDispatchState.reset(); 3276 mView.dispatchWindowFocusChanged(hasWindowFocus); 3277 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus); 3278 } 3279 3280 // Note: must be done after the focus change callbacks, 3281 // so all of the view state is set up correctly. 3282 if (hasWindowFocus) { 3283 if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { 3284 imm.onWindowFocus(mView, mView.findFocus(), 3285 mWindowAttributes.softInputMode, 3286 !mHasHadWindowFocus, mWindowAttributes.flags); 3287 } 3288 // Clear the forward bit. We can just do this directly, since 3289 // the window manager doesn't care about it. 3290 mWindowAttributes.softInputMode &= 3291 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3292 ((WindowManager.LayoutParams)mView.getLayoutParams()) 3293 .softInputMode &= 3294 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3295 mHasHadWindowFocus = true; 3296 } 3297 3298 if (mView != null && mAccessibilityManager.isEnabled()) { 3299 if (hasWindowFocus) { 3300 mView.sendAccessibilityEvent( 3301 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 3302 } 3303 } 3304 } 3305 } break; 3306 case MSG_DIE: 3307 doDie(); 3308 break; 3309 case MSG_DISPATCH_INPUT_EVENT: { 3310 SomeArgs args = (SomeArgs)msg.obj; 3311 InputEvent event = (InputEvent)args.arg1; 3312 InputEventReceiver receiver = (InputEventReceiver)args.arg2; 3313 enqueueInputEvent(event, receiver, 0, true); 3314 args.recycle(); 3315 } break; 3316 case MSG_SYNTHESIZE_INPUT_EVENT: { 3317 InputEvent event = (InputEvent)msg.obj; 3318 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true); 3319 } break; 3320 case MSG_DISPATCH_KEY_FROM_IME: { 3321 if (LOCAL_LOGV) Log.v( 3322 TAG, "Dispatching key " 3323 + msg.obj + " from IME to " + mView); 3324 KeyEvent event = (KeyEvent)msg.obj; 3325 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 3326 // The IME is trying to say this event is from the 3327 // system! Bad bad bad! 3328 //noinspection UnusedAssignment 3329 event = KeyEvent.changeFlags(event, event.getFlags() & 3330 ~KeyEvent.FLAG_FROM_SYSTEM); 3331 } 3332 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 3333 } break; 3334 case MSG_FINISH_INPUT_CONNECTION: { 3335 InputMethodManager imm = InputMethodManager.peekInstance(); 3336 if (imm != null) { 3337 imm.reportFinishInputConnection((InputConnection)msg.obj); 3338 } 3339 } break; 3340 case MSG_CHECK_FOCUS: { 3341 InputMethodManager imm = InputMethodManager.peekInstance(); 3342 if (imm != null) { 3343 imm.checkFocus(); 3344 } 3345 } break; 3346 case MSG_CLOSE_SYSTEM_DIALOGS: { 3347 if (mView != null) { 3348 mView.onCloseSystemDialogs((String)msg.obj); 3349 } 3350 } break; 3351 case MSG_DISPATCH_DRAG_EVENT: 3352 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 3353 DragEvent event = (DragEvent)msg.obj; 3354 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 3355 handleDragEvent(event); 3356 } break; 3357 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 3358 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); 3359 } break; 3360 case MSG_UPDATE_CONFIGURATION: { 3361 Configuration config = (Configuration)msg.obj; 3362 if (config.isOtherSeqNewer(mLastConfiguration)) { 3363 config = mLastConfiguration; 3364 } 3365 updateConfiguration(config, false); 3366 } break; 3367 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3368 setAccessibilityFocus(null, null); 3369 } break; 3370 case MSG_DISPATCH_DONE_ANIMATING: { 3371 handleDispatchDoneAnimating(); 3372 } break; 3373 case MSG_INVALIDATE_WORLD: { 3374 if (mView != null) { 3375 invalidateWorld(mView); 3376 } 3377 } break; 3378 case MSG_DISPATCH_WINDOW_SHOWN: { 3379 handleDispatchWindowShown(); 3380 } 3381 } 3382 } 3383 } 3384 3385 final ViewRootHandler mHandler = new ViewRootHandler(); 3386 3387 /** 3388 * Something in the current window tells us we need to change the touch mode. For 3389 * example, we are not in touch mode, and the user touches the screen. 3390 * 3391 * If the touch mode has changed, tell the window manager, and handle it locally. 3392 * 3393 * @param inTouchMode Whether we want to be in touch mode. 3394 * @return True if the touch mode changed and focus changed was changed as a result 3395 */ 3396 boolean ensureTouchMode(boolean inTouchMode) { 3397 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3398 + "touch mode is " + mAttachInfo.mInTouchMode); 3399 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3400 3401 // tell the window manager 3402 try { 3403 if (!isInLocalFocusMode()) { 3404 mWindowSession.setInTouchMode(inTouchMode); 3405 } 3406 } catch (RemoteException e) { 3407 throw new RuntimeException(e); 3408 } 3409 3410 // handle the change 3411 return ensureTouchModeLocally(inTouchMode); 3412 } 3413 3414 /** 3415 * Ensure that the touch mode for this window is set, and if it is changing, 3416 * take the appropriate action. 3417 * @param inTouchMode Whether we want to be in touch mode. 3418 * @return True if the touch mode changed and focus changed was changed as a result 3419 */ 3420 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3421 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3422 + "touch mode is " + mAttachInfo.mInTouchMode); 3423 3424 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3425 3426 mAttachInfo.mInTouchMode = inTouchMode; 3427 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3428 3429 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3430 } 3431 3432 private boolean enterTouchMode() { 3433 if (mView != null && mView.hasFocus()) { 3434 // note: not relying on mFocusedView here because this could 3435 // be when the window is first being added, and mFocused isn't 3436 // set yet. 3437 final View focused = mView.findFocus(); 3438 if (focused != null && !focused.isFocusableInTouchMode()) { 3439 final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused); 3440 if (ancestorToTakeFocus != null) { 3441 // there is an ancestor that wants focus after its 3442 // descendants that is focusable in touch mode.. give it 3443 // focus 3444 return ancestorToTakeFocus.requestFocus(); 3445 } else { 3446 // There's nothing to focus. Clear and propagate through the 3447 // hierarchy, but don't attempt to place new focus. 3448 focused.clearFocusInternal(null, true, false); 3449 return true; 3450 } 3451 } 3452 } 3453 return false; 3454 } 3455 3456 /** 3457 * Find an ancestor of focused that wants focus after its descendants and is 3458 * focusable in touch mode. 3459 * @param focused The currently focused view. 3460 * @return An appropriate view, or null if no such view exists. 3461 */ 3462 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3463 ViewParent parent = focused.getParent(); 3464 while (parent instanceof ViewGroup) { 3465 final ViewGroup vgParent = (ViewGroup) parent; 3466 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3467 && vgParent.isFocusableInTouchMode()) { 3468 return vgParent; 3469 } 3470 if (vgParent.isRootNamespace()) { 3471 return null; 3472 } else { 3473 parent = vgParent.getParent(); 3474 } 3475 } 3476 return null; 3477 } 3478 3479 private boolean leaveTouchMode() { 3480 if (mView != null) { 3481 if (mView.hasFocus()) { 3482 View focusedView = mView.findFocus(); 3483 if (!(focusedView instanceof ViewGroup)) { 3484 // some view has focus, let it keep it 3485 return false; 3486 } else if (((ViewGroup) focusedView).getDescendantFocusability() != 3487 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3488 // some view group has focus, and doesn't prefer its children 3489 // over itself for focus, so let them keep it. 3490 return false; 3491 } 3492 } 3493 3494 // find the best view to give focus to in this brave new non-touch-mode 3495 // world 3496 final View focused = focusSearch(null, View.FOCUS_DOWN); 3497 if (focused != null) { 3498 return focused.requestFocus(View.FOCUS_DOWN); 3499 } 3500 } 3501 return false; 3502 } 3503 3504 /** 3505 * Base class for implementing a stage in the chain of responsibility 3506 * for processing input events. 3507 * <p> 3508 * Events are delivered to the stage by the {@link #deliver} method. The stage 3509 * then has the choice of finishing the event or forwarding it to the next stage. 3510 * </p> 3511 */ 3512 abstract class InputStage { 3513 private final InputStage mNext; 3514 3515 protected static final int FORWARD = 0; 3516 protected static final int FINISH_HANDLED = 1; 3517 protected static final int FINISH_NOT_HANDLED = 2; 3518 3519 /** 3520 * Creates an input stage. 3521 * @param next The next stage to which events should be forwarded. 3522 */ 3523 public InputStage(InputStage next) { 3524 mNext = next; 3525 } 3526 3527 /** 3528 * Delivers an event to be processed. 3529 */ 3530 public final void deliver(QueuedInputEvent q) { 3531 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) { 3532 forward(q); 3533 } else if (shouldDropInputEvent(q)) { 3534 finish(q, false); 3535 } else { 3536 apply(q, onProcess(q)); 3537 } 3538 } 3539 3540 /** 3541 * Marks the the input event as finished then forwards it to the next stage. 3542 */ 3543 protected void finish(QueuedInputEvent q, boolean handled) { 3544 q.mFlags |= QueuedInputEvent.FLAG_FINISHED; 3545 if (handled) { 3546 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED; 3547 } 3548 forward(q); 3549 } 3550 3551 /** 3552 * Forwards the event to the next stage. 3553 */ 3554 protected void forward(QueuedInputEvent q) { 3555 onDeliverToNext(q); 3556 } 3557 3558 /** 3559 * Applies a result code from {@link #onProcess} to the specified event. 3560 */ 3561 protected void apply(QueuedInputEvent q, int result) { 3562 if (result == FORWARD) { 3563 forward(q); 3564 } else if (result == FINISH_HANDLED) { 3565 finish(q, true); 3566 } else if (result == FINISH_NOT_HANDLED) { 3567 finish(q, false); 3568 } else { 3569 throw new IllegalArgumentException("Invalid result: " + result); 3570 } 3571 } 3572 3573 /** 3574 * Called when an event is ready to be processed. 3575 * @return A result code indicating how the event was handled. 3576 */ 3577 protected int onProcess(QueuedInputEvent q) { 3578 return FORWARD; 3579 } 3580 3581 /** 3582 * Called when an event is being delivered to the next stage. 3583 */ 3584 protected void onDeliverToNext(QueuedInputEvent q) { 3585 if (DEBUG_INPUT_STAGES) { 3586 Log.v(TAG, "Done with " + getClass().getSimpleName() + ". " + q); 3587 } 3588 if (mNext != null) { 3589 mNext.deliver(q); 3590 } else { 3591 finishInputEvent(q); 3592 } 3593 } 3594 3595 protected boolean shouldDropInputEvent(QueuedInputEvent q) { 3596 if (mView == null || !mAdded) { 3597 Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent); 3598 return true; 3599 } else if ((!mAttachInfo.mHasWindowFocus || mStopped) 3600 && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 3601 // This is a focus event and the window doesn't currently have input focus or 3602 // has stopped. This could be an event that came back from the previous stage 3603 // but the window has lost focus or stopped in the meantime. 3604 if (isTerminalInputEvent(q.mEvent)) { 3605 // Don't drop terminal input events, however mark them as canceled. 3606 q.mEvent.cancel(); 3607 Slog.w(TAG, "Cancelling event due to no window focus: " + q.mEvent); 3608 return false; 3609 } 3610 3611 // Drop non-terminal input events. 3612 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent); 3613 return true; 3614 } 3615 return false; 3616 } 3617 3618 void dump(String prefix, PrintWriter writer) { 3619 if (mNext != null) { 3620 mNext.dump(prefix, writer); 3621 } 3622 } 3623 } 3624 3625 /** 3626 * Base class for implementing an input pipeline stage that supports 3627 * asynchronous and out-of-order processing of input events. 3628 * <p> 3629 * In addition to what a normal input stage can do, an asynchronous 3630 * input stage may also defer an input event that has been delivered to it 3631 * and finish or forward it later. 3632 * </p> 3633 */ 3634 abstract class AsyncInputStage extends InputStage { 3635 private final String mTraceCounter; 3636 3637 private QueuedInputEvent mQueueHead; 3638 private QueuedInputEvent mQueueTail; 3639 private int mQueueLength; 3640 3641 protected static final int DEFER = 3; 3642 3643 /** 3644 * Creates an asynchronous input stage. 3645 * @param next The next stage to which events should be forwarded. 3646 * @param traceCounter The name of a counter to record the size of 3647 * the queue of pending events. 3648 */ 3649 public AsyncInputStage(InputStage next, String traceCounter) { 3650 super(next); 3651 mTraceCounter = traceCounter; 3652 } 3653 3654 /** 3655 * Marks the event as deferred, which is to say that it will be handled 3656 * asynchronously. The caller is responsible for calling {@link #forward} 3657 * or {@link #finish} later when it is done handling the event. 3658 */ 3659 protected void defer(QueuedInputEvent q) { 3660 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED; 3661 enqueue(q); 3662 } 3663 3664 @Override 3665 protected void forward(QueuedInputEvent q) { 3666 // Clear the deferred flag. 3667 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED; 3668 3669 // Fast path if the queue is empty. 3670 QueuedInputEvent curr = mQueueHead; 3671 if (curr == null) { 3672 super.forward(q); 3673 return; 3674 } 3675 3676 // Determine whether the event must be serialized behind any others 3677 // before it can be delivered to the next stage. This is done because 3678 // deferred events might be handled out of order by the stage. 3679 final int deviceId = q.mEvent.getDeviceId(); 3680 QueuedInputEvent prev = null; 3681 boolean blocked = false; 3682 while (curr != null && curr != q) { 3683 if (!blocked && deviceId == curr.mEvent.getDeviceId()) { 3684 blocked = true; 3685 } 3686 prev = curr; 3687 curr = curr.mNext; 3688 } 3689 3690 // If the event is blocked, then leave it in the queue to be delivered later. 3691 // Note that the event might not yet be in the queue if it was not previously 3692 // deferred so we will enqueue it if needed. 3693 if (blocked) { 3694 if (curr == null) { 3695 enqueue(q); 3696 } 3697 return; 3698 } 3699 3700 // The event is not blocked. Deliver it immediately. 3701 if (curr != null) { 3702 curr = curr.mNext; 3703 dequeue(q, prev); 3704 } 3705 super.forward(q); 3706 3707 // Dequeuing this event may have unblocked successors. Deliver them. 3708 while (curr != null) { 3709 if (deviceId == curr.mEvent.getDeviceId()) { 3710 if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) { 3711 break; 3712 } 3713 QueuedInputEvent next = curr.mNext; 3714 dequeue(curr, prev); 3715 super.forward(curr); 3716 curr = next; 3717 } else { 3718 prev = curr; 3719 curr = curr.mNext; 3720 } 3721 } 3722 } 3723 3724 @Override 3725 protected void apply(QueuedInputEvent q, int result) { 3726 if (result == DEFER) { 3727 defer(q); 3728 } else { 3729 super.apply(q, result); 3730 } 3731 } 3732 3733 private void enqueue(QueuedInputEvent q) { 3734 if (mQueueTail == null) { 3735 mQueueHead = q; 3736 mQueueTail = q; 3737 } else { 3738 mQueueTail.mNext = q; 3739 mQueueTail = q; 3740 } 3741 3742 mQueueLength += 1; 3743 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3744 } 3745 3746 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) { 3747 if (prev == null) { 3748 mQueueHead = q.mNext; 3749 } else { 3750 prev.mNext = q.mNext; 3751 } 3752 if (mQueueTail == q) { 3753 mQueueTail = prev; 3754 } 3755 q.mNext = null; 3756 3757 mQueueLength -= 1; 3758 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3759 } 3760 3761 @Override 3762 void dump(String prefix, PrintWriter writer) { 3763 writer.print(prefix); 3764 writer.print(getClass().getName()); 3765 writer.print(": mQueueLength="); 3766 writer.println(mQueueLength); 3767 3768 super.dump(prefix, writer); 3769 } 3770 } 3771 3772 /** 3773 * Delivers pre-ime input events to a native activity. 3774 * Does not support pointer events. 3775 */ 3776 final class NativePreImeInputStage extends AsyncInputStage 3777 implements InputQueue.FinishedInputEventCallback { 3778 public NativePreImeInputStage(InputStage next, String traceCounter) { 3779 super(next, traceCounter); 3780 } 3781 3782 @Override 3783 protected int onProcess(QueuedInputEvent q) { 3784 if (mInputQueue != null && q.mEvent instanceof KeyEvent) { 3785 mInputQueue.sendInputEvent(q.mEvent, q, true, this); 3786 return DEFER; 3787 } 3788 return FORWARD; 3789 } 3790 3791 @Override 3792 public void onFinishedInputEvent(Object token, boolean handled) { 3793 QueuedInputEvent q = (QueuedInputEvent)token; 3794 if (handled) { 3795 finish(q, true); 3796 return; 3797 } 3798 forward(q); 3799 } 3800 } 3801 3802 /** 3803 * Delivers pre-ime input events to the view hierarchy. 3804 * Does not support pointer events. 3805 */ 3806 final class ViewPreImeInputStage extends InputStage { 3807 public ViewPreImeInputStage(InputStage next) { 3808 super(next); 3809 } 3810 3811 @Override 3812 protected int onProcess(QueuedInputEvent q) { 3813 if (q.mEvent instanceof KeyEvent) { 3814 return processKeyEvent(q); 3815 } 3816 return FORWARD; 3817 } 3818 3819 private int processKeyEvent(QueuedInputEvent q) { 3820 final KeyEvent event = (KeyEvent)q.mEvent; 3821 if (mView.dispatchKeyEventPreIme(event)) { 3822 return FINISH_HANDLED; 3823 } 3824 return FORWARD; 3825 } 3826 } 3827 3828 /** 3829 * Delivers input events to the ime. 3830 * Does not support pointer events. 3831 */ 3832 final class ImeInputStage extends AsyncInputStage 3833 implements InputMethodManager.FinishedInputEventCallback { 3834 public ImeInputStage(InputStage next, String traceCounter) { 3835 super(next, traceCounter); 3836 } 3837 3838 @Override 3839 protected int onProcess(QueuedInputEvent q) { 3840 if (mLastWasImTarget && !isInLocalFocusMode()) { 3841 InputMethodManager imm = InputMethodManager.peekInstance(); 3842 if (imm != null) { 3843 final InputEvent event = q.mEvent; 3844 if (DEBUG_IMF) Log.v(TAG, "Sending input event to IME: " + event); 3845 int result = imm.dispatchInputEvent(event, q, this, mHandler); 3846 if (result == InputMethodManager.DISPATCH_HANDLED) { 3847 return FINISH_HANDLED; 3848 } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) { 3849 // The IME could not handle it, so skip along to the next InputStage 3850 return FORWARD; 3851 } else { 3852 return DEFER; // callback will be invoked later 3853 } 3854 } 3855 } 3856 return FORWARD; 3857 } 3858 3859 @Override 3860 public void onFinishedInputEvent(Object token, boolean handled) { 3861 QueuedInputEvent q = (QueuedInputEvent)token; 3862 if (handled) { 3863 finish(q, true); 3864 return; 3865 } 3866 forward(q); 3867 } 3868 } 3869 3870 /** 3871 * Performs early processing of post-ime input events. 3872 */ 3873 final class EarlyPostImeInputStage extends InputStage { 3874 public EarlyPostImeInputStage(InputStage next) { 3875 super(next); 3876 } 3877 3878 @Override 3879 protected int onProcess(QueuedInputEvent q) { 3880 if (q.mEvent instanceof KeyEvent) { 3881 return processKeyEvent(q); 3882 } else { 3883 final int source = q.mEvent.getSource(); 3884 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3885 return processPointerEvent(q); 3886 } 3887 } 3888 return FORWARD; 3889 } 3890 3891 private int processKeyEvent(QueuedInputEvent q) { 3892 final KeyEvent event = (KeyEvent)q.mEvent; 3893 3894 // If the key's purpose is to exit touch mode then we consume it 3895 // and consider it handled. 3896 if (checkForLeavingTouchModeAndConsume(event)) { 3897 return FINISH_HANDLED; 3898 } 3899 3900 // Make sure the fallback event policy sees all keys that will be 3901 // delivered to the view hierarchy. 3902 mFallbackEventHandler.preDispatchKeyEvent(event); 3903 return FORWARD; 3904 } 3905 3906 private int processPointerEvent(QueuedInputEvent q) { 3907 final MotionEvent event = (MotionEvent)q.mEvent; 3908 3909 // Translate the pointer event for compatibility, if needed. 3910 if (mTranslator != null) { 3911 mTranslator.translateEventInScreenToAppWindow(event); 3912 } 3913 3914 // Enter touch mode on down or scroll. 3915 final int action = event.getAction(); 3916 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3917 ensureTouchMode(true); 3918 } 3919 3920 // Offset the scroll position. 3921 if (mCurScrollY != 0) { 3922 event.offsetLocation(0, mCurScrollY); 3923 } 3924 3925 // Remember the touch position for possible drag-initiation. 3926 if (event.isTouchEvent()) { 3927 mLastTouchPoint.x = event.getRawX(); 3928 mLastTouchPoint.y = event.getRawY(); 3929 } 3930 return FORWARD; 3931 } 3932 } 3933 3934 /** 3935 * Delivers post-ime input events to a native activity. 3936 */ 3937 final class NativePostImeInputStage extends AsyncInputStage 3938 implements InputQueue.FinishedInputEventCallback { 3939 public NativePostImeInputStage(InputStage next, String traceCounter) { 3940 super(next, traceCounter); 3941 } 3942 3943 @Override 3944 protected int onProcess(QueuedInputEvent q) { 3945 if (mInputQueue != null) { 3946 mInputQueue.sendInputEvent(q.mEvent, q, false, this); 3947 return DEFER; 3948 } 3949 return FORWARD; 3950 } 3951 3952 @Override 3953 public void onFinishedInputEvent(Object token, boolean handled) { 3954 QueuedInputEvent q = (QueuedInputEvent)token; 3955 if (handled) { 3956 finish(q, true); 3957 return; 3958 } 3959 forward(q); 3960 } 3961 } 3962 3963 /** 3964 * Delivers post-ime input events to the view hierarchy. 3965 */ 3966 final class ViewPostImeInputStage extends InputStage { 3967 public ViewPostImeInputStage(InputStage next) { 3968 super(next); 3969 } 3970 3971 @Override 3972 protected int onProcess(QueuedInputEvent q) { 3973 if (q.mEvent instanceof KeyEvent) { 3974 return processKeyEvent(q); 3975 } else { 3976 // If delivering a new non-key event, make sure the window is 3977 // now allowed to start updating. 3978 handleDispatchDoneAnimating(); 3979 final int source = q.mEvent.getSource(); 3980 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3981 return processPointerEvent(q); 3982 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3983 return processTrackballEvent(q); 3984 } else { 3985 return processGenericMotionEvent(q); 3986 } 3987 } 3988 } 3989 3990 @Override 3991 protected void onDeliverToNext(QueuedInputEvent q) { 3992 if (mUnbufferedInputDispatch 3993 && q.mEvent instanceof MotionEvent 3994 && ((MotionEvent)q.mEvent).isTouchEvent() 3995 && isTerminalInputEvent(q.mEvent)) { 3996 mUnbufferedInputDispatch = false; 3997 scheduleConsumeBatchedInput(); 3998 } 3999 super.onDeliverToNext(q); 4000 } 4001 4002 private int processKeyEvent(QueuedInputEvent q) { 4003 final KeyEvent event = (KeyEvent)q.mEvent; 4004 4005 if (event.getAction() != KeyEvent.ACTION_UP) { 4006 // If delivering a new key event, make sure the window is 4007 // now allowed to start updating. 4008 handleDispatchDoneAnimating(); 4009 } 4010 4011 // Deliver the key to the view hierarchy. 4012 if (mView.dispatchKeyEvent(event)) { 4013 return FINISH_HANDLED; 4014 } 4015 4016 if (shouldDropInputEvent(q)) { 4017 return FINISH_NOT_HANDLED; 4018 } 4019 4020 // If the Control modifier is held, try to interpret the key as a shortcut. 4021 if (event.getAction() == KeyEvent.ACTION_DOWN 4022 && event.isCtrlPressed() 4023 && event.getRepeatCount() == 0 4024 && !KeyEvent.isModifierKey(event.getKeyCode())) { 4025 if (mView.dispatchKeyShortcutEvent(event)) { 4026 return FINISH_HANDLED; 4027 } 4028 if (shouldDropInputEvent(q)) { 4029 return FINISH_NOT_HANDLED; 4030 } 4031 } 4032 4033 // Apply the fallback event policy. 4034 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 4035 return FINISH_HANDLED; 4036 } 4037 if (shouldDropInputEvent(q)) { 4038 return FINISH_NOT_HANDLED; 4039 } 4040 4041 // Handle automatic focus changes. 4042 if (event.getAction() == KeyEvent.ACTION_DOWN) { 4043 int direction = 0; 4044 switch (event.getKeyCode()) { 4045 case KeyEvent.KEYCODE_DPAD_LEFT: 4046 if (event.hasNoModifiers()) { 4047 direction = View.FOCUS_LEFT; 4048 } 4049 break; 4050 case KeyEvent.KEYCODE_DPAD_RIGHT: 4051 if (event.hasNoModifiers()) { 4052 direction = View.FOCUS_RIGHT; 4053 } 4054 break; 4055 case KeyEvent.KEYCODE_DPAD_UP: 4056 if (event.hasNoModifiers()) { 4057 direction = View.FOCUS_UP; 4058 } 4059 break; 4060 case KeyEvent.KEYCODE_DPAD_DOWN: 4061 if (event.hasNoModifiers()) { 4062 direction = View.FOCUS_DOWN; 4063 } 4064 break; 4065 case KeyEvent.KEYCODE_TAB: 4066 if (event.hasNoModifiers()) { 4067 direction = View.FOCUS_FORWARD; 4068 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 4069 direction = View.FOCUS_BACKWARD; 4070 } 4071 break; 4072 } 4073 if (direction != 0) { 4074 View focused = mView.findFocus(); 4075 if (focused != null) { 4076 View v = focused.focusSearch(direction); 4077 if (v != null && v != focused) { 4078 // do the math the get the interesting rect 4079 // of previous focused into the coord system of 4080 // newly focused view 4081 focused.getFocusedRect(mTempRect); 4082 if (mView instanceof ViewGroup) { 4083 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 4084 focused, mTempRect); 4085 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 4086 v, mTempRect); 4087 } 4088 if (v.requestFocus(direction, mTempRect)) { 4089 playSoundEffect(SoundEffectConstants 4090 .getContantForFocusDirection(direction)); 4091 return FINISH_HANDLED; 4092 } 4093 } 4094 4095 // Give the focused view a last chance to handle the dpad key. 4096 if (mView.dispatchUnhandledMove(focused, direction)) { 4097 return FINISH_HANDLED; 4098 } 4099 } else { 4100 // find the best view to give focus to in this non-touch-mode with no-focus 4101 View v = focusSearch(null, direction); 4102 if (v != null && v.requestFocus(direction)) { 4103 return FINISH_HANDLED; 4104 } 4105 } 4106 } 4107 } 4108 return FORWARD; 4109 } 4110 4111 private int processPointerEvent(QueuedInputEvent q) { 4112 final MotionEvent event = (MotionEvent)q.mEvent; 4113 4114 mAttachInfo.mUnbufferedDispatchRequested = false; 4115 boolean handled = mView.dispatchPointerEvent(event); 4116 if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) { 4117 mUnbufferedInputDispatch = true; 4118 if (mConsumeBatchedInputScheduled) { 4119 scheduleConsumeBatchedInputImmediately(); 4120 } 4121 } 4122 return handled ? FINISH_HANDLED : FORWARD; 4123 } 4124 4125 private int processTrackballEvent(QueuedInputEvent q) { 4126 final MotionEvent event = (MotionEvent)q.mEvent; 4127 4128 if (mView.dispatchTrackballEvent(event)) { 4129 return FINISH_HANDLED; 4130 } 4131 return FORWARD; 4132 } 4133 4134 private int processGenericMotionEvent(QueuedInputEvent q) { 4135 final MotionEvent event = (MotionEvent)q.mEvent; 4136 4137 // Deliver the event to the view. 4138 if (mView.dispatchGenericMotionEvent(event)) { 4139 return FINISH_HANDLED; 4140 } 4141 return FORWARD; 4142 } 4143 } 4144 4145 /** 4146 * Performs synthesis of new input events from unhandled input events. 4147 */ 4148 final class SyntheticInputStage extends InputStage { 4149 private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler(); 4150 private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler(); 4151 private final SyntheticTouchNavigationHandler mTouchNavigation = 4152 new SyntheticTouchNavigationHandler(); 4153 private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler(); 4154 4155 public SyntheticInputStage() { 4156 super(null); 4157 } 4158 4159 @Override 4160 protected int onProcess(QueuedInputEvent q) { 4161 q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED; 4162 if (q.mEvent instanceof MotionEvent) { 4163 final MotionEvent event = (MotionEvent)q.mEvent; 4164 final int source = event.getSource(); 4165 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 4166 mTrackball.process(event); 4167 return FINISH_HANDLED; 4168 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 4169 mJoystick.process(event); 4170 return FINISH_HANDLED; 4171 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 4172 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 4173 mTouchNavigation.process(event); 4174 return FINISH_HANDLED; 4175 } 4176 } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) { 4177 mKeyboard.process((KeyEvent)q.mEvent); 4178 return FINISH_HANDLED; 4179 } 4180 4181 return FORWARD; 4182 } 4183 4184 @Override 4185 protected void onDeliverToNext(QueuedInputEvent q) { 4186 if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) { 4187 // Cancel related synthetic events if any prior stage has handled the event. 4188 if (q.mEvent instanceof MotionEvent) { 4189 final MotionEvent event = (MotionEvent)q.mEvent; 4190 final int source = event.getSource(); 4191 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 4192 mTrackball.cancel(event); 4193 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 4194 mJoystick.cancel(event); 4195 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 4196 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 4197 mTouchNavigation.cancel(event); 4198 } 4199 } 4200 } 4201 super.onDeliverToNext(q); 4202 } 4203 } 4204 4205 /** 4206 * Creates dpad events from unhandled trackball movements. 4207 */ 4208 final class SyntheticTrackballHandler { 4209 private final TrackballAxis mX = new TrackballAxis(); 4210 private final TrackballAxis mY = new TrackballAxis(); 4211 private long mLastTime; 4212 4213 public void process(MotionEvent event) { 4214 // Translate the trackball event into DPAD keys and try to deliver those. 4215 long curTime = SystemClock.uptimeMillis(); 4216 if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) { 4217 // It has been too long since the last movement, 4218 // so restart at the beginning. 4219 mX.reset(0); 4220 mY.reset(0); 4221 mLastTime = curTime; 4222 } 4223 4224 final int action = event.getAction(); 4225 final int metaState = event.getMetaState(); 4226 switch (action) { 4227 case MotionEvent.ACTION_DOWN: 4228 mX.reset(2); 4229 mY.reset(2); 4230 enqueueInputEvent(new KeyEvent(curTime, curTime, 4231 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 4232 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4233 InputDevice.SOURCE_KEYBOARD)); 4234 break; 4235 case MotionEvent.ACTION_UP: 4236 mX.reset(2); 4237 mY.reset(2); 4238 enqueueInputEvent(new KeyEvent(curTime, curTime, 4239 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 4240 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4241 InputDevice.SOURCE_KEYBOARD)); 4242 break; 4243 } 4244 4245 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step=" 4246 + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration 4247 + " move=" + event.getX() 4248 + " / Y=" + mY.position + " step=" 4249 + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration 4250 + " move=" + event.getY()); 4251 final float xOff = mX.collect(event.getX(), event.getEventTime(), "X"); 4252 final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y"); 4253 4254 // Generate DPAD events based on the trackball movement. 4255 // We pick the axis that has moved the most as the direction of 4256 // the DPAD. When we generate DPAD events for one axis, then the 4257 // other axis is reset -- we don't want to perform DPAD jumps due 4258 // to slight movements in the trackball when making major movements 4259 // along the other axis. 4260 int keycode = 0; 4261 int movement = 0; 4262 float accel = 1; 4263 if (xOff > yOff) { 4264 movement = mX.generate(); 4265 if (movement != 0) { 4266 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 4267 : KeyEvent.KEYCODE_DPAD_LEFT; 4268 accel = mX.acceleration; 4269 mY.reset(2); 4270 } 4271 } else if (yOff > 0) { 4272 movement = mY.generate(); 4273 if (movement != 0) { 4274 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 4275 : KeyEvent.KEYCODE_DPAD_UP; 4276 accel = mY.acceleration; 4277 mX.reset(2); 4278 } 4279 } 4280 4281 if (keycode != 0) { 4282 if (movement < 0) movement = -movement; 4283 int accelMovement = (int)(movement * accel); 4284 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 4285 + " accelMovement=" + accelMovement 4286 + " accel=" + accel); 4287 if (accelMovement > movement) { 4288 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4289 + keycode); 4290 movement--; 4291 int repeatCount = accelMovement - movement; 4292 enqueueInputEvent(new KeyEvent(curTime, curTime, 4293 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 4294 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4295 InputDevice.SOURCE_KEYBOARD)); 4296 } 4297 while (movement > 0) { 4298 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4299 + keycode); 4300 movement--; 4301 curTime = SystemClock.uptimeMillis(); 4302 enqueueInputEvent(new KeyEvent(curTime, curTime, 4303 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 4304 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4305 InputDevice.SOURCE_KEYBOARD)); 4306 enqueueInputEvent(new KeyEvent(curTime, curTime, 4307 KeyEvent.ACTION_UP, keycode, 0, metaState, 4308 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4309 InputDevice.SOURCE_KEYBOARD)); 4310 } 4311 mLastTime = curTime; 4312 } 4313 } 4314 4315 public void cancel(MotionEvent event) { 4316 mLastTime = Integer.MIN_VALUE; 4317 4318 // If we reach this, we consumed a trackball event. 4319 // Because we will not translate the trackball event into a key event, 4320 // touch mode will not exit, so we exit touch mode here. 4321 if (mView != null && mAdded) { 4322 ensureTouchMode(false); 4323 } 4324 } 4325 } 4326 4327 /** 4328 * Maintains state information for a single trackball axis, generating 4329 * discrete (DPAD) movements based on raw trackball motion. 4330 */ 4331 static final class TrackballAxis { 4332 /** 4333 * The maximum amount of acceleration we will apply. 4334 */ 4335 static final float MAX_ACCELERATION = 20; 4336 4337 /** 4338 * The maximum amount of time (in milliseconds) between events in order 4339 * for us to consider the user to be doing fast trackball movements, 4340 * and thus apply an acceleration. 4341 */ 4342 static final long FAST_MOVE_TIME = 150; 4343 4344 /** 4345 * Scaling factor to the time (in milliseconds) between events to how 4346 * much to multiple/divide the current acceleration. When movement 4347 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4348 * FAST_MOVE_TIME it divides it. 4349 */ 4350 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4351 4352 static final float FIRST_MOVEMENT_THRESHOLD = 0.5f; 4353 static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f; 4354 static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f; 4355 4356 float position; 4357 float acceleration = 1; 4358 long lastMoveTime = 0; 4359 int step; 4360 int dir; 4361 int nonAccelMovement; 4362 4363 void reset(int _step) { 4364 position = 0; 4365 acceleration = 1; 4366 lastMoveTime = 0; 4367 step = _step; 4368 dir = 0; 4369 } 4370 4371 /** 4372 * Add trackball movement into the state. If the direction of movement 4373 * has been reversed, the state is reset before adding the 4374 * movement (so that you don't have to compensate for any previously 4375 * collected movement before see the result of the movement in the 4376 * new direction). 4377 * 4378 * @return Returns the absolute value of the amount of movement 4379 * collected so far. 4380 */ 4381 float collect(float off, long time, String axis) { 4382 long normTime; 4383 if (off > 0) { 4384 normTime = (long)(off * FAST_MOVE_TIME); 4385 if (dir < 0) { 4386 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4387 position = 0; 4388 step = 0; 4389 acceleration = 1; 4390 lastMoveTime = 0; 4391 } 4392 dir = 1; 4393 } else if (off < 0) { 4394 normTime = (long)((-off) * FAST_MOVE_TIME); 4395 if (dir > 0) { 4396 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4397 position = 0; 4398 step = 0; 4399 acceleration = 1; 4400 lastMoveTime = 0; 4401 } 4402 dir = -1; 4403 } else { 4404 normTime = 0; 4405 } 4406 4407 // The number of milliseconds between each movement that is 4408 // considered "normal" and will not result in any acceleration 4409 // or deceleration, scaled by the offset we have here. 4410 if (normTime > 0) { 4411 long delta = time - lastMoveTime; 4412 lastMoveTime = time; 4413 float acc = acceleration; 4414 if (delta < normTime) { 4415 // The user is scrolling rapidly, so increase acceleration. 4416 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4417 if (scale > 1) acc *= scale; 4418 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4419 + off + " normTime=" + normTime + " delta=" + delta 4420 + " scale=" + scale + " acc=" + acc); 4421 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4422 } else { 4423 // The user is scrolling slowly, so decrease acceleration. 4424 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4425 if (scale > 1) acc /= scale; 4426 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4427 + off + " normTime=" + normTime + " delta=" + delta 4428 + " scale=" + scale + " acc=" + acc); 4429 acceleration = acc > 1 ? acc : 1; 4430 } 4431 } 4432 position += off; 4433 return Math.abs(position); 4434 } 4435 4436 /** 4437 * Generate the number of discrete movement events appropriate for 4438 * the currently collected trackball movement. 4439 * 4440 * @return Returns the number of discrete movements, either positive 4441 * or negative, or 0 if there is not enough trackball movement yet 4442 * for a discrete movement. 4443 */ 4444 int generate() { 4445 int movement = 0; 4446 nonAccelMovement = 0; 4447 do { 4448 final int dir = position >= 0 ? 1 : -1; 4449 switch (step) { 4450 // If we are going to execute the first step, then we want 4451 // to do this as soon as possible instead of waiting for 4452 // a full movement, in order to make things look responsive. 4453 case 0: 4454 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) { 4455 return movement; 4456 } 4457 movement += dir; 4458 nonAccelMovement += dir; 4459 step = 1; 4460 break; 4461 // If we have generated the first movement, then we need 4462 // to wait for the second complete trackball motion before 4463 // generating the second discrete movement. 4464 case 1: 4465 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) { 4466 return movement; 4467 } 4468 movement += dir; 4469 nonAccelMovement += dir; 4470 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir; 4471 step = 2; 4472 break; 4473 // After the first two, we generate discrete movements 4474 // consistently with the trackball, applying an acceleration 4475 // if the trackball is moving quickly. This is a simple 4476 // acceleration on top of what we already compute based 4477 // on how quickly the wheel is being turned, to apply 4478 // a longer increasing acceleration to continuous movement 4479 // in one direction. 4480 default: 4481 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) { 4482 return movement; 4483 } 4484 movement += dir; 4485 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD; 4486 float acc = acceleration; 4487 acc *= 1.1f; 4488 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4489 break; 4490 } 4491 } while (true); 4492 } 4493 } 4494 4495 /** 4496 * Creates dpad events from unhandled joystick movements. 4497 */ 4498 final class SyntheticJoystickHandler extends Handler { 4499 private final static String TAG = "SyntheticJoystickHandler"; 4500 private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1; 4501 private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2; 4502 4503 private int mLastXDirection; 4504 private int mLastYDirection; 4505 private int mLastXKeyCode; 4506 private int mLastYKeyCode; 4507 4508 public SyntheticJoystickHandler() { 4509 super(true); 4510 } 4511 4512 @Override 4513 public void handleMessage(Message msg) { 4514 switch (msg.what) { 4515 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT: 4516 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: { 4517 KeyEvent oldEvent = (KeyEvent)msg.obj; 4518 KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent, 4519 SystemClock.uptimeMillis(), 4520 oldEvent.getRepeatCount() + 1); 4521 if (mAttachInfo.mHasWindowFocus) { 4522 enqueueInputEvent(e); 4523 Message m = obtainMessage(msg.what, e); 4524 m.setAsynchronous(true); 4525 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay()); 4526 } 4527 } break; 4528 } 4529 } 4530 4531 public void process(MotionEvent event) { 4532 switch(event.getActionMasked()) { 4533 case MotionEvent.ACTION_CANCEL: 4534 cancel(event); 4535 break; 4536 case MotionEvent.ACTION_MOVE: 4537 update(event, true); 4538 break; 4539 default: 4540 Log.w(TAG, "Unexpected action: " + event.getActionMasked()); 4541 } 4542 } 4543 4544 private void cancel(MotionEvent event) { 4545 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4546 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4547 update(event, false); 4548 } 4549 4550 private void update(MotionEvent event, boolean synthesizeNewKeys) { 4551 final long time = event.getEventTime(); 4552 final int metaState = event.getMetaState(); 4553 final int deviceId = event.getDeviceId(); 4554 final int source = event.getSource(); 4555 4556 int xDirection = joystickAxisValueToDirection( 4557 event.getAxisValue(MotionEvent.AXIS_HAT_X)); 4558 if (xDirection == 0) { 4559 xDirection = joystickAxisValueToDirection(event.getX()); 4560 } 4561 4562 int yDirection = joystickAxisValueToDirection( 4563 event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 4564 if (yDirection == 0) { 4565 yDirection = joystickAxisValueToDirection(event.getY()); 4566 } 4567 4568 if (xDirection != mLastXDirection) { 4569 if (mLastXKeyCode != 0) { 4570 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4571 enqueueInputEvent(new KeyEvent(time, time, 4572 KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState, 4573 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4574 mLastXKeyCode = 0; 4575 } 4576 4577 mLastXDirection = xDirection; 4578 4579 if (xDirection != 0 && synthesizeNewKeys) { 4580 mLastXKeyCode = xDirection > 0 4581 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 4582 final KeyEvent e = new KeyEvent(time, time, 4583 KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState, 4584 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4585 enqueueInputEvent(e); 4586 Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e); 4587 m.setAsynchronous(true); 4588 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4589 } 4590 } 4591 4592 if (yDirection != mLastYDirection) { 4593 if (mLastYKeyCode != 0) { 4594 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4595 enqueueInputEvent(new KeyEvent(time, time, 4596 KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState, 4597 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4598 mLastYKeyCode = 0; 4599 } 4600 4601 mLastYDirection = yDirection; 4602 4603 if (yDirection != 0 && synthesizeNewKeys) { 4604 mLastYKeyCode = yDirection > 0 4605 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 4606 final KeyEvent e = new KeyEvent(time, time, 4607 KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState, 4608 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4609 enqueueInputEvent(e); 4610 Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e); 4611 m.setAsynchronous(true); 4612 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4613 } 4614 } 4615 } 4616 4617 private int joystickAxisValueToDirection(float value) { 4618 if (value >= 0.5f) { 4619 return 1; 4620 } else if (value <= -0.5f) { 4621 return -1; 4622 } else { 4623 return 0; 4624 } 4625 } 4626 } 4627 4628 /** 4629 * Creates dpad events from unhandled touch navigation movements. 4630 */ 4631 final class SyntheticTouchNavigationHandler extends Handler { 4632 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler"; 4633 private static final boolean LOCAL_DEBUG = false; 4634 4635 // Assumed nominal width and height in millimeters of a touch navigation pad, 4636 // if no resolution information is available from the input system. 4637 private static final float DEFAULT_WIDTH_MILLIMETERS = 48; 4638 private static final float DEFAULT_HEIGHT_MILLIMETERS = 48; 4639 4640 /* TODO: These constants should eventually be moved to ViewConfiguration. */ 4641 4642 // The nominal distance traveled to move by one unit. 4643 private static final int TICK_DISTANCE_MILLIMETERS = 12; 4644 4645 // Minimum and maximum fling velocity in ticks per second. 4646 // The minimum velocity should be set such that we perform enough ticks per 4647 // second that the fling appears to be fluid. For example, if we set the minimum 4648 // to 2 ticks per second, then there may be up to half a second delay between the next 4649 // to last and last ticks which is noticeably discrete and jerky. This value should 4650 // probably not be set to anything less than about 4. 4651 // If fling accuracy is a problem then consider tuning the tick distance instead. 4652 private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f; 4653 private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f; 4654 4655 // Fling velocity decay factor applied after each new key is emitted. 4656 // This parameter controls the deceleration and overall duration of the fling. 4657 // The fling stops automatically when its velocity drops below the minimum 4658 // fling velocity defined above. 4659 private static final float FLING_TICK_DECAY = 0.8f; 4660 4661 /* The input device that we are tracking. */ 4662 4663 private int mCurrentDeviceId = -1; 4664 private int mCurrentSource; 4665 private boolean mCurrentDeviceSupported; 4666 4667 /* Configuration for the current input device. */ 4668 4669 // The scaled tick distance. A movement of this amount should generally translate 4670 // into a single dpad event in a given direction. 4671 private float mConfigTickDistance; 4672 4673 // The minimum and maximum scaled fling velocity. 4674 private float mConfigMinFlingVelocity; 4675 private float mConfigMaxFlingVelocity; 4676 4677 /* Tracking state. */ 4678 4679 // The velocity tracker for detecting flings. 4680 private VelocityTracker mVelocityTracker; 4681 4682 // The active pointer id, or -1 if none. 4683 private int mActivePointerId = -1; 4684 4685 // Location where tracking started. 4686 private float mStartX; 4687 private float mStartY; 4688 4689 // Most recently observed position. 4690 private float mLastX; 4691 private float mLastY; 4692 4693 // Accumulated movement delta since the last direction key was sent. 4694 private float mAccumulatedX; 4695 private float mAccumulatedY; 4696 4697 // Set to true if any movement was delivered to the app. 4698 // Implies that tap slop was exceeded. 4699 private boolean mConsumedMovement; 4700 4701 // The most recently sent key down event. 4702 // The keycode remains set until the direction changes or a fling ends 4703 // so that repeated key events may be generated as required. 4704 private long mPendingKeyDownTime; 4705 private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4706 private int mPendingKeyRepeatCount; 4707 private int mPendingKeyMetaState; 4708 4709 // The current fling velocity while a fling is in progress. 4710 private boolean mFlinging; 4711 private float mFlingVelocity; 4712 4713 public SyntheticTouchNavigationHandler() { 4714 super(true); 4715 } 4716 4717 public void process(MotionEvent event) { 4718 // Update the current device information. 4719 final long time = event.getEventTime(); 4720 final int deviceId = event.getDeviceId(); 4721 final int source = event.getSource(); 4722 if (mCurrentDeviceId != deviceId || mCurrentSource != source) { 4723 finishKeys(time); 4724 finishTracking(time); 4725 mCurrentDeviceId = deviceId; 4726 mCurrentSource = source; 4727 mCurrentDeviceSupported = false; 4728 InputDevice device = event.getDevice(); 4729 if (device != null) { 4730 // In order to support an input device, we must know certain 4731 // characteristics about it, such as its size and resolution. 4732 InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X); 4733 InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y); 4734 if (xRange != null && yRange != null) { 4735 mCurrentDeviceSupported = true; 4736 4737 // Infer the resolution if it not actually known. 4738 float xRes = xRange.getResolution(); 4739 if (xRes <= 0) { 4740 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS; 4741 } 4742 float yRes = yRange.getResolution(); 4743 if (yRes <= 0) { 4744 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS; 4745 } 4746 float nominalRes = (xRes + yRes) * 0.5f; 4747 4748 // Precompute all of the configuration thresholds we will need. 4749 mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes; 4750 mConfigMinFlingVelocity = 4751 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4752 mConfigMaxFlingVelocity = 4753 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4754 4755 if (LOCAL_DEBUG) { 4756 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId 4757 + " (" + Integer.toHexString(mCurrentSource) + "): " 4758 + ", mConfigTickDistance=" + mConfigTickDistance 4759 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity 4760 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity); 4761 } 4762 } 4763 } 4764 } 4765 if (!mCurrentDeviceSupported) { 4766 return; 4767 } 4768 4769 // Handle the event. 4770 final int action = event.getActionMasked(); 4771 switch (action) { 4772 case MotionEvent.ACTION_DOWN: { 4773 boolean caughtFling = mFlinging; 4774 finishKeys(time); 4775 finishTracking(time); 4776 mActivePointerId = event.getPointerId(0); 4777 mVelocityTracker = VelocityTracker.obtain(); 4778 mVelocityTracker.addMovement(event); 4779 mStartX = event.getX(); 4780 mStartY = event.getY(); 4781 mLastX = mStartX; 4782 mLastY = mStartY; 4783 mAccumulatedX = 0; 4784 mAccumulatedY = 0; 4785 4786 // If we caught a fling, then pretend that the tap slop has already 4787 // been exceeded to suppress taps whose only purpose is to stop the fling. 4788 mConsumedMovement = caughtFling; 4789 break; 4790 } 4791 4792 case MotionEvent.ACTION_MOVE: 4793 case MotionEvent.ACTION_UP: { 4794 if (mActivePointerId < 0) { 4795 break; 4796 } 4797 final int index = event.findPointerIndex(mActivePointerId); 4798 if (index < 0) { 4799 finishKeys(time); 4800 finishTracking(time); 4801 break; 4802 } 4803 4804 mVelocityTracker.addMovement(event); 4805 final float x = event.getX(index); 4806 final float y = event.getY(index); 4807 mAccumulatedX += x - mLastX; 4808 mAccumulatedY += y - mLastY; 4809 mLastX = x; 4810 mLastY = y; 4811 4812 // Consume any accumulated movement so far. 4813 final int metaState = event.getMetaState(); 4814 consumeAccumulatedMovement(time, metaState); 4815 4816 // Detect taps and flings. 4817 if (action == MotionEvent.ACTION_UP) { 4818 if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4819 // It might be a fling. 4820 mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity); 4821 final float vx = mVelocityTracker.getXVelocity(mActivePointerId); 4822 final float vy = mVelocityTracker.getYVelocity(mActivePointerId); 4823 if (!startFling(time, vx, vy)) { 4824 finishKeys(time); 4825 } 4826 } 4827 finishTracking(time); 4828 } 4829 break; 4830 } 4831 4832 case MotionEvent.ACTION_CANCEL: { 4833 finishKeys(time); 4834 finishTracking(time); 4835 break; 4836 } 4837 } 4838 } 4839 4840 public void cancel(MotionEvent event) { 4841 if (mCurrentDeviceId == event.getDeviceId() 4842 && mCurrentSource == event.getSource()) { 4843 final long time = event.getEventTime(); 4844 finishKeys(time); 4845 finishTracking(time); 4846 } 4847 } 4848 4849 private void finishKeys(long time) { 4850 cancelFling(); 4851 sendKeyUp(time); 4852 } 4853 4854 private void finishTracking(long time) { 4855 if (mActivePointerId >= 0) { 4856 mActivePointerId = -1; 4857 mVelocityTracker.recycle(); 4858 mVelocityTracker = null; 4859 } 4860 } 4861 4862 private void consumeAccumulatedMovement(long time, int metaState) { 4863 final float absX = Math.abs(mAccumulatedX); 4864 final float absY = Math.abs(mAccumulatedY); 4865 if (absX >= absY) { 4866 if (absX >= mConfigTickDistance) { 4867 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX, 4868 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT); 4869 mAccumulatedY = 0; 4870 mConsumedMovement = true; 4871 } 4872 } else { 4873 if (absY >= mConfigTickDistance) { 4874 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY, 4875 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN); 4876 mAccumulatedX = 0; 4877 mConsumedMovement = true; 4878 } 4879 } 4880 } 4881 4882 private float consumeAccumulatedMovement(long time, int metaState, 4883 float accumulator, int negativeKeyCode, int positiveKeyCode) { 4884 while (accumulator <= -mConfigTickDistance) { 4885 sendKeyDownOrRepeat(time, negativeKeyCode, metaState); 4886 accumulator += mConfigTickDistance; 4887 } 4888 while (accumulator >= mConfigTickDistance) { 4889 sendKeyDownOrRepeat(time, positiveKeyCode, metaState); 4890 accumulator -= mConfigTickDistance; 4891 } 4892 return accumulator; 4893 } 4894 4895 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) { 4896 if (mPendingKeyCode != keyCode) { 4897 sendKeyUp(time); 4898 mPendingKeyDownTime = time; 4899 mPendingKeyCode = keyCode; 4900 mPendingKeyRepeatCount = 0; 4901 } else { 4902 mPendingKeyRepeatCount += 1; 4903 } 4904 mPendingKeyMetaState = metaState; 4905 4906 // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1 4907 // but it doesn't quite make sense when simulating the events in this way. 4908 if (LOCAL_DEBUG) { 4909 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode 4910 + ", repeatCount=" + mPendingKeyRepeatCount 4911 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4912 } 4913 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4914 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount, 4915 mPendingKeyMetaState, mCurrentDeviceId, 4916 KeyEvent.FLAG_FALLBACK, mCurrentSource)); 4917 } 4918 4919 private void sendKeyUp(long time) { 4920 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4921 if (LOCAL_DEBUG) { 4922 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode 4923 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4924 } 4925 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4926 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState, 4927 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK, 4928 mCurrentSource)); 4929 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4930 } 4931 } 4932 4933 private boolean startFling(long time, float vx, float vy) { 4934 if (LOCAL_DEBUG) { 4935 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy 4936 + ", min=" + mConfigMinFlingVelocity); 4937 } 4938 4939 // Flings must be oriented in the same direction as the preceding movements. 4940 switch (mPendingKeyCode) { 4941 case KeyEvent.KEYCODE_DPAD_LEFT: 4942 if (-vx >= mConfigMinFlingVelocity 4943 && Math.abs(vy) < mConfigMinFlingVelocity) { 4944 mFlingVelocity = -vx; 4945 break; 4946 } 4947 return false; 4948 4949 case KeyEvent.KEYCODE_DPAD_RIGHT: 4950 if (vx >= mConfigMinFlingVelocity 4951 && Math.abs(vy) < mConfigMinFlingVelocity) { 4952 mFlingVelocity = vx; 4953 break; 4954 } 4955 return false; 4956 4957 case KeyEvent.KEYCODE_DPAD_UP: 4958 if (-vy >= mConfigMinFlingVelocity 4959 && Math.abs(vx) < mConfigMinFlingVelocity) { 4960 mFlingVelocity = -vy; 4961 break; 4962 } 4963 return false; 4964 4965 case KeyEvent.KEYCODE_DPAD_DOWN: 4966 if (vy >= mConfigMinFlingVelocity 4967 && Math.abs(vx) < mConfigMinFlingVelocity) { 4968 mFlingVelocity = vy; 4969 break; 4970 } 4971 return false; 4972 } 4973 4974 // Post the first fling event. 4975 mFlinging = postFling(time); 4976 return mFlinging; 4977 } 4978 4979 private boolean postFling(long time) { 4980 // The idea here is to estimate the time when the pointer would have 4981 // traveled one tick distance unit given the current fling velocity. 4982 // This effect creates continuity of motion. 4983 if (mFlingVelocity >= mConfigMinFlingVelocity) { 4984 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000); 4985 postAtTime(mFlingRunnable, time + delay); 4986 if (LOCAL_DEBUG) { 4987 Log.d(LOCAL_TAG, "Posted fling: velocity=" 4988 + mFlingVelocity + ", delay=" + delay 4989 + ", keyCode=" + mPendingKeyCode); 4990 } 4991 return true; 4992 } 4993 return false; 4994 } 4995 4996 private void cancelFling() { 4997 if (mFlinging) { 4998 removeCallbacks(mFlingRunnable); 4999 mFlinging = false; 5000 } 5001 } 5002 5003 private final Runnable mFlingRunnable = new Runnable() { 5004 @Override 5005 public void run() { 5006 final long time = SystemClock.uptimeMillis(); 5007 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState); 5008 mFlingVelocity *= FLING_TICK_DECAY; 5009 if (!postFling(time)) { 5010 mFlinging = false; 5011 finishKeys(time); 5012 } 5013 } 5014 }; 5015 } 5016 5017 final class SyntheticKeyboardHandler { 5018 public void process(KeyEvent event) { 5019 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) { 5020 return; 5021 } 5022 5023 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 5024 final int keyCode = event.getKeyCode(); 5025 final int metaState = event.getMetaState(); 5026 5027 // Check for fallback actions specified by the key character map. 5028 KeyCharacterMap.FallbackAction fallbackAction = 5029 kcm.getFallbackAction(keyCode, metaState); 5030 if (fallbackAction != null) { 5031 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 5032 KeyEvent fallbackEvent = KeyEvent.obtain( 5033 event.getDownTime(), event.getEventTime(), 5034 event.getAction(), fallbackAction.keyCode, 5035 event.getRepeatCount(), fallbackAction.metaState, 5036 event.getDeviceId(), event.getScanCode(), 5037 flags, event.getSource(), null); 5038 fallbackAction.recycle(); 5039 enqueueInputEvent(fallbackEvent); 5040 } 5041 } 5042 } 5043 5044 /** 5045 * Returns true if the key is used for keyboard navigation. 5046 * @param keyEvent The key event. 5047 * @return True if the key is used for keyboard navigation. 5048 */ 5049 private static boolean isNavigationKey(KeyEvent keyEvent) { 5050 switch (keyEvent.getKeyCode()) { 5051 case KeyEvent.KEYCODE_DPAD_LEFT: 5052 case KeyEvent.KEYCODE_DPAD_RIGHT: 5053 case KeyEvent.KEYCODE_DPAD_UP: 5054 case KeyEvent.KEYCODE_DPAD_DOWN: 5055 case KeyEvent.KEYCODE_DPAD_CENTER: 5056 case KeyEvent.KEYCODE_PAGE_UP: 5057 case KeyEvent.KEYCODE_PAGE_DOWN: 5058 case KeyEvent.KEYCODE_MOVE_HOME: 5059 case KeyEvent.KEYCODE_MOVE_END: 5060 case KeyEvent.KEYCODE_TAB: 5061 case KeyEvent.KEYCODE_SPACE: 5062 case KeyEvent.KEYCODE_ENTER: 5063 return true; 5064 } 5065 return false; 5066 } 5067 5068 /** 5069 * Returns true if the key is used for typing. 5070 * @param keyEvent The key event. 5071 * @return True if the key is used for typing. 5072 */ 5073 private static boolean isTypingKey(KeyEvent keyEvent) { 5074 return keyEvent.getUnicodeChar() > 0; 5075 } 5076 5077 /** 5078 * See if the key event means we should leave touch mode (and leave touch mode if so). 5079 * @param event The key event. 5080 * @return Whether this key event should be consumed (meaning the act of 5081 * leaving touch mode alone is considered the event). 5082 */ 5083 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 5084 // Only relevant in touch mode. 5085 if (!mAttachInfo.mInTouchMode) { 5086 return false; 5087 } 5088 5089 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 5090 final int action = event.getAction(); 5091 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 5092 return false; 5093 } 5094 5095 // Don't leave touch mode if the IME told us not to. 5096 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 5097 return false; 5098 } 5099 5100 // If the key can be used for keyboard navigation then leave touch mode 5101 // and select a focused view if needed (in ensureTouchMode). 5102 // When a new focused view is selected, we consume the navigation key because 5103 // navigation doesn't make much sense unless a view already has focus so 5104 // the key's purpose is to set focus. 5105 if (isNavigationKey(event)) { 5106 return ensureTouchMode(false); 5107 } 5108 5109 // If the key can be used for typing then leave touch mode 5110 // and select a focused view if needed (in ensureTouchMode). 5111 // Always allow the view to process the typing key. 5112 if (isTypingKey(event)) { 5113 ensureTouchMode(false); 5114 return false; 5115 } 5116 5117 return false; 5118 } 5119 5120 /* drag/drop */ 5121 void setLocalDragState(Object obj) { 5122 mLocalDragState = obj; 5123 } 5124 5125 private void handleDragEvent(DragEvent event) { 5126 // From the root, only drag start/end/location are dispatched. entered/exited 5127 // are determined and dispatched by the viewgroup hierarchy, who then report 5128 // that back here for ultimate reporting back to the framework. 5129 if (mView != null && mAdded) { 5130 final int what = event.mAction; 5131 5132 if (what == DragEvent.ACTION_DRAG_EXITED) { 5133 // A direct EXITED event means that the window manager knows we've just crossed 5134 // a window boundary, so the current drag target within this one must have 5135 // just been exited. Send it the usual notifications and then we're done 5136 // for now. 5137 mView.dispatchDragEvent(event); 5138 } else { 5139 // Cache the drag description when the operation starts, then fill it in 5140 // on subsequent calls as a convenience 5141 if (what == DragEvent.ACTION_DRAG_STARTED) { 5142 mCurrentDragView = null; // Start the current-recipient tracking 5143 mDragDescription = event.mClipDescription; 5144 } else { 5145 event.mClipDescription = mDragDescription; 5146 } 5147 5148 // For events with a [screen] location, translate into window coordinates 5149 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 5150 mDragPoint.set(event.mX, event.mY); 5151 if (mTranslator != null) { 5152 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 5153 } 5154 5155 if (mCurScrollY != 0) { 5156 mDragPoint.offset(0, mCurScrollY); 5157 } 5158 5159 event.mX = mDragPoint.x; 5160 event.mY = mDragPoint.y; 5161 } 5162 5163 // Remember who the current drag target is pre-dispatch 5164 final View prevDragView = mCurrentDragView; 5165 5166 // Now dispatch the drag/drop event 5167 boolean result = mView.dispatchDragEvent(event); 5168 5169 // If we changed apparent drag target, tell the OS about it 5170 if (prevDragView != mCurrentDragView) { 5171 try { 5172 if (prevDragView != null) { 5173 mWindowSession.dragRecipientExited(mWindow); 5174 } 5175 if (mCurrentDragView != null) { 5176 mWindowSession.dragRecipientEntered(mWindow); 5177 } 5178 } catch (RemoteException e) { 5179 Slog.e(TAG, "Unable to note drag target change"); 5180 } 5181 } 5182 5183 // Report the drop result when we're done 5184 if (what == DragEvent.ACTION_DROP) { 5185 mDragDescription = null; 5186 try { 5187 Log.i(TAG, "Reporting drop result: " + result); 5188 mWindowSession.reportDropResult(mWindow, result); 5189 } catch (RemoteException e) { 5190 Log.e(TAG, "Unable to report drop result"); 5191 } 5192 } 5193 5194 // When the drag operation ends, release any local state object 5195 // that may have been in use 5196 if (what == DragEvent.ACTION_DRAG_ENDED) { 5197 setLocalDragState(null); 5198 } 5199 } 5200 } 5201 event.recycle(); 5202 } 5203 5204 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 5205 if (mSeq != args.seq) { 5206 // The sequence has changed, so we need to update our value and make 5207 // sure to do a traversal afterward so the window manager is given our 5208 // most recent data. 5209 mSeq = args.seq; 5210 mAttachInfo.mForceReportNewAttributes = true; 5211 scheduleTraversals(); 5212 } 5213 if (mView == null) return; 5214 if (args.localChanges != 0) { 5215 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 5216 } 5217 5218 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 5219 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 5220 mAttachInfo.mGlobalSystemUiVisibility = visibility; 5221 mView.dispatchSystemUiVisibilityChanged(visibility); 5222 } 5223 } 5224 5225 public void handleDispatchDoneAnimating() { 5226 if (mWindowsAnimating) { 5227 mWindowsAnimating = false; 5228 if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded) { 5229 scheduleTraversals(); 5230 } 5231 } 5232 } 5233 5234 public void handleDispatchWindowShown() { 5235 mAttachInfo.mTreeObserver.dispatchOnWindowShown(); 5236 } 5237 5238 public void getLastTouchPoint(Point outLocation) { 5239 outLocation.x = (int) mLastTouchPoint.x; 5240 outLocation.y = (int) mLastTouchPoint.y; 5241 } 5242 5243 public void setDragFocus(View newDragTarget) { 5244 if (mCurrentDragView != newDragTarget) { 5245 mCurrentDragView = newDragTarget; 5246 } 5247 } 5248 5249 private AudioManager getAudioManager() { 5250 if (mView == null) { 5251 throw new IllegalStateException("getAudioManager called when there is no mView"); 5252 } 5253 if (mAudioManager == null) { 5254 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 5255 } 5256 return mAudioManager; 5257 } 5258 5259 public AccessibilityInteractionController getAccessibilityInteractionController() { 5260 if (mView == null) { 5261 throw new IllegalStateException("getAccessibilityInteractionController" 5262 + " called when there is no mView"); 5263 } 5264 if (mAccessibilityInteractionController == null) { 5265 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 5266 } 5267 return mAccessibilityInteractionController; 5268 } 5269 5270 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 5271 boolean insetsPending) throws RemoteException { 5272 5273 float appScale = mAttachInfo.mApplicationScale; 5274 boolean restore = false; 5275 if (params != null && mTranslator != null) { 5276 restore = true; 5277 params.backup(); 5278 mTranslator.translateWindowLayout(params); 5279 } 5280 if (params != null) { 5281 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 5282 } 5283 mPendingConfiguration.seq = 0; 5284 //Log.d(TAG, ">>>>>> CALLING relayout"); 5285 if (params != null && mOrigWindowType != params.type) { 5286 // For compatibility with old apps, don't crash here. 5287 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 5288 Slog.w(TAG, "Window type can not be changed after " 5289 + "the window is added; ignoring change of " + mView); 5290 params.type = mOrigWindowType; 5291 } 5292 } 5293 int relayoutResult = mWindowSession.relayout( 5294 mWindow, mSeq, params, 5295 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 5296 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 5297 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 5298 mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets, 5299 mPendingStableInsets, mPendingConfiguration, mSurface); 5300 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 5301 if (restore) { 5302 params.restore(); 5303 } 5304 5305 if (mTranslator != null) { 5306 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 5307 mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets); 5308 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 5309 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 5310 mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets); 5311 } 5312 return relayoutResult; 5313 } 5314 5315 /** 5316 * {@inheritDoc} 5317 */ 5318 @Override 5319 public void playSoundEffect(int effectId) { 5320 checkThread(); 5321 5322 if (mMediaDisabled) { 5323 return; 5324 } 5325 5326 try { 5327 final AudioManager audioManager = getAudioManager(); 5328 5329 switch (effectId) { 5330 case SoundEffectConstants.CLICK: 5331 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 5332 return; 5333 case SoundEffectConstants.NAVIGATION_DOWN: 5334 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 5335 return; 5336 case SoundEffectConstants.NAVIGATION_LEFT: 5337 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 5338 return; 5339 case SoundEffectConstants.NAVIGATION_RIGHT: 5340 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 5341 return; 5342 case SoundEffectConstants.NAVIGATION_UP: 5343 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 5344 return; 5345 default: 5346 throw new IllegalArgumentException("unknown effect id " + effectId + 5347 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 5348 } 5349 } catch (IllegalStateException e) { 5350 // Exception thrown by getAudioManager() when mView is null 5351 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 5352 e.printStackTrace(); 5353 } 5354 } 5355 5356 /** 5357 * {@inheritDoc} 5358 */ 5359 @Override 5360 public boolean performHapticFeedback(int effectId, boolean always) { 5361 try { 5362 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 5363 } catch (RemoteException e) { 5364 return false; 5365 } 5366 } 5367 5368 /** 5369 * {@inheritDoc} 5370 */ 5371 @Override 5372 public View focusSearch(View focused, int direction) { 5373 checkThread(); 5374 if (!(mView instanceof ViewGroup)) { 5375 return null; 5376 } 5377 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 5378 } 5379 5380 public void debug() { 5381 mView.debug(); 5382 } 5383 5384 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 5385 String innerPrefix = prefix + " "; 5386 writer.print(prefix); writer.println("ViewRoot:"); 5387 writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded); 5388 writer.print(" mRemoved="); writer.println(mRemoved); 5389 writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled="); 5390 writer.println(mConsumeBatchedInputScheduled); 5391 writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled="); 5392 writer.println(mConsumeBatchedInputImmediatelyScheduled); 5393 writer.print(innerPrefix); writer.print("mPendingInputEventCount="); 5394 writer.println(mPendingInputEventCount); 5395 writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled="); 5396 writer.println(mProcessInputEventsScheduled); 5397 writer.print(innerPrefix); writer.print("mTraversalScheduled="); 5398 writer.print(mTraversalScheduled); 5399 if (mTraversalScheduled) { 5400 writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")"); 5401 } else { 5402 writer.println(); 5403 } 5404 mFirstInputStage.dump(innerPrefix, writer); 5405 5406 mChoreographer.dump(prefix, writer); 5407 5408 writer.print(prefix); writer.println("View Hierarchy:"); 5409 dumpViewHierarchy(innerPrefix, writer, mView); 5410 } 5411 5412 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) { 5413 writer.print(prefix); 5414 if (view == null) { 5415 writer.println("null"); 5416 return; 5417 } 5418 writer.println(view.toString()); 5419 if (!(view instanceof ViewGroup)) { 5420 return; 5421 } 5422 ViewGroup grp = (ViewGroup)view; 5423 final int N = grp.getChildCount(); 5424 if (N <= 0) { 5425 return; 5426 } 5427 prefix = prefix + " "; 5428 for (int i=0; i<N; i++) { 5429 dumpViewHierarchy(prefix, writer, grp.getChildAt(i)); 5430 } 5431 } 5432 5433 public void dumpGfxInfo(int[] info) { 5434 info[0] = info[1] = 0; 5435 if (mView != null) { 5436 getGfxInfo(mView, info); 5437 } 5438 } 5439 5440 private static void getGfxInfo(View view, int[] info) { 5441 RenderNode renderNode = view.mRenderNode; 5442 info[0]++; 5443 if (renderNode != null) { 5444 info[1] += renderNode.getDebugSize(); 5445 } 5446 5447 if (view instanceof ViewGroup) { 5448 ViewGroup group = (ViewGroup) view; 5449 5450 int count = group.getChildCount(); 5451 for (int i = 0; i < count; i++) { 5452 getGfxInfo(group.getChildAt(i), info); 5453 } 5454 } 5455 } 5456 5457 /** 5458 * @param immediate True, do now if not in traversal. False, put on queue and do later. 5459 * @return True, request has been queued. False, request has been completed. 5460 */ 5461 boolean die(boolean immediate) { 5462 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 5463 // done by dispatchDetachedFromWindow will cause havoc on return. 5464 if (immediate && !mIsInTraversal) { 5465 doDie(); 5466 return false; 5467 } 5468 5469 if (!mIsDrawing) { 5470 destroyHardwareRenderer(); 5471 } else { 5472 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 5473 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 5474 } 5475 mHandler.sendEmptyMessage(MSG_DIE); 5476 return true; 5477 } 5478 5479 void doDie() { 5480 checkThread(); 5481 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 5482 synchronized (this) { 5483 if (mRemoved) { 5484 return; 5485 } 5486 mRemoved = true; 5487 if (mAdded) { 5488 dispatchDetachedFromWindow(); 5489 } 5490 5491 if (mAdded && !mFirst) { 5492 destroyHardwareRenderer(); 5493 5494 if (mView != null) { 5495 int viewVisibility = mView.getVisibility(); 5496 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 5497 if (mWindowAttributesChanged || viewVisibilityChanged) { 5498 // If layout params have been changed, first give them 5499 // to the window manager to make sure it has the correct 5500 // animation info. 5501 try { 5502 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 5503 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 5504 mWindowSession.finishDrawing(mWindow); 5505 } 5506 } catch (RemoteException e) { 5507 } 5508 } 5509 5510 mSurface.release(); 5511 } 5512 } 5513 5514 mAdded = false; 5515 } 5516 WindowManagerGlobal.getInstance().doRemoveView(this); 5517 } 5518 5519 public void requestUpdateConfiguration(Configuration config) { 5520 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 5521 mHandler.sendMessage(msg); 5522 } 5523 5524 public void loadSystemProperties() { 5525 mHandler.post(new Runnable() { 5526 @Override 5527 public void run() { 5528 // Profiling 5529 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false); 5530 profileRendering(mAttachInfo.mHasWindowFocus); 5531 5532 // Media (used by sound effects) 5533 mMediaDisabled = SystemProperties.getBoolean(PROPERTY_MEDIA_DISABLED, false); 5534 5535 // Hardware rendering 5536 if (mAttachInfo.mHardwareRenderer != null) { 5537 if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) { 5538 invalidate(); 5539 } 5540 } 5541 5542 // Layout debugging 5543 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false); 5544 if (layout != mAttachInfo.mDebugLayout) { 5545 mAttachInfo.mDebugLayout = layout; 5546 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 5547 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 5548 } 5549 } 5550 5551 // detect emulator 5552 mIsEmulator = Build.HARDWARE.contains("goldfish"); 5553 mIsCircularEmulator = 5554 SystemProperties.getBoolean(PROPERTY_EMULATOR_CIRCULAR, false); 5555 } 5556 }); 5557 } 5558 5559 private void destroyHardwareRenderer() { 5560 HardwareRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer; 5561 5562 if (hardwareRenderer != null) { 5563 if (mView != null) { 5564 hardwareRenderer.destroyHardwareResources(mView); 5565 } 5566 hardwareRenderer.destroy(); 5567 hardwareRenderer.setRequested(false); 5568 5569 mAttachInfo.mHardwareRenderer = null; 5570 mAttachInfo.mHardwareAccelerated = false; 5571 } 5572 } 5573 5574 public void dispatchFinishInputConnection(InputConnection connection) { 5575 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 5576 mHandler.sendMessage(msg); 5577 } 5578 5579 public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets, 5580 Rect visibleInsets, Rect stableInsets, boolean reportDraw, Configuration newConfig) { 5581 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 5582 + " contentInsets=" + contentInsets.toShortString() 5583 + " visibleInsets=" + visibleInsets.toShortString() 5584 + " reportDraw=" + reportDraw); 5585 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 5586 if (mTranslator != null) { 5587 mTranslator.translateRectInScreenToAppWindow(frame); 5588 mTranslator.translateRectInScreenToAppWindow(overscanInsets); 5589 mTranslator.translateRectInScreenToAppWindow(contentInsets); 5590 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 5591 } 5592 SomeArgs args = SomeArgs.obtain(); 5593 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 5594 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 5595 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 5596 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 5597 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 5598 args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets; 5599 args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets; 5600 msg.obj = args; 5601 mHandler.sendMessage(msg); 5602 } 5603 5604 public void dispatchMoved(int newX, int newY) { 5605 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 5606 if (mTranslator != null) { 5607 PointF point = new PointF(newX, newY); 5608 mTranslator.translatePointInScreenToAppWindow(point); 5609 newX = (int) (point.x + 0.5); 5610 newY = (int) (point.y + 0.5); 5611 } 5612 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 5613 mHandler.sendMessage(msg); 5614 } 5615 5616 /** 5617 * Represents a pending input event that is waiting in a queue. 5618 * 5619 * Input events are processed in serial order by the timestamp specified by 5620 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 5621 * one input event to the application at a time and waits for the application 5622 * to finish handling it before delivering the next one. 5623 * 5624 * However, because the application or IME can synthesize and inject multiple 5625 * key events at a time without going through the input dispatcher, we end up 5626 * needing a queue on the application's side. 5627 */ 5628 private static final class QueuedInputEvent { 5629 public static final int FLAG_DELIVER_POST_IME = 1 << 0; 5630 public static final int FLAG_DEFERRED = 1 << 1; 5631 public static final int FLAG_FINISHED = 1 << 2; 5632 public static final int FLAG_FINISHED_HANDLED = 1 << 3; 5633 public static final int FLAG_RESYNTHESIZED = 1 << 4; 5634 public static final int FLAG_UNHANDLED = 1 << 5; 5635 5636 public QueuedInputEvent mNext; 5637 5638 public InputEvent mEvent; 5639 public InputEventReceiver mReceiver; 5640 public int mFlags; 5641 5642 public boolean shouldSkipIme() { 5643 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) { 5644 return true; 5645 } 5646 return mEvent instanceof MotionEvent 5647 && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER); 5648 } 5649 5650 public boolean shouldSendToSynthesizer() { 5651 if ((mFlags & FLAG_UNHANDLED) != 0) { 5652 return true; 5653 } 5654 5655 return false; 5656 } 5657 5658 @Override 5659 public String toString() { 5660 StringBuilder sb = new StringBuilder("QueuedInputEvent{flags="); 5661 boolean hasPrevious = false; 5662 hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb); 5663 hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb); 5664 hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb); 5665 hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb); 5666 hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb); 5667 hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb); 5668 if (!hasPrevious) { 5669 sb.append("0"); 5670 } 5671 sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false")); 5672 sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false")); 5673 sb.append(", mEvent=" + mEvent + "}"); 5674 return sb.toString(); 5675 } 5676 5677 private boolean flagToString(String name, int flag, 5678 boolean hasPrevious, StringBuilder sb) { 5679 if ((mFlags & flag) != 0) { 5680 if (hasPrevious) { 5681 sb.append("|"); 5682 } 5683 sb.append(name); 5684 return true; 5685 } 5686 return hasPrevious; 5687 } 5688 } 5689 5690 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 5691 InputEventReceiver receiver, int flags) { 5692 QueuedInputEvent q = mQueuedInputEventPool; 5693 if (q != null) { 5694 mQueuedInputEventPoolSize -= 1; 5695 mQueuedInputEventPool = q.mNext; 5696 q.mNext = null; 5697 } else { 5698 q = new QueuedInputEvent(); 5699 } 5700 5701 q.mEvent = event; 5702 q.mReceiver = receiver; 5703 q.mFlags = flags; 5704 return q; 5705 } 5706 5707 private void recycleQueuedInputEvent(QueuedInputEvent q) { 5708 q.mEvent = null; 5709 q.mReceiver = null; 5710 5711 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 5712 mQueuedInputEventPoolSize += 1; 5713 q.mNext = mQueuedInputEventPool; 5714 mQueuedInputEventPool = q; 5715 } 5716 } 5717 5718 void enqueueInputEvent(InputEvent event) { 5719 enqueueInputEvent(event, null, 0, false); 5720 } 5721 5722 void enqueueInputEvent(InputEvent event, 5723 InputEventReceiver receiver, int flags, boolean processImmediately) { 5724 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 5725 5726 // Always enqueue the input event in order, regardless of its time stamp. 5727 // We do this because the application or the IME may inject key events 5728 // in response to touch events and we want to ensure that the injected keys 5729 // are processed in the order they were received and we cannot trust that 5730 // the time stamp of injected events are monotonic. 5731 QueuedInputEvent last = mPendingInputEventTail; 5732 if (last == null) { 5733 mPendingInputEventHead = q; 5734 mPendingInputEventTail = q; 5735 } else { 5736 last.mNext = q; 5737 mPendingInputEventTail = q; 5738 } 5739 mPendingInputEventCount += 1; 5740 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5741 mPendingInputEventCount); 5742 5743 if (processImmediately) { 5744 doProcessInputEvents(); 5745 } else { 5746 scheduleProcessInputEvents(); 5747 } 5748 } 5749 5750 private void scheduleProcessInputEvents() { 5751 if (!mProcessInputEventsScheduled) { 5752 mProcessInputEventsScheduled = true; 5753 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 5754 msg.setAsynchronous(true); 5755 mHandler.sendMessage(msg); 5756 } 5757 } 5758 5759 void doProcessInputEvents() { 5760 // Deliver all pending input events in the queue. 5761 while (mPendingInputEventHead != null) { 5762 QueuedInputEvent q = mPendingInputEventHead; 5763 mPendingInputEventHead = q.mNext; 5764 if (mPendingInputEventHead == null) { 5765 mPendingInputEventTail = null; 5766 } 5767 q.mNext = null; 5768 5769 mPendingInputEventCount -= 1; 5770 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5771 mPendingInputEventCount); 5772 5773 deliverInputEvent(q); 5774 } 5775 5776 // We are done processing all input events that we can process right now 5777 // so we can clear the pending flag immediately. 5778 if (mProcessInputEventsScheduled) { 5779 mProcessInputEventsScheduled = false; 5780 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 5781 } 5782 } 5783 5784 private void deliverInputEvent(QueuedInputEvent q) { 5785 Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent", 5786 q.mEvent.getSequenceNumber()); 5787 if (mInputEventConsistencyVerifier != null) { 5788 mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0); 5789 } 5790 5791 InputStage stage; 5792 if (q.shouldSendToSynthesizer()) { 5793 stage = mSyntheticInputStage; 5794 } else { 5795 stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage; 5796 } 5797 5798 if (stage != null) { 5799 stage.deliver(q); 5800 } else { 5801 finishInputEvent(q); 5802 } 5803 } 5804 5805 private void finishInputEvent(QueuedInputEvent q) { 5806 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent", 5807 q.mEvent.getSequenceNumber()); 5808 5809 if (q.mReceiver != null) { 5810 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0; 5811 q.mReceiver.finishInputEvent(q.mEvent, handled); 5812 } else { 5813 q.mEvent.recycleIfNeededAfterDispatch(); 5814 } 5815 5816 recycleQueuedInputEvent(q); 5817 } 5818 5819 static boolean isTerminalInputEvent(InputEvent event) { 5820 if (event instanceof KeyEvent) { 5821 final KeyEvent keyEvent = (KeyEvent)event; 5822 return keyEvent.getAction() == KeyEvent.ACTION_UP; 5823 } else { 5824 final MotionEvent motionEvent = (MotionEvent)event; 5825 final int action = motionEvent.getAction(); 5826 return action == MotionEvent.ACTION_UP 5827 || action == MotionEvent.ACTION_CANCEL 5828 || action == MotionEvent.ACTION_HOVER_EXIT; 5829 } 5830 } 5831 5832 void scheduleConsumeBatchedInput() { 5833 if (!mConsumeBatchedInputScheduled) { 5834 mConsumeBatchedInputScheduled = true; 5835 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 5836 mConsumedBatchedInputRunnable, null); 5837 } 5838 } 5839 5840 void unscheduleConsumeBatchedInput() { 5841 if (mConsumeBatchedInputScheduled) { 5842 mConsumeBatchedInputScheduled = false; 5843 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 5844 mConsumedBatchedInputRunnable, null); 5845 } 5846 } 5847 5848 void scheduleConsumeBatchedInputImmediately() { 5849 if (!mConsumeBatchedInputImmediatelyScheduled) { 5850 unscheduleConsumeBatchedInput(); 5851 mConsumeBatchedInputImmediatelyScheduled = true; 5852 mHandler.post(mConsumeBatchedInputImmediatelyRunnable); 5853 } 5854 } 5855 5856 void doConsumeBatchedInput(long frameTimeNanos) { 5857 if (mConsumeBatchedInputScheduled) { 5858 mConsumeBatchedInputScheduled = false; 5859 if (mInputEventReceiver != null) { 5860 if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos) 5861 && frameTimeNanos != -1) { 5862 // If we consumed a batch here, we want to go ahead and schedule the 5863 // consumption of batched input events on the next frame. Otherwise, we would 5864 // wait until we have more input events pending and might get starved by other 5865 // things occurring in the process. If the frame time is -1, however, then 5866 // we're in a non-batching mode, so there's no need to schedule this. 5867 scheduleConsumeBatchedInput(); 5868 } 5869 } 5870 doProcessInputEvents(); 5871 } 5872 } 5873 5874 final class TraversalRunnable implements Runnable { 5875 @Override 5876 public void run() { 5877 doTraversal(); 5878 } 5879 } 5880 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 5881 5882 final class WindowInputEventReceiver extends InputEventReceiver { 5883 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 5884 super(inputChannel, looper); 5885 } 5886 5887 @Override 5888 public void onInputEvent(InputEvent event) { 5889 enqueueInputEvent(event, this, 0, true); 5890 } 5891 5892 @Override 5893 public void onBatchedInputEventPending() { 5894 if (mUnbufferedInputDispatch) { 5895 super.onBatchedInputEventPending(); 5896 } else { 5897 scheduleConsumeBatchedInput(); 5898 } 5899 } 5900 5901 @Override 5902 public void dispose() { 5903 unscheduleConsumeBatchedInput(); 5904 super.dispose(); 5905 } 5906 } 5907 WindowInputEventReceiver mInputEventReceiver; 5908 5909 final class ConsumeBatchedInputRunnable implements Runnable { 5910 @Override 5911 public void run() { 5912 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 5913 } 5914 } 5915 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 5916 new ConsumeBatchedInputRunnable(); 5917 boolean mConsumeBatchedInputScheduled; 5918 5919 final class ConsumeBatchedInputImmediatelyRunnable implements Runnable { 5920 @Override 5921 public void run() { 5922 doConsumeBatchedInput(-1); 5923 } 5924 } 5925 final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable = 5926 new ConsumeBatchedInputImmediatelyRunnable(); 5927 boolean mConsumeBatchedInputImmediatelyScheduled; 5928 5929 final class InvalidateOnAnimationRunnable implements Runnable { 5930 private boolean mPosted; 5931 private final ArrayList<View> mViews = new ArrayList<View>(); 5932 private final ArrayList<AttachInfo.InvalidateInfo> mViewRects = 5933 new ArrayList<AttachInfo.InvalidateInfo>(); 5934 private View[] mTempViews; 5935 private AttachInfo.InvalidateInfo[] mTempViewRects; 5936 5937 public void addView(View view) { 5938 synchronized (this) { 5939 mViews.add(view); 5940 postIfNeededLocked(); 5941 } 5942 } 5943 5944 public void addViewRect(AttachInfo.InvalidateInfo info) { 5945 synchronized (this) { 5946 mViewRects.add(info); 5947 postIfNeededLocked(); 5948 } 5949 } 5950 5951 public void removeView(View view) { 5952 synchronized (this) { 5953 mViews.remove(view); 5954 5955 for (int i = mViewRects.size(); i-- > 0; ) { 5956 AttachInfo.InvalidateInfo info = mViewRects.get(i); 5957 if (info.target == view) { 5958 mViewRects.remove(i); 5959 info.recycle(); 5960 } 5961 } 5962 5963 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 5964 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 5965 mPosted = false; 5966 } 5967 } 5968 } 5969 5970 @Override 5971 public void run() { 5972 final int viewCount; 5973 final int viewRectCount; 5974 synchronized (this) { 5975 mPosted = false; 5976 5977 viewCount = mViews.size(); 5978 if (viewCount != 0) { 5979 mTempViews = mViews.toArray(mTempViews != null 5980 ? mTempViews : new View[viewCount]); 5981 mViews.clear(); 5982 } 5983 5984 viewRectCount = mViewRects.size(); 5985 if (viewRectCount != 0) { 5986 mTempViewRects = mViewRects.toArray(mTempViewRects != null 5987 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 5988 mViewRects.clear(); 5989 } 5990 } 5991 5992 for (int i = 0; i < viewCount; i++) { 5993 mTempViews[i].invalidate(); 5994 mTempViews[i] = null; 5995 } 5996 5997 for (int i = 0; i < viewRectCount; i++) { 5998 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 5999 info.target.invalidate(info.left, info.top, info.right, info.bottom); 6000 info.recycle(); 6001 } 6002 } 6003 6004 private void postIfNeededLocked() { 6005 if (!mPosted) { 6006 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 6007 mPosted = true; 6008 } 6009 } 6010 } 6011 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 6012 new InvalidateOnAnimationRunnable(); 6013 6014 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 6015 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 6016 mHandler.sendMessageDelayed(msg, delayMilliseconds); 6017 } 6018 6019 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 6020 long delayMilliseconds) { 6021 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 6022 mHandler.sendMessageDelayed(msg, delayMilliseconds); 6023 } 6024 6025 public void dispatchInvalidateOnAnimation(View view) { 6026 mInvalidateOnAnimationRunnable.addView(view); 6027 } 6028 6029 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 6030 mInvalidateOnAnimationRunnable.addViewRect(info); 6031 } 6032 6033 public void cancelInvalidate(View view) { 6034 mHandler.removeMessages(MSG_INVALIDATE, view); 6035 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 6036 // them to the pool 6037 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 6038 mInvalidateOnAnimationRunnable.removeView(view); 6039 } 6040 6041 public void dispatchInputEvent(InputEvent event) { 6042 dispatchInputEvent(event, null); 6043 } 6044 6045 public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) { 6046 SomeArgs args = SomeArgs.obtain(); 6047 args.arg1 = event; 6048 args.arg2 = receiver; 6049 Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args); 6050 msg.setAsynchronous(true); 6051 mHandler.sendMessage(msg); 6052 } 6053 6054 public void synthesizeInputEvent(InputEvent event) { 6055 Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event); 6056 msg.setAsynchronous(true); 6057 mHandler.sendMessage(msg); 6058 } 6059 6060 public void dispatchKeyFromIme(KeyEvent event) { 6061 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 6062 msg.setAsynchronous(true); 6063 mHandler.sendMessage(msg); 6064 } 6065 6066 /** 6067 * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events. 6068 * 6069 * Note that it is the responsibility of the caller of this API to recycle the InputEvent it 6070 * passes in. 6071 */ 6072 public void dispatchUnhandledInputEvent(InputEvent event) { 6073 if (event instanceof MotionEvent) { 6074 event = MotionEvent.obtain((MotionEvent) event); 6075 } 6076 synthesizeInputEvent(event); 6077 } 6078 6079 public void dispatchAppVisibility(boolean visible) { 6080 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 6081 msg.arg1 = visible ? 1 : 0; 6082 mHandler.sendMessage(msg); 6083 } 6084 6085 public void dispatchGetNewSurface() { 6086 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 6087 mHandler.sendMessage(msg); 6088 } 6089 6090 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 6091 Message msg = Message.obtain(); 6092 msg.what = MSG_WINDOW_FOCUS_CHANGED; 6093 msg.arg1 = hasFocus ? 1 : 0; 6094 msg.arg2 = inTouchMode ? 1 : 0; 6095 mHandler.sendMessage(msg); 6096 } 6097 6098 public void dispatchWindowShown() { 6099 mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN); 6100 } 6101 6102 public void dispatchCloseSystemDialogs(String reason) { 6103 Message msg = Message.obtain(); 6104 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 6105 msg.obj = reason; 6106 mHandler.sendMessage(msg); 6107 } 6108 6109 public void dispatchDragEvent(DragEvent event) { 6110 final int what; 6111 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 6112 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 6113 mHandler.removeMessages(what); 6114 } else { 6115 what = MSG_DISPATCH_DRAG_EVENT; 6116 } 6117 Message msg = mHandler.obtainMessage(what, event); 6118 mHandler.sendMessage(msg); 6119 } 6120 6121 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 6122 int localValue, int localChanges) { 6123 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 6124 args.seq = seq; 6125 args.globalVisibility = globalVisibility; 6126 args.localValue = localValue; 6127 args.localChanges = localChanges; 6128 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 6129 } 6130 6131 public void dispatchDoneAnimating() { 6132 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 6133 } 6134 6135 public void dispatchCheckFocus() { 6136 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 6137 // This will result in a call to checkFocus() below. 6138 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 6139 } 6140 } 6141 6142 /** 6143 * Post a callback to send a 6144 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 6145 * This event is send at most once every 6146 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 6147 */ 6148 private void postSendWindowContentChangedCallback(View source, int changeType) { 6149 if (mSendWindowContentChangedAccessibilityEvent == null) { 6150 mSendWindowContentChangedAccessibilityEvent = 6151 new SendWindowContentChangedAccessibilityEvent(); 6152 } 6153 mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType); 6154 } 6155 6156 /** 6157 * Remove a posted callback to send a 6158 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 6159 */ 6160 private void removeSendWindowContentChangedCallback() { 6161 if (mSendWindowContentChangedAccessibilityEvent != null) { 6162 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 6163 } 6164 } 6165 6166 @Override 6167 public boolean showContextMenuForChild(View originalView) { 6168 return false; 6169 } 6170 6171 @Override 6172 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 6173 return null; 6174 } 6175 6176 @Override 6177 public void createContextMenu(ContextMenu menu) { 6178 } 6179 6180 @Override 6181 public void childDrawableStateChanged(View child) { 6182 } 6183 6184 @Override 6185 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 6186 if (mView == null) { 6187 return false; 6188 } 6189 // Intercept accessibility focus events fired by virtual nodes to keep 6190 // track of accessibility focus position in such nodes. 6191 final int eventType = event.getEventType(); 6192 switch (eventType) { 6193 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 6194 final long sourceNodeId = event.getSourceNodeId(); 6195 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 6196 sourceNodeId); 6197 View source = mView.findViewByAccessibilityId(accessibilityViewId); 6198 if (source != null) { 6199 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 6200 if (provider != null) { 6201 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 6202 sourceNodeId); 6203 final AccessibilityNodeInfo node; 6204 if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) { 6205 node = provider.createAccessibilityNodeInfo( 6206 AccessibilityNodeProvider.HOST_VIEW_ID); 6207 } else { 6208 node = provider.createAccessibilityNodeInfo(virtualNodeId); 6209 } 6210 setAccessibilityFocus(source, node); 6211 } 6212 } 6213 } break; 6214 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 6215 final long sourceNodeId = event.getSourceNodeId(); 6216 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 6217 sourceNodeId); 6218 View source = mView.findViewByAccessibilityId(accessibilityViewId); 6219 if (source != null) { 6220 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 6221 if (provider != null) { 6222 setAccessibilityFocus(null, null); 6223 } 6224 } 6225 } break; 6226 6227 6228 case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: { 6229 if (mAccessibilityFocusedHost != null && mAccessibilityFocusedVirtualView != null) { 6230 // We care only for changes rooted in the focused host. 6231 final long eventSourceId = event.getSourceNodeId(); 6232 final int hostViewId = AccessibilityNodeInfo.getAccessibilityViewId( 6233 eventSourceId); 6234 if (hostViewId != mAccessibilityFocusedHost.getAccessibilityViewId()) { 6235 break; 6236 } 6237 6238 // We only care about changes that may change the virtual focused view bounds. 6239 final int changes = event.getContentChangeTypes(); 6240 if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) != 0 6241 || changes == AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) { 6242 AccessibilityNodeProvider provider = mAccessibilityFocusedHost 6243 .getAccessibilityNodeProvider(); 6244 if (provider != null) { 6245 final int virtualChildId = AccessibilityNodeInfo.getVirtualDescendantId( 6246 mAccessibilityFocusedVirtualView.getSourceNodeId()); 6247 if (virtualChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) { 6248 mAccessibilityFocusedVirtualView = provider 6249 .createAccessibilityNodeInfo( 6250 AccessibilityNodeProvider.HOST_VIEW_ID); 6251 } else { 6252 mAccessibilityFocusedVirtualView = provider 6253 .createAccessibilityNodeInfo(virtualChildId); 6254 } 6255 } 6256 } 6257 } 6258 } break; 6259 } 6260 mAccessibilityManager.sendAccessibilityEvent(event); 6261 return true; 6262 } 6263 6264 @Override 6265 public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { 6266 postSendWindowContentChangedCallback(source, changeType); 6267 } 6268 6269 @Override 6270 public boolean canResolveLayoutDirection() { 6271 return true; 6272 } 6273 6274 @Override 6275 public boolean isLayoutDirectionResolved() { 6276 return true; 6277 } 6278 6279 @Override 6280 public int getLayoutDirection() { 6281 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6282 } 6283 6284 @Override 6285 public boolean canResolveTextDirection() { 6286 return true; 6287 } 6288 6289 @Override 6290 public boolean isTextDirectionResolved() { 6291 return true; 6292 } 6293 6294 @Override 6295 public int getTextDirection() { 6296 return View.TEXT_DIRECTION_RESOLVED_DEFAULT; 6297 } 6298 6299 @Override 6300 public boolean canResolveTextAlignment() { 6301 return true; 6302 } 6303 6304 @Override 6305 public boolean isTextAlignmentResolved() { 6306 return true; 6307 } 6308 6309 @Override 6310 public int getTextAlignment() { 6311 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT; 6312 } 6313 6314 private View getCommonPredecessor(View first, View second) { 6315 if (mTempHashSet == null) { 6316 mTempHashSet = new HashSet<View>(); 6317 } 6318 HashSet<View> seen = mTempHashSet; 6319 seen.clear(); 6320 View firstCurrent = first; 6321 while (firstCurrent != null) { 6322 seen.add(firstCurrent); 6323 ViewParent firstCurrentParent = firstCurrent.mParent; 6324 if (firstCurrentParent instanceof View) { 6325 firstCurrent = (View) firstCurrentParent; 6326 } else { 6327 firstCurrent = null; 6328 } 6329 } 6330 View secondCurrent = second; 6331 while (secondCurrent != null) { 6332 if (seen.contains(secondCurrent)) { 6333 seen.clear(); 6334 return secondCurrent; 6335 } 6336 ViewParent secondCurrentParent = secondCurrent.mParent; 6337 if (secondCurrentParent instanceof View) { 6338 secondCurrent = (View) secondCurrentParent; 6339 } else { 6340 secondCurrent = null; 6341 } 6342 } 6343 seen.clear(); 6344 return null; 6345 } 6346 6347 void checkThread() { 6348 if (mThread != Thread.currentThread()) { 6349 throw new CalledFromWrongThreadException( 6350 "Only the original thread that created a view hierarchy can touch its views."); 6351 } 6352 } 6353 6354 @Override 6355 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 6356 // ViewAncestor never intercepts touch event, so this can be a no-op 6357 } 6358 6359 @Override 6360 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 6361 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 6362 if (rectangle != null) { 6363 mTempRect.set(rectangle); 6364 mTempRect.offset(0, -mCurScrollY); 6365 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6366 try { 6367 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect); 6368 } catch (RemoteException re) { 6369 /* ignore */ 6370 } 6371 } 6372 return scrolled; 6373 } 6374 6375 @Override 6376 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 6377 // Do nothing. 6378 } 6379 6380 @Override 6381 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { 6382 return false; 6383 } 6384 6385 @Override 6386 public void onStopNestedScroll(View target) { 6387 } 6388 6389 @Override 6390 public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { 6391 } 6392 6393 @Override 6394 public void onNestedScroll(View target, int dxConsumed, int dyConsumed, 6395 int dxUnconsumed, int dyUnconsumed) { 6396 } 6397 6398 @Override 6399 public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { 6400 } 6401 6402 @Override 6403 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { 6404 return false; 6405 } 6406 6407 @Override 6408 public boolean onNestedPreFling(View target, float velocityX, float velocityY) { 6409 return false; 6410 } 6411 6412 void changeCanvasOpacity(boolean opaque) { 6413 Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque); 6414 if (mAttachInfo.mHardwareRenderer != null) { 6415 mAttachInfo.mHardwareRenderer.setOpaque(opaque); 6416 } 6417 } 6418 6419 class TakenSurfaceHolder extends BaseSurfaceHolder { 6420 @Override 6421 public boolean onAllowLockCanvas() { 6422 return mDrawingAllowed; 6423 } 6424 6425 @Override 6426 public void onRelayoutContainer() { 6427 // Not currently interesting -- from changing between fixed and layout size. 6428 } 6429 6430 @Override 6431 public void setFormat(int format) { 6432 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 6433 } 6434 6435 @Override 6436 public void setType(int type) { 6437 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 6438 } 6439 6440 @Override 6441 public void onUpdateSurface() { 6442 // We take care of format and type changes on our own. 6443 throw new IllegalStateException("Shouldn't be here"); 6444 } 6445 6446 @Override 6447 public boolean isCreating() { 6448 return mIsCreating; 6449 } 6450 6451 @Override 6452 public void setFixedSize(int width, int height) { 6453 throw new UnsupportedOperationException( 6454 "Currently only support sizing from layout"); 6455 } 6456 6457 @Override 6458 public void setKeepScreenOn(boolean screenOn) { 6459 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 6460 } 6461 } 6462 6463 static class W extends IWindow.Stub { 6464 private final WeakReference<ViewRootImpl> mViewAncestor; 6465 private final IWindowSession mWindowSession; 6466 6467 W(ViewRootImpl viewAncestor) { 6468 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 6469 mWindowSession = viewAncestor.mWindowSession; 6470 } 6471 6472 @Override 6473 public void resized(Rect frame, Rect overscanInsets, Rect contentInsets, 6474 Rect visibleInsets, Rect stableInsets, boolean reportDraw, 6475 Configuration newConfig) { 6476 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6477 if (viewAncestor != null) { 6478 viewAncestor.dispatchResized(frame, overscanInsets, contentInsets, 6479 visibleInsets, stableInsets, reportDraw, newConfig); 6480 } 6481 } 6482 6483 @Override 6484 public void moved(int newX, int newY) { 6485 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6486 if (viewAncestor != null) { 6487 viewAncestor.dispatchMoved(newX, newY); 6488 } 6489 } 6490 6491 @Override 6492 public void dispatchAppVisibility(boolean visible) { 6493 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6494 if (viewAncestor != null) { 6495 viewAncestor.dispatchAppVisibility(visible); 6496 } 6497 } 6498 6499 @Override 6500 public void dispatchGetNewSurface() { 6501 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6502 if (viewAncestor != null) { 6503 viewAncestor.dispatchGetNewSurface(); 6504 } 6505 } 6506 6507 @Override 6508 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 6509 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6510 if (viewAncestor != null) { 6511 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 6512 } 6513 } 6514 6515 private static int checkCallingPermission(String permission) { 6516 try { 6517 return ActivityManagerNative.getDefault().checkPermission( 6518 permission, Binder.getCallingPid(), Binder.getCallingUid()); 6519 } catch (RemoteException e) { 6520 return PackageManager.PERMISSION_DENIED; 6521 } 6522 } 6523 6524 @Override 6525 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 6526 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6527 if (viewAncestor != null) { 6528 final View view = viewAncestor.mView; 6529 if (view != null) { 6530 if (checkCallingPermission(Manifest.permission.DUMP) != 6531 PackageManager.PERMISSION_GRANTED) { 6532 throw new SecurityException("Insufficient permissions to invoke" 6533 + " executeCommand() from pid=" + Binder.getCallingPid() 6534 + ", uid=" + Binder.getCallingUid()); 6535 } 6536 6537 OutputStream clientStream = null; 6538 try { 6539 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 6540 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 6541 } catch (IOException e) { 6542 e.printStackTrace(); 6543 } finally { 6544 if (clientStream != null) { 6545 try { 6546 clientStream.close(); 6547 } catch (IOException e) { 6548 e.printStackTrace(); 6549 } 6550 } 6551 } 6552 } 6553 } 6554 } 6555 6556 @Override 6557 public void closeSystemDialogs(String reason) { 6558 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6559 if (viewAncestor != null) { 6560 viewAncestor.dispatchCloseSystemDialogs(reason); 6561 } 6562 } 6563 6564 @Override 6565 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 6566 boolean sync) { 6567 if (sync) { 6568 try { 6569 mWindowSession.wallpaperOffsetsComplete(asBinder()); 6570 } catch (RemoteException e) { 6571 } 6572 } 6573 } 6574 6575 @Override 6576 public void dispatchWallpaperCommand(String action, int x, int y, 6577 int z, Bundle extras, boolean sync) { 6578 if (sync) { 6579 try { 6580 mWindowSession.wallpaperCommandComplete(asBinder(), null); 6581 } catch (RemoteException e) { 6582 } 6583 } 6584 } 6585 6586 /* Drag/drop */ 6587 @Override 6588 public void dispatchDragEvent(DragEvent event) { 6589 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6590 if (viewAncestor != null) { 6591 viewAncestor.dispatchDragEvent(event); 6592 } 6593 } 6594 6595 @Override 6596 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 6597 int localValue, int localChanges) { 6598 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6599 if (viewAncestor != null) { 6600 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 6601 localValue, localChanges); 6602 } 6603 } 6604 6605 @Override 6606 public void doneAnimating() { 6607 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6608 if (viewAncestor != null) { 6609 viewAncestor.dispatchDoneAnimating(); 6610 } 6611 } 6612 6613 @Override 6614 public void dispatchWindowShown() { 6615 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6616 if (viewAncestor != null) { 6617 viewAncestor.dispatchWindowShown(); 6618 } 6619 } 6620 } 6621 6622 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 6623 public CalledFromWrongThreadException(String msg) { 6624 super(msg); 6625 } 6626 } 6627 6628 static RunQueue getRunQueue() { 6629 RunQueue rq = sRunQueues.get(); 6630 if (rq != null) { 6631 return rq; 6632 } 6633 rq = new RunQueue(); 6634 sRunQueues.set(rq); 6635 return rq; 6636 } 6637 6638 /** 6639 * The run queue is used to enqueue pending work from Views when no Handler is 6640 * attached. The work is executed during the next call to performTraversals on 6641 * the thread. 6642 * @hide 6643 */ 6644 static final class RunQueue { 6645 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 6646 6647 void post(Runnable action) { 6648 postDelayed(action, 0); 6649 } 6650 6651 void postDelayed(Runnable action, long delayMillis) { 6652 HandlerAction handlerAction = new HandlerAction(); 6653 handlerAction.action = action; 6654 handlerAction.delay = delayMillis; 6655 6656 synchronized (mActions) { 6657 mActions.add(handlerAction); 6658 } 6659 } 6660 6661 void removeCallbacks(Runnable action) { 6662 final HandlerAction handlerAction = new HandlerAction(); 6663 handlerAction.action = action; 6664 6665 synchronized (mActions) { 6666 final ArrayList<HandlerAction> actions = mActions; 6667 6668 while (actions.remove(handlerAction)) { 6669 // Keep going 6670 } 6671 } 6672 } 6673 6674 void executeActions(Handler handler) { 6675 synchronized (mActions) { 6676 final ArrayList<HandlerAction> actions = mActions; 6677 final int count = actions.size(); 6678 6679 for (int i = 0; i < count; i++) { 6680 final HandlerAction handlerAction = actions.get(i); 6681 handler.postDelayed(handlerAction.action, handlerAction.delay); 6682 } 6683 6684 actions.clear(); 6685 } 6686 } 6687 6688 private static class HandlerAction { 6689 Runnable action; 6690 long delay; 6691 6692 @Override 6693 public boolean equals(Object o) { 6694 if (this == o) return true; 6695 if (o == null || getClass() != o.getClass()) return false; 6696 6697 HandlerAction that = (HandlerAction) o; 6698 return !(action != null ? !action.equals(that.action) : that.action != null); 6699 6700 } 6701 6702 @Override 6703 public int hashCode() { 6704 int result = action != null ? action.hashCode() : 0; 6705 result = 31 * result + (int) (delay ^ (delay >>> 32)); 6706 return result; 6707 } 6708 } 6709 } 6710 6711 /** 6712 * Class for managing the accessibility interaction connection 6713 * based on the global accessibility state. 6714 */ 6715 final class AccessibilityInteractionConnectionManager 6716 implements AccessibilityStateChangeListener { 6717 @Override 6718 public void onAccessibilityStateChanged(boolean enabled) { 6719 if (enabled) { 6720 ensureConnection(); 6721 if (mAttachInfo.mHasWindowFocus) { 6722 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 6723 View focusedView = mView.findFocus(); 6724 if (focusedView != null && focusedView != mView) { 6725 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6726 } 6727 } 6728 } else { 6729 ensureNoConnection(); 6730 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 6731 } 6732 } 6733 6734 public void ensureConnection() { 6735 final boolean registered = 6736 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6737 if (!registered) { 6738 mAttachInfo.mAccessibilityWindowId = 6739 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 6740 new AccessibilityInteractionConnection(ViewRootImpl.this)); 6741 } 6742 } 6743 6744 public void ensureNoConnection() { 6745 final boolean registered = 6746 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6747 if (registered) { 6748 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6749 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 6750 } 6751 } 6752 } 6753 6754 final class HighContrastTextManager implements HighTextContrastChangeListener { 6755 HighContrastTextManager() { 6756 mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled(); 6757 } 6758 @Override 6759 public void onHighTextContrastStateChanged(boolean enabled) { 6760 mAttachInfo.mHighContrastText = enabled; 6761 6762 // Destroy Displaylists so they can be recreated with high contrast recordings 6763 destroyHardwareResources(); 6764 6765 // Schedule redraw, which will rerecord + redraw all text 6766 invalidate(); 6767 } 6768 } 6769 6770 /** 6771 * This class is an interface this ViewAncestor provides to the 6772 * AccessibilityManagerService to the latter can interact with 6773 * the view hierarchy in this ViewAncestor. 6774 */ 6775 static final class AccessibilityInteractionConnection 6776 extends IAccessibilityInteractionConnection.Stub { 6777 private final WeakReference<ViewRootImpl> mViewRootImpl; 6778 6779 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 6780 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 6781 } 6782 6783 @Override 6784 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 6785 Region interactiveRegion, int interactionId, 6786 IAccessibilityInteractionConnectionCallback callback, int flags, 6787 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6788 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6789 if (viewRootImpl != null && viewRootImpl.mView != null) { 6790 viewRootImpl.getAccessibilityInteractionController() 6791 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 6792 interactiveRegion, interactionId, callback, flags, interrogatingPid, 6793 interrogatingTid, spec); 6794 } else { 6795 // We cannot make the call and notify the caller so it does not wait. 6796 try { 6797 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6798 } catch (RemoteException re) { 6799 /* best effort - ignore */ 6800 } 6801 } 6802 } 6803 6804 @Override 6805 public void performAccessibilityAction(long accessibilityNodeId, int action, 6806 Bundle arguments, int interactionId, 6807 IAccessibilityInteractionConnectionCallback callback, int flags, 6808 int interrogatingPid, long interrogatingTid) { 6809 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6810 if (viewRootImpl != null && viewRootImpl.mView != null) { 6811 viewRootImpl.getAccessibilityInteractionController() 6812 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 6813 interactionId, callback, flags, interrogatingPid, interrogatingTid); 6814 } else { 6815 // We cannot make the call and notify the caller so it does not wait. 6816 try { 6817 callback.setPerformAccessibilityActionResult(false, interactionId); 6818 } catch (RemoteException re) { 6819 /* best effort - ignore */ 6820 } 6821 } 6822 } 6823 6824 @Override 6825 public void computeClickPointInScreen(long accessibilityNodeId, Region interactiveRegion, 6826 int interactionId, IAccessibilityInteractionConnectionCallback callback, 6827 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6828 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6829 if (viewRootImpl != null && viewRootImpl.mView != null) { 6830 viewRootImpl.getAccessibilityInteractionController() 6831 .computeClickPointInScreenClientThread(accessibilityNodeId, 6832 interactiveRegion, interactionId, callback, interrogatingPid, 6833 interrogatingTid, spec); 6834 } else { 6835 // We cannot make the call and notify the caller so it does not wait. 6836 try { 6837 callback.setComputeClickPointInScreenActionResult(null, interactionId); 6838 } catch (RemoteException re) { 6839 /* best effort - ignore */ 6840 } 6841 } 6842 } 6843 6844 @Override 6845 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId, 6846 String viewId, Region interactiveRegion, int interactionId, 6847 IAccessibilityInteractionConnectionCallback callback, int flags, 6848 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6849 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6850 if (viewRootImpl != null && viewRootImpl.mView != null) { 6851 viewRootImpl.getAccessibilityInteractionController() 6852 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId, 6853 viewId, interactiveRegion, interactionId, callback, flags, 6854 interrogatingPid, interrogatingTid, spec); 6855 } else { 6856 // We cannot make the call and notify the caller so it does not wait. 6857 try { 6858 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6859 } catch (RemoteException re) { 6860 /* best effort - ignore */ 6861 } 6862 } 6863 } 6864 6865 @Override 6866 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 6867 Region interactiveRegion, int interactionId, 6868 IAccessibilityInteractionConnectionCallback callback, int flags, 6869 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6870 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6871 if (viewRootImpl != null && viewRootImpl.mView != null) { 6872 viewRootImpl.getAccessibilityInteractionController() 6873 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 6874 interactiveRegion, interactionId, callback, flags, interrogatingPid, 6875 interrogatingTid, spec); 6876 } else { 6877 // We cannot make the call and notify the caller so it does not wait. 6878 try { 6879 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6880 } catch (RemoteException re) { 6881 /* best effort - ignore */ 6882 } 6883 } 6884 } 6885 6886 @Override 6887 public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion, 6888 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6889 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6890 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6891 if (viewRootImpl != null && viewRootImpl.mView != null) { 6892 viewRootImpl.getAccessibilityInteractionController() 6893 .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion, 6894 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6895 spec); 6896 } else { 6897 // We cannot make the call and notify the caller so it does not wait. 6898 try { 6899 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6900 } catch (RemoteException re) { 6901 /* best effort - ignore */ 6902 } 6903 } 6904 } 6905 6906 @Override 6907 public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion, 6908 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6909 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6910 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6911 if (viewRootImpl != null && viewRootImpl.mView != null) { 6912 viewRootImpl.getAccessibilityInteractionController() 6913 .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion, 6914 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6915 spec); 6916 } else { 6917 // We cannot make the call and notify the caller so it does not wait. 6918 try { 6919 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6920 } catch (RemoteException re) { 6921 /* best effort - ignore */ 6922 } 6923 } 6924 } 6925 } 6926 6927 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 6928 private int mChangeTypes = 0; 6929 6930 public View mSource; 6931 public long mLastEventTimeMillis; 6932 6933 @Override 6934 public void run() { 6935 // The accessibility may be turned off while we were waiting so check again. 6936 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6937 mLastEventTimeMillis = SystemClock.uptimeMillis(); 6938 AccessibilityEvent event = AccessibilityEvent.obtain(); 6939 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 6940 event.setContentChangeTypes(mChangeTypes); 6941 mSource.sendAccessibilityEventUnchecked(event); 6942 } else { 6943 mLastEventTimeMillis = 0; 6944 } 6945 // In any case reset to initial state. 6946 mSource.resetSubtreeAccessibilityStateChanged(); 6947 mSource = null; 6948 mChangeTypes = 0; 6949 } 6950 6951 public void runOrPost(View source, int changeType) { 6952 if (mSource != null) { 6953 // If there is no common predecessor, then mSource points to 6954 // a removed view, hence in this case always prefer the source. 6955 View predecessor = getCommonPredecessor(mSource, source); 6956 mSource = (predecessor != null) ? predecessor : source; 6957 mChangeTypes |= changeType; 6958 return; 6959 } 6960 mSource = source; 6961 mChangeTypes = changeType; 6962 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 6963 final long minEventIntevalMillis = 6964 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 6965 if (timeSinceLastMillis >= minEventIntevalMillis) { 6966 mSource.removeCallbacks(this); 6967 run(); 6968 } else { 6969 mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 6970 } 6971 } 6972 } 6973} 6974