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