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