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