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