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