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