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