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