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