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