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