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