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