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