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