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