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