ViewRootImpl.java revision a42521ca0a537823311cec67f3c70cb546ae71db
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 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this); 2570 } else { 2571 // If we get here with a disabled & requested hardware renderer, something went 2572 // wrong (an invalidate posted right before we destroyed the hardware surface 2573 // for instance) so we should just bail out. Locking the surface with software 2574 // rendering at this point would lock it forever and prevent hardware renderer 2575 // from doing its job when it comes back. 2576 // Before we request a new frame we must however attempt to reinitiliaze the 2577 // hardware renderer if it's in requested state. This would happen after an 2578 // eglTerminate() for instance. 2579 if (mAttachInfo.mHardwareRenderer != null && 2580 !mAttachInfo.mHardwareRenderer.isEnabled() && 2581 mAttachInfo.mHardwareRenderer.isRequested()) { 2582 2583 try { 2584 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 2585 mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets); 2586 } catch (OutOfResourcesException e) { 2587 handleOutOfResourcesException(e); 2588 return; 2589 } 2590 2591 mFullRedrawNeeded = true; 2592 scheduleTraversals(); 2593 return; 2594 } 2595 2596 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) { 2597 return; 2598 } 2599 } 2600 } 2601 2602 if (animating) { 2603 mFullRedrawNeeded = true; 2604 scheduleTraversals(); 2605 } 2606 } 2607 2608 /** 2609 * @return true if drawing was successful, false if an error occurred 2610 */ 2611 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff, 2612 boolean scalingRequired, Rect dirty) { 2613 2614 // Draw with software renderer. 2615 final Canvas canvas; 2616 try { 2617 final int left = dirty.left; 2618 final int top = dirty.top; 2619 final int right = dirty.right; 2620 final int bottom = dirty.bottom; 2621 2622 canvas = mSurface.lockCanvas(dirty); 2623 2624 // The dirty rectangle can be modified by Surface.lockCanvas() 2625 //noinspection ConstantConditions 2626 if (left != dirty.left || top != dirty.top || right != dirty.right 2627 || bottom != dirty.bottom) { 2628 attachInfo.mIgnoreDirtyState = true; 2629 } 2630 2631 // TODO: Do this in native 2632 canvas.setDensity(mDensity); 2633 } catch (Surface.OutOfResourcesException e) { 2634 handleOutOfResourcesException(e); 2635 return false; 2636 } catch (IllegalArgumentException e) { 2637 Log.e(TAG, "Could not lock surface", e); 2638 // Don't assume this is due to out of memory, it could be 2639 // something else, and if it is something else then we could 2640 // kill stuff (or ourself) for no reason. 2641 mLayoutRequested = true; // ask wm for a new surface next time. 2642 return false; 2643 } 2644 2645 try { 2646 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2647 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2648 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2649 //canvas.drawARGB(255, 255, 0, 0); 2650 } 2651 2652 // If this bitmap's format includes an alpha channel, we 2653 // need to clear it before drawing so that the child will 2654 // properly re-composite its drawing on a transparent 2655 // background. This automatically respects the clip/dirty region 2656 // or 2657 // If we are applying an offset, we need to clear the area 2658 // where the offset doesn't appear to avoid having garbage 2659 // left in the blank areas. 2660 if (!canvas.isOpaque() || yoff != 0 || xoff != 0) { 2661 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2662 } 2663 2664 dirty.setEmpty(); 2665 mIsAnimating = false; 2666 mView.mPrivateFlags |= View.PFLAG_DRAWN; 2667 2668 if (DEBUG_DRAW) { 2669 Context cxt = mView.getContext(); 2670 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2671 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2672 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2673 } 2674 try { 2675 canvas.translate(-xoff, -yoff); 2676 if (mTranslator != null) { 2677 mTranslator.translateCanvas(canvas); 2678 } 2679 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0); 2680 attachInfo.mSetIgnoreDirtyState = false; 2681 2682 mView.draw(canvas); 2683 2684 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2685 } finally { 2686 if (!attachInfo.mSetIgnoreDirtyState) { 2687 // Only clear the flag if it was not set during the mView.draw() call 2688 attachInfo.mIgnoreDirtyState = false; 2689 } 2690 } 2691 } finally { 2692 try { 2693 surface.unlockCanvasAndPost(canvas); 2694 } catch (IllegalArgumentException e) { 2695 Log.e(TAG, "Could not unlock surface", e); 2696 mLayoutRequested = true; // ask wm for a new surface next time. 2697 //noinspection ReturnInsideFinallyBlock 2698 return false; 2699 } 2700 2701 if (LOCAL_LOGV) { 2702 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2703 } 2704 } 2705 return true; 2706 } 2707 2708 /** 2709 * We want to draw a highlight around the current accessibility focused. 2710 * Since adding a style for all possible view is not a viable option we 2711 * have this specialized drawing method. 2712 * 2713 * Note: We are doing this here to be able to draw the highlight for 2714 * virtual views in addition to real ones. 2715 * 2716 * @param canvas The canvas on which to draw. 2717 */ 2718 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) { 2719 final Rect bounds = mAttachInfo.mTmpInvalRect; 2720 if (getAccessibilityFocusedRect(bounds)) { 2721 final Drawable drawable = getAccessibilityFocusedDrawable(); 2722 if (drawable != null) { 2723 drawable.setBounds(bounds); 2724 drawable.draw(canvas); 2725 } 2726 } else if (mAttachInfo.mAccessibilityFocusDrawable != null) { 2727 mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0); 2728 } 2729 } 2730 2731 private boolean getAccessibilityFocusedRect(Rect bounds) { 2732 final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext); 2733 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 2734 return false; 2735 } 2736 2737 final View host = mAccessibilityFocusedHost; 2738 if (host == null || host.mAttachInfo == null) { 2739 return false; 2740 } 2741 2742 final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider(); 2743 if (provider == null) { 2744 host.getBoundsOnScreen(bounds, true); 2745 } else if (mAccessibilityFocusedVirtualView != null) { 2746 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds); 2747 } else { 2748 return false; 2749 } 2750 2751 // Transform the rect into window-relative coordinates. 2752 final AttachInfo attachInfo = mAttachInfo; 2753 bounds.offset(0, attachInfo.mViewRootImpl.mScrollY); 2754 bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop); 2755 if (!bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth, 2756 attachInfo.mViewRootImpl.mHeight)) { 2757 // If no intersection, set bounds to empty. 2758 bounds.setEmpty(); 2759 } 2760 return !bounds.isEmpty(); 2761 } 2762 2763 private Drawable getAccessibilityFocusedDrawable() { 2764 // Lazily load the accessibility focus drawable. 2765 if (mAttachInfo.mAccessibilityFocusDrawable == null) { 2766 final TypedValue value = new TypedValue(); 2767 final boolean resolved = mView.mContext.getTheme().resolveAttribute( 2768 R.attr.accessibilityFocusedDrawable, value, true); 2769 if (resolved) { 2770 mAttachInfo.mAccessibilityFocusDrawable = 2771 mView.mContext.getDrawable(value.resourceId); 2772 } 2773 } 2774 return mAttachInfo.mAccessibilityFocusDrawable; 2775 } 2776 2777 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2778 final Rect ci = mAttachInfo.mContentInsets; 2779 final Rect vi = mAttachInfo.mVisibleInsets; 2780 int scrollY = 0; 2781 boolean handled = false; 2782 2783 if (vi.left > ci.left || vi.top > ci.top 2784 || vi.right > ci.right || vi.bottom > ci.bottom) { 2785 // We'll assume that we aren't going to change the scroll 2786 // offset, since we want to avoid that unless it is actually 2787 // going to make the focus visible... otherwise we scroll 2788 // all over the place. 2789 scrollY = mScrollY; 2790 // We can be called for two different situations: during a draw, 2791 // to update the scroll position if the focus has changed (in which 2792 // case 'rectangle' is null), or in response to a 2793 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2794 // is non-null and we just want to scroll to whatever that 2795 // rectangle is). 2796 final View focus = mView.findFocus(); 2797 if (focus == null) { 2798 return false; 2799 } 2800 View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null; 2801 if (focus != lastScrolledFocus) { 2802 // If the focus has changed, then ignore any requests to scroll 2803 // to a rectangle; first we want to make sure the entire focus 2804 // view is visible. 2805 rectangle = null; 2806 } 2807 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2808 + " rectangle=" + rectangle + " ci=" + ci 2809 + " vi=" + vi); 2810 if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) { 2811 // Optimization: if the focus hasn't changed since last 2812 // time, and no layout has happened, then just leave things 2813 // as they are. 2814 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2815 + mScrollY + " vi=" + vi.toShortString()); 2816 } else { 2817 // We need to determine if the currently focused view is 2818 // within the visible part of the window and, if not, apply 2819 // a pan so it can be seen. 2820 mLastScrolledFocus = new WeakReference<View>(focus); 2821 mScrollMayChange = false; 2822 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2823 // Try to find the rectangle from the focus view. 2824 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2825 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2826 + mView.getWidth() + " h=" + mView.getHeight() 2827 + " ci=" + ci.toShortString() 2828 + " vi=" + vi.toShortString()); 2829 if (rectangle == null) { 2830 focus.getFocusedRect(mTempRect); 2831 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2832 + ": focusRect=" + mTempRect.toShortString()); 2833 if (mView instanceof ViewGroup) { 2834 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2835 focus, mTempRect); 2836 } 2837 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2838 "Focus in window: focusRect=" 2839 + mTempRect.toShortString() 2840 + " visRect=" + mVisRect.toShortString()); 2841 } else { 2842 mTempRect.set(rectangle); 2843 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2844 "Request scroll to rect: " 2845 + mTempRect.toShortString() 2846 + " visRect=" + mVisRect.toShortString()); 2847 } 2848 if (mTempRect.intersect(mVisRect)) { 2849 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2850 "Focus window visible rect: " 2851 + mTempRect.toShortString()); 2852 if (mTempRect.height() > 2853 (mView.getHeight()-vi.top-vi.bottom)) { 2854 // If the focus simply is not going to fit, then 2855 // best is probably just to leave things as-is. 2856 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2857 "Too tall; leaving scrollY=" + scrollY); 2858 } else if ((mTempRect.top-scrollY) < vi.top) { 2859 scrollY -= vi.top - (mTempRect.top-scrollY); 2860 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2861 "Top covered; scrollY=" + scrollY); 2862 } else if ((mTempRect.bottom-scrollY) 2863 > (mView.getHeight()-vi.bottom)) { 2864 scrollY += (mTempRect.bottom-scrollY) 2865 - (mView.getHeight()-vi.bottom); 2866 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2867 "Bottom covered; scrollY=" + scrollY); 2868 } 2869 handled = true; 2870 } 2871 } 2872 } 2873 } 2874 2875 if (scrollY != mScrollY) { 2876 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2877 + mScrollY + " , new=" + scrollY); 2878 if (!immediate) { 2879 if (mScroller == null) { 2880 mScroller = new Scroller(mView.getContext()); 2881 } 2882 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2883 } else if (mScroller != null) { 2884 mScroller.abortAnimation(); 2885 } 2886 mScrollY = scrollY; 2887 } 2888 2889 return handled; 2890 } 2891 2892 /** 2893 * @hide 2894 */ 2895 public View getAccessibilityFocusedHost() { 2896 return mAccessibilityFocusedHost; 2897 } 2898 2899 /** 2900 * @hide 2901 */ 2902 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() { 2903 return mAccessibilityFocusedVirtualView; 2904 } 2905 2906 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) { 2907 // If we have a virtual view with accessibility focus we need 2908 // to clear the focus and invalidate the virtual view bounds. 2909 if (mAccessibilityFocusedVirtualView != null) { 2910 2911 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView; 2912 View focusHost = mAccessibilityFocusedHost; 2913 2914 // Wipe the state of the current accessibility focus since 2915 // the call into the provider to clear accessibility focus 2916 // will fire an accessibility event which will end up calling 2917 // this method and we want to have clean state when this 2918 // invocation happens. 2919 mAccessibilityFocusedHost = null; 2920 mAccessibilityFocusedVirtualView = null; 2921 2922 // Clear accessibility focus on the host after clearing state since 2923 // this method may be reentrant. 2924 focusHost.clearAccessibilityFocusNoCallbacks(); 2925 2926 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider(); 2927 if (provider != null) { 2928 // Invalidate the area of the cleared accessibility focus. 2929 focusNode.getBoundsInParent(mTempRect); 2930 focusHost.invalidate(mTempRect); 2931 // Clear accessibility focus in the virtual node. 2932 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 2933 focusNode.getSourceNodeId()); 2934 provider.performAction(virtualNodeId, 2935 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); 2936 } 2937 focusNode.recycle(); 2938 } 2939 if (mAccessibilityFocusedHost != null) { 2940 // Clear accessibility focus in the view. 2941 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(); 2942 } 2943 2944 // Set the new focus host and node. 2945 mAccessibilityFocusedHost = view; 2946 mAccessibilityFocusedVirtualView = node; 2947 2948 if (mAttachInfo.mHardwareRenderer != null) { 2949 mAttachInfo.mHardwareRenderer.invalidateRoot(); 2950 } 2951 } 2952 2953 @Override 2954 public void requestChildFocus(View child, View focused) { 2955 if (DEBUG_INPUT_RESIZE) { 2956 Log.v(TAG, "Request child focus: focus now " + focused); 2957 } 2958 checkThread(); 2959 scheduleTraversals(); 2960 } 2961 2962 @Override 2963 public void clearChildFocus(View child) { 2964 if (DEBUG_INPUT_RESIZE) { 2965 Log.v(TAG, "Clearing child focus"); 2966 } 2967 checkThread(); 2968 scheduleTraversals(); 2969 } 2970 2971 @Override 2972 public ViewParent getParentForAccessibility() { 2973 return null; 2974 } 2975 2976 @Override 2977 public void focusableViewAvailable(View v) { 2978 checkThread(); 2979 if (mView != null) { 2980 if (!mView.hasFocus()) { 2981 v.requestFocus(); 2982 } else { 2983 // the one case where will transfer focus away from the current one 2984 // is if the current view is a view group that prefers to give focus 2985 // to its children first AND the view is a descendant of it. 2986 View focused = mView.findFocus(); 2987 if (focused instanceof ViewGroup) { 2988 ViewGroup group = (ViewGroup) focused; 2989 if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 2990 && isViewDescendantOf(v, focused)) { 2991 v.requestFocus(); 2992 } 2993 } 2994 } 2995 } 2996 } 2997 2998 @Override 2999 public void recomputeViewAttributes(View child) { 3000 checkThread(); 3001 if (mView == child) { 3002 mAttachInfo.mRecomputeGlobalAttributes = true; 3003 if (!mWillDrawSoon) { 3004 scheduleTraversals(); 3005 } 3006 } 3007 } 3008 3009 void dispatchDetachedFromWindow() { 3010 if (mView != null && mView.mAttachInfo != null) { 3011 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false); 3012 mView.dispatchDetachedFromWindow(); 3013 } 3014 3015 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 3016 mAccessibilityManager.removeAccessibilityStateChangeListener( 3017 mAccessibilityInteractionConnectionManager); 3018 mAccessibilityManager.removeHighTextContrastStateChangeListener( 3019 mHighContrastTextManager); 3020 removeSendWindowContentChangedCallback(); 3021 3022 destroyHardwareRenderer(); 3023 3024 setAccessibilityFocus(null, null); 3025 3026 mView.assignParent(null); 3027 mView = null; 3028 mAttachInfo.mRootView = null; 3029 3030 mSurface.release(); 3031 3032 if (mInputQueueCallback != null && mInputQueue != null) { 3033 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 3034 mInputQueue.dispose(); 3035 mInputQueueCallback = null; 3036 mInputQueue = null; 3037 } 3038 if (mInputEventReceiver != null) { 3039 mInputEventReceiver.dispose(); 3040 mInputEventReceiver = null; 3041 } 3042 try { 3043 mWindowSession.remove(mWindow); 3044 } catch (RemoteException e) { 3045 } 3046 3047 // Dispose the input channel after removing the window so the Window Manager 3048 // doesn't interpret the input channel being closed as an abnormal termination. 3049 if (mInputChannel != null) { 3050 mInputChannel.dispose(); 3051 mInputChannel = null; 3052 } 3053 3054 mDisplayManager.unregisterDisplayListener(mDisplayListener); 3055 3056 unscheduleTraversals(); 3057 } 3058 3059 void updateConfiguration(Configuration config, boolean force) { 3060 if (DEBUG_CONFIGURATION) Log.v(TAG, 3061 "Applying new config to window " 3062 + mWindowAttributes.getTitle() 3063 + ": " + config); 3064 3065 CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo(); 3066 if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) { 3067 config = new Configuration(config); 3068 ci.applyToConfiguration(mNoncompatDensity, config); 3069 } 3070 3071 synchronized (sConfigCallbacks) { 3072 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 3073 sConfigCallbacks.get(i).onConfigurationChanged(config); 3074 } 3075 } 3076 if (mView != null) { 3077 // At this point the resources have been updated to 3078 // have the most recent config, whatever that is. Use 3079 // the one in them which may be newer. 3080 config = mView.getResources().getConfiguration(); 3081 if (force || mLastConfiguration.diff(config) != 0) { 3082 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection(); 3083 final int currentLayoutDirection = config.getLayoutDirection(); 3084 mLastConfiguration.setTo(config); 3085 if (lastLayoutDirection != currentLayoutDirection && 3086 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 3087 mView.setLayoutDirection(currentLayoutDirection); 3088 } 3089 mView.dispatchConfigurationChanged(config); 3090 } 3091 } 3092 } 3093 3094 /** 3095 * Return true if child is an ancestor of parent, (or equal to the parent). 3096 */ 3097 public static boolean isViewDescendantOf(View child, View parent) { 3098 if (child == parent) { 3099 return true; 3100 } 3101 3102 final ViewParent theParent = child.getParent(); 3103 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 3104 } 3105 3106 private static void forceLayout(View view) { 3107 view.forceLayout(); 3108 if (view instanceof ViewGroup) { 3109 ViewGroup group = (ViewGroup) view; 3110 final int count = group.getChildCount(); 3111 for (int i = 0; i < count; i++) { 3112 forceLayout(group.getChildAt(i)); 3113 } 3114 } 3115 } 3116 3117 private final static int MSG_INVALIDATE = 1; 3118 private final static int MSG_INVALIDATE_RECT = 2; 3119 private final static int MSG_DIE = 3; 3120 private final static int MSG_RESIZED = 4; 3121 private final static int MSG_RESIZED_REPORT = 5; 3122 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 3123 private final static int MSG_DISPATCH_INPUT_EVENT = 7; 3124 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 3125 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 3126 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 3127 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 3128 private final static int MSG_CHECK_FOCUS = 13; 3129 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 3130 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 3131 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 3132 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 3133 private final static int MSG_UPDATE_CONFIGURATION = 18; 3134 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 3135 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21; 3136 private final static int MSG_INVALIDATE_WORLD = 22; 3137 private final static int MSG_WINDOW_MOVED = 23; 3138 private final static int MSG_SYNTHESIZE_INPUT_EVENT = 24; 3139 private final static int MSG_DISPATCH_WINDOW_SHOWN = 25; 3140 3141 final class ViewRootHandler extends Handler { 3142 @Override 3143 public String getMessageName(Message message) { 3144 switch (message.what) { 3145 case MSG_INVALIDATE: 3146 return "MSG_INVALIDATE"; 3147 case MSG_INVALIDATE_RECT: 3148 return "MSG_INVALIDATE_RECT"; 3149 case MSG_DIE: 3150 return "MSG_DIE"; 3151 case MSG_RESIZED: 3152 return "MSG_RESIZED"; 3153 case MSG_RESIZED_REPORT: 3154 return "MSG_RESIZED_REPORT"; 3155 case MSG_WINDOW_FOCUS_CHANGED: 3156 return "MSG_WINDOW_FOCUS_CHANGED"; 3157 case MSG_DISPATCH_INPUT_EVENT: 3158 return "MSG_DISPATCH_INPUT_EVENT"; 3159 case MSG_DISPATCH_APP_VISIBILITY: 3160 return "MSG_DISPATCH_APP_VISIBILITY"; 3161 case MSG_DISPATCH_GET_NEW_SURFACE: 3162 return "MSG_DISPATCH_GET_NEW_SURFACE"; 3163 case MSG_DISPATCH_KEY_FROM_IME: 3164 return "MSG_DISPATCH_KEY_FROM_IME"; 3165 case MSG_FINISH_INPUT_CONNECTION: 3166 return "MSG_FINISH_INPUT_CONNECTION"; 3167 case MSG_CHECK_FOCUS: 3168 return "MSG_CHECK_FOCUS"; 3169 case MSG_CLOSE_SYSTEM_DIALOGS: 3170 return "MSG_CLOSE_SYSTEM_DIALOGS"; 3171 case MSG_DISPATCH_DRAG_EVENT: 3172 return "MSG_DISPATCH_DRAG_EVENT"; 3173 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 3174 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 3175 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 3176 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 3177 case MSG_UPDATE_CONFIGURATION: 3178 return "MSG_UPDATE_CONFIGURATION"; 3179 case MSG_PROCESS_INPUT_EVENTS: 3180 return "MSG_PROCESS_INPUT_EVENTS"; 3181 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 3182 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 3183 case MSG_WINDOW_MOVED: 3184 return "MSG_WINDOW_MOVED"; 3185 case MSG_SYNTHESIZE_INPUT_EVENT: 3186 return "MSG_SYNTHESIZE_INPUT_EVENT"; 3187 case MSG_DISPATCH_WINDOW_SHOWN: 3188 return "MSG_DISPATCH_WINDOW_SHOWN"; 3189 } 3190 return super.getMessageName(message); 3191 } 3192 3193 @Override 3194 public void handleMessage(Message msg) { 3195 switch (msg.what) { 3196 case MSG_INVALIDATE: 3197 ((View) msg.obj).invalidate(); 3198 break; 3199 case MSG_INVALIDATE_RECT: 3200 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 3201 info.target.invalidate(info.left, info.top, info.right, info.bottom); 3202 info.recycle(); 3203 break; 3204 case MSG_PROCESS_INPUT_EVENTS: 3205 mProcessInputEventsScheduled = false; 3206 doProcessInputEvents(); 3207 break; 3208 case MSG_DISPATCH_APP_VISIBILITY: 3209 handleAppVisibility(msg.arg1 != 0); 3210 break; 3211 case MSG_DISPATCH_GET_NEW_SURFACE: 3212 handleGetNewSurface(); 3213 break; 3214 case MSG_RESIZED: { 3215 // Recycled in the fall through... 3216 SomeArgs args = (SomeArgs) msg.obj; 3217 if (mWinFrame.equals(args.arg1) 3218 && mPendingOverscanInsets.equals(args.arg5) 3219 && mPendingContentInsets.equals(args.arg2) 3220 && mPendingStableInsets.equals(args.arg6) 3221 && mPendingVisibleInsets.equals(args.arg3) 3222 && mPendingOutsets.equals(args.arg7) 3223 && args.arg4 == null) { 3224 break; 3225 } 3226 } // fall through... 3227 case MSG_RESIZED_REPORT: 3228 if (mAdded) { 3229 SomeArgs args = (SomeArgs) msg.obj; 3230 3231 Configuration config = (Configuration) args.arg4; 3232 if (config != null) { 3233 updateConfiguration(config, false); 3234 } 3235 3236 mWinFrame.set((Rect) args.arg1); 3237 mPendingOverscanInsets.set((Rect) args.arg5); 3238 mPendingContentInsets.set((Rect) args.arg2); 3239 mPendingStableInsets.set((Rect) args.arg6); 3240 mPendingVisibleInsets.set((Rect) args.arg3); 3241 mPendingOutsets.set((Rect) args.arg7); 3242 3243 args.recycle(); 3244 3245 if (msg.what == MSG_RESIZED_REPORT) { 3246 mReportNextDraw = true; 3247 } 3248 3249 if (mView != null) { 3250 forceLayout(mView); 3251 } 3252 3253 requestLayout(); 3254 } 3255 break; 3256 case MSG_WINDOW_MOVED: 3257 if (mAdded) { 3258 final int w = mWinFrame.width(); 3259 final int h = mWinFrame.height(); 3260 final int l = msg.arg1; 3261 final int t = msg.arg2; 3262 mWinFrame.left = l; 3263 mWinFrame.right = l + w; 3264 mWinFrame.top = t; 3265 mWinFrame.bottom = t + h; 3266 3267 if (mView != null) { 3268 forceLayout(mView); 3269 } 3270 requestLayout(); 3271 } 3272 break; 3273 case MSG_WINDOW_FOCUS_CHANGED: { 3274 if (mAdded) { 3275 boolean hasWindowFocus = msg.arg1 != 0; 3276 mAttachInfo.mHasWindowFocus = hasWindowFocus; 3277 3278 profileRendering(hasWindowFocus); 3279 3280 if (hasWindowFocus) { 3281 boolean inTouchMode = msg.arg2 != 0; 3282 ensureTouchModeLocally(inTouchMode); 3283 3284 if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){ 3285 mFullRedrawNeeded = true; 3286 try { 3287 final WindowManager.LayoutParams lp = mWindowAttributes; 3288 final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null; 3289 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 3290 mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets); 3291 } catch (OutOfResourcesException e) { 3292 Log.e(TAG, "OutOfResourcesException locking surface", e); 3293 try { 3294 if (!mWindowSession.outOfMemory(mWindow)) { 3295 Slog.w(TAG, "No processes killed for memory; killing self"); 3296 Process.killProcess(Process.myPid()); 3297 } 3298 } catch (RemoteException ex) { 3299 } 3300 // Retry in a bit. 3301 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 3302 return; 3303 } 3304 } 3305 } 3306 3307 mLastWasImTarget = WindowManager.LayoutParams 3308 .mayUseInputMethod(mWindowAttributes.flags); 3309 3310 InputMethodManager imm = InputMethodManager.peekInstance(); 3311 if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { 3312 imm.onPreWindowFocus(mView, hasWindowFocus); 3313 } 3314 if (mView != null) { 3315 mAttachInfo.mKeyDispatchState.reset(); 3316 mView.dispatchWindowFocusChanged(hasWindowFocus); 3317 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus); 3318 } 3319 3320 // Note: must be done after the focus change callbacks, 3321 // so all of the view state is set up correctly. 3322 if (hasWindowFocus) { 3323 if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { 3324 imm.onPostWindowFocus(mView, mView.findFocus(), 3325 mWindowAttributes.softInputMode, 3326 !mHasHadWindowFocus, mWindowAttributes.flags); 3327 } 3328 // Clear the forward bit. We can just do this directly, since 3329 // the window manager doesn't care about it. 3330 mWindowAttributes.softInputMode &= 3331 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3332 ((WindowManager.LayoutParams)mView.getLayoutParams()) 3333 .softInputMode &= 3334 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3335 mHasHadWindowFocus = true; 3336 } 3337 } 3338 } break; 3339 case MSG_DIE: 3340 doDie(); 3341 break; 3342 case MSG_DISPATCH_INPUT_EVENT: { 3343 SomeArgs args = (SomeArgs)msg.obj; 3344 InputEvent event = (InputEvent)args.arg1; 3345 InputEventReceiver receiver = (InputEventReceiver)args.arg2; 3346 enqueueInputEvent(event, receiver, 0, true); 3347 args.recycle(); 3348 } break; 3349 case MSG_SYNTHESIZE_INPUT_EVENT: { 3350 InputEvent event = (InputEvent)msg.obj; 3351 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true); 3352 } break; 3353 case MSG_DISPATCH_KEY_FROM_IME: { 3354 if (LOCAL_LOGV) Log.v( 3355 TAG, "Dispatching key " 3356 + msg.obj + " from IME to " + mView); 3357 KeyEvent event = (KeyEvent)msg.obj; 3358 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 3359 // The IME is trying to say this event is from the 3360 // system! Bad bad bad! 3361 //noinspection UnusedAssignment 3362 event = KeyEvent.changeFlags(event, event.getFlags() & 3363 ~KeyEvent.FLAG_FROM_SYSTEM); 3364 } 3365 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 3366 } break; 3367 case MSG_FINISH_INPUT_CONNECTION: { 3368 InputMethodManager imm = InputMethodManager.peekInstance(); 3369 if (imm != null) { 3370 imm.reportFinishInputConnection((InputConnection)msg.obj); 3371 } 3372 } break; 3373 case MSG_CHECK_FOCUS: { 3374 InputMethodManager imm = InputMethodManager.peekInstance(); 3375 if (imm != null) { 3376 imm.checkFocus(); 3377 } 3378 } break; 3379 case MSG_CLOSE_SYSTEM_DIALOGS: { 3380 if (mView != null) { 3381 mView.onCloseSystemDialogs((String)msg.obj); 3382 } 3383 } break; 3384 case MSG_DISPATCH_DRAG_EVENT: 3385 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 3386 DragEvent event = (DragEvent)msg.obj; 3387 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 3388 handleDragEvent(event); 3389 } break; 3390 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 3391 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); 3392 } break; 3393 case MSG_UPDATE_CONFIGURATION: { 3394 Configuration config = (Configuration)msg.obj; 3395 if (config.isOtherSeqNewer(mLastConfiguration)) { 3396 config = mLastConfiguration; 3397 } 3398 updateConfiguration(config, false); 3399 } break; 3400 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3401 setAccessibilityFocus(null, null); 3402 } break; 3403 case MSG_INVALIDATE_WORLD: { 3404 if (mView != null) { 3405 invalidateWorld(mView); 3406 } 3407 } break; 3408 case MSG_DISPATCH_WINDOW_SHOWN: { 3409 handleDispatchWindowShown(); 3410 } 3411 } 3412 } 3413 } 3414 3415 final ViewRootHandler mHandler = new ViewRootHandler(); 3416 3417 /** 3418 * Something in the current window tells us we need to change the touch mode. For 3419 * example, we are not in touch mode, and the user touches the screen. 3420 * 3421 * If the touch mode has changed, tell the window manager, and handle it locally. 3422 * 3423 * @param inTouchMode Whether we want to be in touch mode. 3424 * @return True if the touch mode changed and focus changed was changed as a result 3425 */ 3426 boolean ensureTouchMode(boolean inTouchMode) { 3427 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3428 + "touch mode is " + mAttachInfo.mInTouchMode); 3429 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3430 3431 // tell the window manager 3432 try { 3433 if (!isInLocalFocusMode()) { 3434 mWindowSession.setInTouchMode(inTouchMode); 3435 } 3436 } catch (RemoteException e) { 3437 throw new RuntimeException(e); 3438 } 3439 3440 // handle the change 3441 return ensureTouchModeLocally(inTouchMode); 3442 } 3443 3444 /** 3445 * Ensure that the touch mode for this window is set, and if it is changing, 3446 * take the appropriate action. 3447 * @param inTouchMode Whether we want to be in touch mode. 3448 * @return True if the touch mode changed and focus changed was changed as a result 3449 */ 3450 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3451 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3452 + "touch mode is " + mAttachInfo.mInTouchMode); 3453 3454 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3455 3456 mAttachInfo.mInTouchMode = inTouchMode; 3457 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3458 3459 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3460 } 3461 3462 private boolean enterTouchMode() { 3463 if (mView != null && mView.hasFocus()) { 3464 // note: not relying on mFocusedView here because this could 3465 // be when the window is first being added, and mFocused isn't 3466 // set yet. 3467 final View focused = mView.findFocus(); 3468 if (focused != null && !focused.isFocusableInTouchMode()) { 3469 final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused); 3470 if (ancestorToTakeFocus != null) { 3471 // there is an ancestor that wants focus after its 3472 // descendants that is focusable in touch mode.. give it 3473 // focus 3474 return ancestorToTakeFocus.requestFocus(); 3475 } else { 3476 // There's nothing to focus. Clear and propagate through the 3477 // hierarchy, but don't attempt to place new focus. 3478 focused.clearFocusInternal(null, true, false); 3479 return true; 3480 } 3481 } 3482 } 3483 return false; 3484 } 3485 3486 /** 3487 * Find an ancestor of focused that wants focus after its descendants and is 3488 * focusable in touch mode. 3489 * @param focused The currently focused view. 3490 * @return An appropriate view, or null if no such view exists. 3491 */ 3492 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3493 ViewParent parent = focused.getParent(); 3494 while (parent instanceof ViewGroup) { 3495 final ViewGroup vgParent = (ViewGroup) parent; 3496 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3497 && vgParent.isFocusableInTouchMode()) { 3498 return vgParent; 3499 } 3500 if (vgParent.isRootNamespace()) { 3501 return null; 3502 } else { 3503 parent = vgParent.getParent(); 3504 } 3505 } 3506 return null; 3507 } 3508 3509 private boolean leaveTouchMode() { 3510 if (mView != null) { 3511 if (mView.hasFocus()) { 3512 View focusedView = mView.findFocus(); 3513 if (!(focusedView instanceof ViewGroup)) { 3514 // some view has focus, let it keep it 3515 return false; 3516 } else if (((ViewGroup) focusedView).getDescendantFocusability() != 3517 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3518 // some view group has focus, and doesn't prefer its children 3519 // over itself for focus, so let them keep it. 3520 return false; 3521 } 3522 } 3523 3524 // find the best view to give focus to in this brave new non-touch-mode 3525 // world 3526 final View focused = focusSearch(null, View.FOCUS_DOWN); 3527 if (focused != null) { 3528 return focused.requestFocus(View.FOCUS_DOWN); 3529 } 3530 } 3531 return false; 3532 } 3533 3534 /** 3535 * Base class for implementing a stage in the chain of responsibility 3536 * for processing input events. 3537 * <p> 3538 * Events are delivered to the stage by the {@link #deliver} method. The stage 3539 * then has the choice of finishing the event or forwarding it to the next stage. 3540 * </p> 3541 */ 3542 abstract class InputStage { 3543 private final InputStage mNext; 3544 3545 protected static final int FORWARD = 0; 3546 protected static final int FINISH_HANDLED = 1; 3547 protected static final int FINISH_NOT_HANDLED = 2; 3548 3549 /** 3550 * Creates an input stage. 3551 * @param next The next stage to which events should be forwarded. 3552 */ 3553 public InputStage(InputStage next) { 3554 mNext = next; 3555 } 3556 3557 /** 3558 * Delivers an event to be processed. 3559 */ 3560 public final void deliver(QueuedInputEvent q) { 3561 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) { 3562 forward(q); 3563 } else if (shouldDropInputEvent(q)) { 3564 finish(q, false); 3565 } else { 3566 apply(q, onProcess(q)); 3567 } 3568 } 3569 3570 /** 3571 * Marks the the input event as finished then forwards it to the next stage. 3572 */ 3573 protected void finish(QueuedInputEvent q, boolean handled) { 3574 q.mFlags |= QueuedInputEvent.FLAG_FINISHED; 3575 if (handled) { 3576 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED; 3577 } 3578 forward(q); 3579 } 3580 3581 /** 3582 * Forwards the event to the next stage. 3583 */ 3584 protected void forward(QueuedInputEvent q) { 3585 onDeliverToNext(q); 3586 } 3587 3588 /** 3589 * Applies a result code from {@link #onProcess} to the specified event. 3590 */ 3591 protected void apply(QueuedInputEvent q, int result) { 3592 if (result == FORWARD) { 3593 forward(q); 3594 } else if (result == FINISH_HANDLED) { 3595 finish(q, true); 3596 } else if (result == FINISH_NOT_HANDLED) { 3597 finish(q, false); 3598 } else { 3599 throw new IllegalArgumentException("Invalid result: " + result); 3600 } 3601 } 3602 3603 /** 3604 * Called when an event is ready to be processed. 3605 * @return A result code indicating how the event was handled. 3606 */ 3607 protected int onProcess(QueuedInputEvent q) { 3608 return FORWARD; 3609 } 3610 3611 /** 3612 * Called when an event is being delivered to the next stage. 3613 */ 3614 protected void onDeliverToNext(QueuedInputEvent q) { 3615 if (DEBUG_INPUT_STAGES) { 3616 Log.v(TAG, "Done with " + getClass().getSimpleName() + ". " + q); 3617 } 3618 if (mNext != null) { 3619 mNext.deliver(q); 3620 } else { 3621 finishInputEvent(q); 3622 } 3623 } 3624 3625 protected boolean shouldDropInputEvent(QueuedInputEvent q) { 3626 if (mView == null || !mAdded) { 3627 Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent); 3628 return true; 3629 } else if ((!mAttachInfo.mHasWindowFocus 3630 && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) || mStopped 3631 || (mPausedForTransition && !isBack(q.mEvent))) { 3632 // This is a focus event and the window doesn't currently have input focus or 3633 // has stopped. This could be an event that came back from the previous stage 3634 // but the window has lost focus or stopped in the meantime. 3635 if (isTerminalInputEvent(q.mEvent)) { 3636 // Don't drop terminal input events, however mark them as canceled. 3637 q.mEvent.cancel(); 3638 Slog.w(TAG, "Cancelling event due to no window focus: " + q.mEvent); 3639 return false; 3640 } 3641 3642 // Drop non-terminal input events. 3643 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent); 3644 return true; 3645 } 3646 return false; 3647 } 3648 3649 void dump(String prefix, PrintWriter writer) { 3650 if (mNext != null) { 3651 mNext.dump(prefix, writer); 3652 } 3653 } 3654 3655 private boolean isBack(InputEvent event) { 3656 if (event instanceof KeyEvent) { 3657 return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK; 3658 } else { 3659 return false; 3660 } 3661 } 3662 } 3663 3664 /** 3665 * Base class for implementing an input pipeline stage that supports 3666 * asynchronous and out-of-order processing of input events. 3667 * <p> 3668 * In addition to what a normal input stage can do, an asynchronous 3669 * input stage may also defer an input event that has been delivered to it 3670 * and finish or forward it later. 3671 * </p> 3672 */ 3673 abstract class AsyncInputStage extends InputStage { 3674 private final String mTraceCounter; 3675 3676 private QueuedInputEvent mQueueHead; 3677 private QueuedInputEvent mQueueTail; 3678 private int mQueueLength; 3679 3680 protected static final int DEFER = 3; 3681 3682 /** 3683 * Creates an asynchronous input stage. 3684 * @param next The next stage to which events should be forwarded. 3685 * @param traceCounter The name of a counter to record the size of 3686 * the queue of pending events. 3687 */ 3688 public AsyncInputStage(InputStage next, String traceCounter) { 3689 super(next); 3690 mTraceCounter = traceCounter; 3691 } 3692 3693 /** 3694 * Marks the event as deferred, which is to say that it will be handled 3695 * asynchronously. The caller is responsible for calling {@link #forward} 3696 * or {@link #finish} later when it is done handling the event. 3697 */ 3698 protected void defer(QueuedInputEvent q) { 3699 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED; 3700 enqueue(q); 3701 } 3702 3703 @Override 3704 protected void forward(QueuedInputEvent q) { 3705 // Clear the deferred flag. 3706 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED; 3707 3708 // Fast path if the queue is empty. 3709 QueuedInputEvent curr = mQueueHead; 3710 if (curr == null) { 3711 super.forward(q); 3712 return; 3713 } 3714 3715 // Determine whether the event must be serialized behind any others 3716 // before it can be delivered to the next stage. This is done because 3717 // deferred events might be handled out of order by the stage. 3718 final int deviceId = q.mEvent.getDeviceId(); 3719 QueuedInputEvent prev = null; 3720 boolean blocked = false; 3721 while (curr != null && curr != q) { 3722 if (!blocked && deviceId == curr.mEvent.getDeviceId()) { 3723 blocked = true; 3724 } 3725 prev = curr; 3726 curr = curr.mNext; 3727 } 3728 3729 // If the event is blocked, then leave it in the queue to be delivered later. 3730 // Note that the event might not yet be in the queue if it was not previously 3731 // deferred so we will enqueue it if needed. 3732 if (blocked) { 3733 if (curr == null) { 3734 enqueue(q); 3735 } 3736 return; 3737 } 3738 3739 // The event is not blocked. Deliver it immediately. 3740 if (curr != null) { 3741 curr = curr.mNext; 3742 dequeue(q, prev); 3743 } 3744 super.forward(q); 3745 3746 // Dequeuing this event may have unblocked successors. Deliver them. 3747 while (curr != null) { 3748 if (deviceId == curr.mEvent.getDeviceId()) { 3749 if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) { 3750 break; 3751 } 3752 QueuedInputEvent next = curr.mNext; 3753 dequeue(curr, prev); 3754 super.forward(curr); 3755 curr = next; 3756 } else { 3757 prev = curr; 3758 curr = curr.mNext; 3759 } 3760 } 3761 } 3762 3763 @Override 3764 protected void apply(QueuedInputEvent q, int result) { 3765 if (result == DEFER) { 3766 defer(q); 3767 } else { 3768 super.apply(q, result); 3769 } 3770 } 3771 3772 private void enqueue(QueuedInputEvent q) { 3773 if (mQueueTail == null) { 3774 mQueueHead = q; 3775 mQueueTail = q; 3776 } else { 3777 mQueueTail.mNext = q; 3778 mQueueTail = q; 3779 } 3780 3781 mQueueLength += 1; 3782 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3783 } 3784 3785 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) { 3786 if (prev == null) { 3787 mQueueHead = q.mNext; 3788 } else { 3789 prev.mNext = q.mNext; 3790 } 3791 if (mQueueTail == q) { 3792 mQueueTail = prev; 3793 } 3794 q.mNext = null; 3795 3796 mQueueLength -= 1; 3797 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3798 } 3799 3800 @Override 3801 void dump(String prefix, PrintWriter writer) { 3802 writer.print(prefix); 3803 writer.print(getClass().getName()); 3804 writer.print(": mQueueLength="); 3805 writer.println(mQueueLength); 3806 3807 super.dump(prefix, writer); 3808 } 3809 } 3810 3811 /** 3812 * Delivers pre-ime input events to a native activity. 3813 * Does not support pointer events. 3814 */ 3815 final class NativePreImeInputStage extends AsyncInputStage 3816 implements InputQueue.FinishedInputEventCallback { 3817 public NativePreImeInputStage(InputStage next, String traceCounter) { 3818 super(next, traceCounter); 3819 } 3820 3821 @Override 3822 protected int onProcess(QueuedInputEvent q) { 3823 if (mInputQueue != null && q.mEvent instanceof KeyEvent) { 3824 mInputQueue.sendInputEvent(q.mEvent, q, true, this); 3825 return DEFER; 3826 } 3827 return FORWARD; 3828 } 3829 3830 @Override 3831 public void onFinishedInputEvent(Object token, boolean handled) { 3832 QueuedInputEvent q = (QueuedInputEvent)token; 3833 if (handled) { 3834 finish(q, true); 3835 return; 3836 } 3837 forward(q); 3838 } 3839 } 3840 3841 /** 3842 * Delivers pre-ime input events to the view hierarchy. 3843 * Does not support pointer events. 3844 */ 3845 final class ViewPreImeInputStage extends InputStage { 3846 public ViewPreImeInputStage(InputStage next) { 3847 super(next); 3848 } 3849 3850 @Override 3851 protected int onProcess(QueuedInputEvent q) { 3852 if (q.mEvent instanceof KeyEvent) { 3853 return processKeyEvent(q); 3854 } 3855 return FORWARD; 3856 } 3857 3858 private int processKeyEvent(QueuedInputEvent q) { 3859 final KeyEvent event = (KeyEvent)q.mEvent; 3860 if (mView.dispatchKeyEventPreIme(event)) { 3861 return FINISH_HANDLED; 3862 } 3863 return FORWARD; 3864 } 3865 } 3866 3867 /** 3868 * Delivers input events to the ime. 3869 * Does not support pointer events. 3870 */ 3871 final class ImeInputStage extends AsyncInputStage 3872 implements InputMethodManager.FinishedInputEventCallback { 3873 public ImeInputStage(InputStage next, String traceCounter) { 3874 super(next, traceCounter); 3875 } 3876 3877 @Override 3878 protected int onProcess(QueuedInputEvent q) { 3879 if (mLastWasImTarget && !isInLocalFocusMode()) { 3880 InputMethodManager imm = InputMethodManager.peekInstance(); 3881 if (imm != null) { 3882 final InputEvent event = q.mEvent; 3883 if (DEBUG_IMF) Log.v(TAG, "Sending input event to IME: " + event); 3884 int result = imm.dispatchInputEvent(event, q, this, mHandler); 3885 if (result == InputMethodManager.DISPATCH_HANDLED) { 3886 return FINISH_HANDLED; 3887 } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) { 3888 // The IME could not handle it, so skip along to the next InputStage 3889 return FORWARD; 3890 } else { 3891 return DEFER; // callback will be invoked later 3892 } 3893 } 3894 } 3895 return FORWARD; 3896 } 3897 3898 @Override 3899 public void onFinishedInputEvent(Object token, boolean handled) { 3900 QueuedInputEvent q = (QueuedInputEvent)token; 3901 if (handled) { 3902 finish(q, true); 3903 return; 3904 } 3905 forward(q); 3906 } 3907 } 3908 3909 /** 3910 * Performs early processing of post-ime input events. 3911 */ 3912 final class EarlyPostImeInputStage extends InputStage { 3913 public EarlyPostImeInputStage(InputStage next) { 3914 super(next); 3915 } 3916 3917 @Override 3918 protected int onProcess(QueuedInputEvent q) { 3919 if (q.mEvent instanceof KeyEvent) { 3920 return processKeyEvent(q); 3921 } else { 3922 final int source = q.mEvent.getSource(); 3923 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3924 return processPointerEvent(q); 3925 } 3926 } 3927 return FORWARD; 3928 } 3929 3930 private int processKeyEvent(QueuedInputEvent q) { 3931 final KeyEvent event = (KeyEvent)q.mEvent; 3932 3933 // If the key's purpose is to exit touch mode then we consume it 3934 // and consider it handled. 3935 if (checkForLeavingTouchModeAndConsume(event)) { 3936 return FINISH_HANDLED; 3937 } 3938 3939 // Make sure the fallback event policy sees all keys that will be 3940 // delivered to the view hierarchy. 3941 mFallbackEventHandler.preDispatchKeyEvent(event); 3942 return FORWARD; 3943 } 3944 3945 private int processPointerEvent(QueuedInputEvent q) { 3946 final MotionEvent event = (MotionEvent)q.mEvent; 3947 3948 // Translate the pointer event for compatibility, if needed. 3949 if (mTranslator != null) { 3950 mTranslator.translateEventInScreenToAppWindow(event); 3951 } 3952 3953 // Enter touch mode on down or scroll. 3954 final int action = event.getAction(); 3955 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3956 ensureTouchMode(true); 3957 } 3958 3959 // Offset the scroll position. 3960 if (mCurScrollY != 0) { 3961 event.offsetLocation(0, mCurScrollY); 3962 } 3963 3964 // Remember the touch position for possible drag-initiation. 3965 if (event.isTouchEvent()) { 3966 mLastTouchPoint.x = event.getRawX(); 3967 mLastTouchPoint.y = event.getRawY(); 3968 } 3969 return FORWARD; 3970 } 3971 } 3972 3973 /** 3974 * Delivers post-ime input events to a native activity. 3975 */ 3976 final class NativePostImeInputStage extends AsyncInputStage 3977 implements InputQueue.FinishedInputEventCallback { 3978 public NativePostImeInputStage(InputStage next, String traceCounter) { 3979 super(next, traceCounter); 3980 } 3981 3982 @Override 3983 protected int onProcess(QueuedInputEvent q) { 3984 if (mInputQueue != null) { 3985 mInputQueue.sendInputEvent(q.mEvent, q, false, this); 3986 return DEFER; 3987 } 3988 return FORWARD; 3989 } 3990 3991 @Override 3992 public void onFinishedInputEvent(Object token, boolean handled) { 3993 QueuedInputEvent q = (QueuedInputEvent)token; 3994 if (handled) { 3995 finish(q, true); 3996 return; 3997 } 3998 forward(q); 3999 } 4000 } 4001 4002 /** 4003 * Delivers post-ime input events to the view hierarchy. 4004 */ 4005 final class ViewPostImeInputStage extends InputStage { 4006 public ViewPostImeInputStage(InputStage next) { 4007 super(next); 4008 } 4009 4010 @Override 4011 protected int onProcess(QueuedInputEvent q) { 4012 if (q.mEvent instanceof KeyEvent) { 4013 return processKeyEvent(q); 4014 } else { 4015 final int source = q.mEvent.getSource(); 4016 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 4017 return processPointerEvent(q); 4018 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 4019 return processTrackballEvent(q); 4020 } else { 4021 return processGenericMotionEvent(q); 4022 } 4023 } 4024 } 4025 4026 @Override 4027 protected void onDeliverToNext(QueuedInputEvent q) { 4028 if (mUnbufferedInputDispatch 4029 && q.mEvent instanceof MotionEvent 4030 && ((MotionEvent)q.mEvent).isTouchEvent() 4031 && isTerminalInputEvent(q.mEvent)) { 4032 mUnbufferedInputDispatch = false; 4033 scheduleConsumeBatchedInput(); 4034 } 4035 super.onDeliverToNext(q); 4036 } 4037 4038 private int processKeyEvent(QueuedInputEvent q) { 4039 final KeyEvent event = (KeyEvent)q.mEvent; 4040 4041 // Deliver the key to the view hierarchy. 4042 if (mView.dispatchKeyEvent(event)) { 4043 return FINISH_HANDLED; 4044 } 4045 4046 if (shouldDropInputEvent(q)) { 4047 return FINISH_NOT_HANDLED; 4048 } 4049 4050 // If the Control modifier is held, try to interpret the key as a shortcut. 4051 if (event.getAction() == KeyEvent.ACTION_DOWN 4052 && event.isCtrlPressed() 4053 && event.getRepeatCount() == 0 4054 && !KeyEvent.isModifierKey(event.getKeyCode())) { 4055 if (mView.dispatchKeyShortcutEvent(event)) { 4056 return FINISH_HANDLED; 4057 } 4058 if (shouldDropInputEvent(q)) { 4059 return FINISH_NOT_HANDLED; 4060 } 4061 } 4062 4063 // Apply the fallback event policy. 4064 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 4065 return FINISH_HANDLED; 4066 } 4067 if (shouldDropInputEvent(q)) { 4068 return FINISH_NOT_HANDLED; 4069 } 4070 4071 // Handle automatic focus changes. 4072 if (event.getAction() == KeyEvent.ACTION_DOWN) { 4073 int direction = 0; 4074 switch (event.getKeyCode()) { 4075 case KeyEvent.KEYCODE_DPAD_LEFT: 4076 if (event.hasNoModifiers()) { 4077 direction = View.FOCUS_LEFT; 4078 } 4079 break; 4080 case KeyEvent.KEYCODE_DPAD_RIGHT: 4081 if (event.hasNoModifiers()) { 4082 direction = View.FOCUS_RIGHT; 4083 } 4084 break; 4085 case KeyEvent.KEYCODE_DPAD_UP: 4086 if (event.hasNoModifiers()) { 4087 direction = View.FOCUS_UP; 4088 } 4089 break; 4090 case KeyEvent.KEYCODE_DPAD_DOWN: 4091 if (event.hasNoModifiers()) { 4092 direction = View.FOCUS_DOWN; 4093 } 4094 break; 4095 case KeyEvent.KEYCODE_TAB: 4096 if (event.hasNoModifiers()) { 4097 direction = View.FOCUS_FORWARD; 4098 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 4099 direction = View.FOCUS_BACKWARD; 4100 } 4101 break; 4102 } 4103 if (direction != 0) { 4104 View focused = mView.findFocus(); 4105 if (focused != null) { 4106 View v = focused.focusSearch(direction); 4107 if (v != null && v != focused) { 4108 // do the math the get the interesting rect 4109 // of previous focused into the coord system of 4110 // newly focused view 4111 focused.getFocusedRect(mTempRect); 4112 if (mView instanceof ViewGroup) { 4113 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 4114 focused, mTempRect); 4115 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 4116 v, mTempRect); 4117 } 4118 if (v.requestFocus(direction, mTempRect)) { 4119 playSoundEffect(SoundEffectConstants 4120 .getContantForFocusDirection(direction)); 4121 return FINISH_HANDLED; 4122 } 4123 } 4124 4125 // Give the focused view a last chance to handle the dpad key. 4126 if (mView.dispatchUnhandledMove(focused, direction)) { 4127 return FINISH_HANDLED; 4128 } 4129 } else { 4130 // find the best view to give focus to in this non-touch-mode with no-focus 4131 View v = focusSearch(null, direction); 4132 if (v != null && v.requestFocus(direction)) { 4133 return FINISH_HANDLED; 4134 } 4135 } 4136 } 4137 } 4138 return FORWARD; 4139 } 4140 4141 private int processPointerEvent(QueuedInputEvent q) { 4142 final MotionEvent event = (MotionEvent)q.mEvent; 4143 4144 mAttachInfo.mUnbufferedDispatchRequested = false; 4145 boolean handled = mView.dispatchPointerEvent(event); 4146 if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) { 4147 mUnbufferedInputDispatch = true; 4148 if (mConsumeBatchedInputScheduled) { 4149 scheduleConsumeBatchedInputImmediately(); 4150 } 4151 } 4152 return handled ? FINISH_HANDLED : FORWARD; 4153 } 4154 4155 private int processTrackballEvent(QueuedInputEvent q) { 4156 final MotionEvent event = (MotionEvent)q.mEvent; 4157 4158 if (mView.dispatchTrackballEvent(event)) { 4159 return FINISH_HANDLED; 4160 } 4161 return FORWARD; 4162 } 4163 4164 private int processGenericMotionEvent(QueuedInputEvent q) { 4165 final MotionEvent event = (MotionEvent)q.mEvent; 4166 4167 // Deliver the event to the view. 4168 if (mView.dispatchGenericMotionEvent(event)) { 4169 return FINISH_HANDLED; 4170 } 4171 return FORWARD; 4172 } 4173 } 4174 4175 /** 4176 * Performs synthesis of new input events from unhandled input events. 4177 */ 4178 final class SyntheticInputStage extends InputStage { 4179 private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler(); 4180 private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler(); 4181 private final SyntheticTouchNavigationHandler mTouchNavigation = 4182 new SyntheticTouchNavigationHandler(); 4183 private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler(); 4184 4185 public SyntheticInputStage() { 4186 super(null); 4187 } 4188 4189 @Override 4190 protected int onProcess(QueuedInputEvent q) { 4191 q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED; 4192 if (q.mEvent instanceof MotionEvent) { 4193 final MotionEvent event = (MotionEvent)q.mEvent; 4194 final int source = event.getSource(); 4195 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 4196 mTrackball.process(event); 4197 return FINISH_HANDLED; 4198 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 4199 mJoystick.process(event); 4200 return FINISH_HANDLED; 4201 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 4202 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 4203 mTouchNavigation.process(event); 4204 return FINISH_HANDLED; 4205 } 4206 } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) { 4207 mKeyboard.process((KeyEvent)q.mEvent); 4208 return FINISH_HANDLED; 4209 } 4210 4211 return FORWARD; 4212 } 4213 4214 @Override 4215 protected void onDeliverToNext(QueuedInputEvent q) { 4216 if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) { 4217 // Cancel related synthetic events if any prior stage has handled the event. 4218 if (q.mEvent instanceof MotionEvent) { 4219 final MotionEvent event = (MotionEvent)q.mEvent; 4220 final int source = event.getSource(); 4221 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 4222 mTrackball.cancel(event); 4223 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 4224 mJoystick.cancel(event); 4225 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 4226 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 4227 mTouchNavigation.cancel(event); 4228 } 4229 } 4230 } 4231 super.onDeliverToNext(q); 4232 } 4233 } 4234 4235 /** 4236 * Creates dpad events from unhandled trackball movements. 4237 */ 4238 final class SyntheticTrackballHandler { 4239 private final TrackballAxis mX = new TrackballAxis(); 4240 private final TrackballAxis mY = new TrackballAxis(); 4241 private long mLastTime; 4242 4243 public void process(MotionEvent event) { 4244 // Translate the trackball event into DPAD keys and try to deliver those. 4245 long curTime = SystemClock.uptimeMillis(); 4246 if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) { 4247 // It has been too long since the last movement, 4248 // so restart at the beginning. 4249 mX.reset(0); 4250 mY.reset(0); 4251 mLastTime = curTime; 4252 } 4253 4254 final int action = event.getAction(); 4255 final int metaState = event.getMetaState(); 4256 switch (action) { 4257 case MotionEvent.ACTION_DOWN: 4258 mX.reset(2); 4259 mY.reset(2); 4260 enqueueInputEvent(new KeyEvent(curTime, curTime, 4261 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 4262 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4263 InputDevice.SOURCE_KEYBOARD)); 4264 break; 4265 case MotionEvent.ACTION_UP: 4266 mX.reset(2); 4267 mY.reset(2); 4268 enqueueInputEvent(new KeyEvent(curTime, curTime, 4269 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 4270 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4271 InputDevice.SOURCE_KEYBOARD)); 4272 break; 4273 } 4274 4275 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step=" 4276 + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration 4277 + " move=" + event.getX() 4278 + " / Y=" + mY.position + " step=" 4279 + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration 4280 + " move=" + event.getY()); 4281 final float xOff = mX.collect(event.getX(), event.getEventTime(), "X"); 4282 final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y"); 4283 4284 // Generate DPAD events based on the trackball movement. 4285 // We pick the axis that has moved the most as the direction of 4286 // the DPAD. When we generate DPAD events for one axis, then the 4287 // other axis is reset -- we don't want to perform DPAD jumps due 4288 // to slight movements in the trackball when making major movements 4289 // along the other axis. 4290 int keycode = 0; 4291 int movement = 0; 4292 float accel = 1; 4293 if (xOff > yOff) { 4294 movement = mX.generate(); 4295 if (movement != 0) { 4296 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 4297 : KeyEvent.KEYCODE_DPAD_LEFT; 4298 accel = mX.acceleration; 4299 mY.reset(2); 4300 } 4301 } else if (yOff > 0) { 4302 movement = mY.generate(); 4303 if (movement != 0) { 4304 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 4305 : KeyEvent.KEYCODE_DPAD_UP; 4306 accel = mY.acceleration; 4307 mX.reset(2); 4308 } 4309 } 4310 4311 if (keycode != 0) { 4312 if (movement < 0) movement = -movement; 4313 int accelMovement = (int)(movement * accel); 4314 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 4315 + " accelMovement=" + accelMovement 4316 + " accel=" + accel); 4317 if (accelMovement > movement) { 4318 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4319 + keycode); 4320 movement--; 4321 int repeatCount = accelMovement - movement; 4322 enqueueInputEvent(new KeyEvent(curTime, curTime, 4323 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 4324 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4325 InputDevice.SOURCE_KEYBOARD)); 4326 } 4327 while (movement > 0) { 4328 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4329 + keycode); 4330 movement--; 4331 curTime = SystemClock.uptimeMillis(); 4332 enqueueInputEvent(new KeyEvent(curTime, curTime, 4333 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 4334 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4335 InputDevice.SOURCE_KEYBOARD)); 4336 enqueueInputEvent(new KeyEvent(curTime, curTime, 4337 KeyEvent.ACTION_UP, keycode, 0, metaState, 4338 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4339 InputDevice.SOURCE_KEYBOARD)); 4340 } 4341 mLastTime = curTime; 4342 } 4343 } 4344 4345 public void cancel(MotionEvent event) { 4346 mLastTime = Integer.MIN_VALUE; 4347 4348 // If we reach this, we consumed a trackball event. 4349 // Because we will not translate the trackball event into a key event, 4350 // touch mode will not exit, so we exit touch mode here. 4351 if (mView != null && mAdded) { 4352 ensureTouchMode(false); 4353 } 4354 } 4355 } 4356 4357 /** 4358 * Maintains state information for a single trackball axis, generating 4359 * discrete (DPAD) movements based on raw trackball motion. 4360 */ 4361 static final class TrackballAxis { 4362 /** 4363 * The maximum amount of acceleration we will apply. 4364 */ 4365 static final float MAX_ACCELERATION = 20; 4366 4367 /** 4368 * The maximum amount of time (in milliseconds) between events in order 4369 * for us to consider the user to be doing fast trackball movements, 4370 * and thus apply an acceleration. 4371 */ 4372 static final long FAST_MOVE_TIME = 150; 4373 4374 /** 4375 * Scaling factor to the time (in milliseconds) between events to how 4376 * much to multiple/divide the current acceleration. When movement 4377 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4378 * FAST_MOVE_TIME it divides it. 4379 */ 4380 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4381 4382 static final float FIRST_MOVEMENT_THRESHOLD = 0.5f; 4383 static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f; 4384 static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f; 4385 4386 float position; 4387 float acceleration = 1; 4388 long lastMoveTime = 0; 4389 int step; 4390 int dir; 4391 int nonAccelMovement; 4392 4393 void reset(int _step) { 4394 position = 0; 4395 acceleration = 1; 4396 lastMoveTime = 0; 4397 step = _step; 4398 dir = 0; 4399 } 4400 4401 /** 4402 * Add trackball movement into the state. If the direction of movement 4403 * has been reversed, the state is reset before adding the 4404 * movement (so that you don't have to compensate for any previously 4405 * collected movement before see the result of the movement in the 4406 * new direction). 4407 * 4408 * @return Returns the absolute value of the amount of movement 4409 * collected so far. 4410 */ 4411 float collect(float off, long time, String axis) { 4412 long normTime; 4413 if (off > 0) { 4414 normTime = (long)(off * FAST_MOVE_TIME); 4415 if (dir < 0) { 4416 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4417 position = 0; 4418 step = 0; 4419 acceleration = 1; 4420 lastMoveTime = 0; 4421 } 4422 dir = 1; 4423 } else if (off < 0) { 4424 normTime = (long)((-off) * FAST_MOVE_TIME); 4425 if (dir > 0) { 4426 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4427 position = 0; 4428 step = 0; 4429 acceleration = 1; 4430 lastMoveTime = 0; 4431 } 4432 dir = -1; 4433 } else { 4434 normTime = 0; 4435 } 4436 4437 // The number of milliseconds between each movement that is 4438 // considered "normal" and will not result in any acceleration 4439 // or deceleration, scaled by the offset we have here. 4440 if (normTime > 0) { 4441 long delta = time - lastMoveTime; 4442 lastMoveTime = time; 4443 float acc = acceleration; 4444 if (delta < normTime) { 4445 // The user is scrolling rapidly, so increase acceleration. 4446 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4447 if (scale > 1) acc *= scale; 4448 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4449 + off + " normTime=" + normTime + " delta=" + delta 4450 + " scale=" + scale + " acc=" + acc); 4451 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4452 } else { 4453 // The user is scrolling slowly, so decrease acceleration. 4454 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4455 if (scale > 1) acc /= scale; 4456 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4457 + off + " normTime=" + normTime + " delta=" + delta 4458 + " scale=" + scale + " acc=" + acc); 4459 acceleration = acc > 1 ? acc : 1; 4460 } 4461 } 4462 position += off; 4463 return Math.abs(position); 4464 } 4465 4466 /** 4467 * Generate the number of discrete movement events appropriate for 4468 * the currently collected trackball movement. 4469 * 4470 * @return Returns the number of discrete movements, either positive 4471 * or negative, or 0 if there is not enough trackball movement yet 4472 * for a discrete movement. 4473 */ 4474 int generate() { 4475 int movement = 0; 4476 nonAccelMovement = 0; 4477 do { 4478 final int dir = position >= 0 ? 1 : -1; 4479 switch (step) { 4480 // If we are going to execute the first step, then we want 4481 // to do this as soon as possible instead of waiting for 4482 // a full movement, in order to make things look responsive. 4483 case 0: 4484 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) { 4485 return movement; 4486 } 4487 movement += dir; 4488 nonAccelMovement += dir; 4489 step = 1; 4490 break; 4491 // If we have generated the first movement, then we need 4492 // to wait for the second complete trackball motion before 4493 // generating the second discrete movement. 4494 case 1: 4495 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) { 4496 return movement; 4497 } 4498 movement += dir; 4499 nonAccelMovement += dir; 4500 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir; 4501 step = 2; 4502 break; 4503 // After the first two, we generate discrete movements 4504 // consistently with the trackball, applying an acceleration 4505 // if the trackball is moving quickly. This is a simple 4506 // acceleration on top of what we already compute based 4507 // on how quickly the wheel is being turned, to apply 4508 // a longer increasing acceleration to continuous movement 4509 // in one direction. 4510 default: 4511 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) { 4512 return movement; 4513 } 4514 movement += dir; 4515 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD; 4516 float acc = acceleration; 4517 acc *= 1.1f; 4518 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4519 break; 4520 } 4521 } while (true); 4522 } 4523 } 4524 4525 /** 4526 * Creates dpad events from unhandled joystick movements. 4527 */ 4528 final class SyntheticJoystickHandler extends Handler { 4529 private final static String TAG = "SyntheticJoystickHandler"; 4530 private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1; 4531 private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2; 4532 4533 private int mLastXDirection; 4534 private int mLastYDirection; 4535 private int mLastXKeyCode; 4536 private int mLastYKeyCode; 4537 4538 public SyntheticJoystickHandler() { 4539 super(true); 4540 } 4541 4542 @Override 4543 public void handleMessage(Message msg) { 4544 switch (msg.what) { 4545 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT: 4546 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: { 4547 KeyEvent oldEvent = (KeyEvent)msg.obj; 4548 KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent, 4549 SystemClock.uptimeMillis(), 4550 oldEvent.getRepeatCount() + 1); 4551 if (mAttachInfo.mHasWindowFocus) { 4552 enqueueInputEvent(e); 4553 Message m = obtainMessage(msg.what, e); 4554 m.setAsynchronous(true); 4555 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay()); 4556 } 4557 } break; 4558 } 4559 } 4560 4561 public void process(MotionEvent event) { 4562 switch(event.getActionMasked()) { 4563 case MotionEvent.ACTION_CANCEL: 4564 cancel(event); 4565 break; 4566 case MotionEvent.ACTION_MOVE: 4567 update(event, true); 4568 break; 4569 default: 4570 Log.w(TAG, "Unexpected action: " + event.getActionMasked()); 4571 } 4572 } 4573 4574 private void cancel(MotionEvent event) { 4575 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4576 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4577 update(event, false); 4578 } 4579 4580 private void update(MotionEvent event, boolean synthesizeNewKeys) { 4581 final long time = event.getEventTime(); 4582 final int metaState = event.getMetaState(); 4583 final int deviceId = event.getDeviceId(); 4584 final int source = event.getSource(); 4585 4586 int xDirection = joystickAxisValueToDirection( 4587 event.getAxisValue(MotionEvent.AXIS_HAT_X)); 4588 if (xDirection == 0) { 4589 xDirection = joystickAxisValueToDirection(event.getX()); 4590 } 4591 4592 int yDirection = joystickAxisValueToDirection( 4593 event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 4594 if (yDirection == 0) { 4595 yDirection = joystickAxisValueToDirection(event.getY()); 4596 } 4597 4598 if (xDirection != mLastXDirection) { 4599 if (mLastXKeyCode != 0) { 4600 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4601 enqueueInputEvent(new KeyEvent(time, time, 4602 KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState, 4603 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4604 mLastXKeyCode = 0; 4605 } 4606 4607 mLastXDirection = xDirection; 4608 4609 if (xDirection != 0 && synthesizeNewKeys) { 4610 mLastXKeyCode = xDirection > 0 4611 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 4612 final KeyEvent e = new KeyEvent(time, time, 4613 KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState, 4614 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4615 enqueueInputEvent(e); 4616 Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e); 4617 m.setAsynchronous(true); 4618 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4619 } 4620 } 4621 4622 if (yDirection != mLastYDirection) { 4623 if (mLastYKeyCode != 0) { 4624 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4625 enqueueInputEvent(new KeyEvent(time, time, 4626 KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState, 4627 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4628 mLastYKeyCode = 0; 4629 } 4630 4631 mLastYDirection = yDirection; 4632 4633 if (yDirection != 0 && synthesizeNewKeys) { 4634 mLastYKeyCode = yDirection > 0 4635 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 4636 final KeyEvent e = new KeyEvent(time, time, 4637 KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState, 4638 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4639 enqueueInputEvent(e); 4640 Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e); 4641 m.setAsynchronous(true); 4642 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4643 } 4644 } 4645 } 4646 4647 private int joystickAxisValueToDirection(float value) { 4648 if (value >= 0.5f) { 4649 return 1; 4650 } else if (value <= -0.5f) { 4651 return -1; 4652 } else { 4653 return 0; 4654 } 4655 } 4656 } 4657 4658 /** 4659 * Creates dpad events from unhandled touch navigation movements. 4660 */ 4661 final class SyntheticTouchNavigationHandler extends Handler { 4662 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler"; 4663 private static final boolean LOCAL_DEBUG = false; 4664 4665 // Assumed nominal width and height in millimeters of a touch navigation pad, 4666 // if no resolution information is available from the input system. 4667 private static final float DEFAULT_WIDTH_MILLIMETERS = 48; 4668 private static final float DEFAULT_HEIGHT_MILLIMETERS = 48; 4669 4670 /* TODO: These constants should eventually be moved to ViewConfiguration. */ 4671 4672 // The nominal distance traveled to move by one unit. 4673 private static final int TICK_DISTANCE_MILLIMETERS = 12; 4674 4675 // Minimum and maximum fling velocity in ticks per second. 4676 // The minimum velocity should be set such that we perform enough ticks per 4677 // second that the fling appears to be fluid. For example, if we set the minimum 4678 // to 2 ticks per second, then there may be up to half a second delay between the next 4679 // to last and last ticks which is noticeably discrete and jerky. This value should 4680 // probably not be set to anything less than about 4. 4681 // If fling accuracy is a problem then consider tuning the tick distance instead. 4682 private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f; 4683 private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f; 4684 4685 // Fling velocity decay factor applied after each new key is emitted. 4686 // This parameter controls the deceleration and overall duration of the fling. 4687 // The fling stops automatically when its velocity drops below the minimum 4688 // fling velocity defined above. 4689 private static final float FLING_TICK_DECAY = 0.8f; 4690 4691 /* The input device that we are tracking. */ 4692 4693 private int mCurrentDeviceId = -1; 4694 private int mCurrentSource; 4695 private boolean mCurrentDeviceSupported; 4696 4697 /* Configuration for the current input device. */ 4698 4699 // The scaled tick distance. A movement of this amount should generally translate 4700 // into a single dpad event in a given direction. 4701 private float mConfigTickDistance; 4702 4703 // The minimum and maximum scaled fling velocity. 4704 private float mConfigMinFlingVelocity; 4705 private float mConfigMaxFlingVelocity; 4706 4707 /* Tracking state. */ 4708 4709 // The velocity tracker for detecting flings. 4710 private VelocityTracker mVelocityTracker; 4711 4712 // The active pointer id, or -1 if none. 4713 private int mActivePointerId = -1; 4714 4715 // Location where tracking started. 4716 private float mStartX; 4717 private float mStartY; 4718 4719 // Most recently observed position. 4720 private float mLastX; 4721 private float mLastY; 4722 4723 // Accumulated movement delta since the last direction key was sent. 4724 private float mAccumulatedX; 4725 private float mAccumulatedY; 4726 4727 // Set to true if any movement was delivered to the app. 4728 // Implies that tap slop was exceeded. 4729 private boolean mConsumedMovement; 4730 4731 // The most recently sent key down event. 4732 // The keycode remains set until the direction changes or a fling ends 4733 // so that repeated key events may be generated as required. 4734 private long mPendingKeyDownTime; 4735 private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4736 private int mPendingKeyRepeatCount; 4737 private int mPendingKeyMetaState; 4738 4739 // The current fling velocity while a fling is in progress. 4740 private boolean mFlinging; 4741 private float mFlingVelocity; 4742 4743 public SyntheticTouchNavigationHandler() { 4744 super(true); 4745 } 4746 4747 public void process(MotionEvent event) { 4748 // Update the current device information. 4749 final long time = event.getEventTime(); 4750 final int deviceId = event.getDeviceId(); 4751 final int source = event.getSource(); 4752 if (mCurrentDeviceId != deviceId || mCurrentSource != source) { 4753 finishKeys(time); 4754 finishTracking(time); 4755 mCurrentDeviceId = deviceId; 4756 mCurrentSource = source; 4757 mCurrentDeviceSupported = false; 4758 InputDevice device = event.getDevice(); 4759 if (device != null) { 4760 // In order to support an input device, we must know certain 4761 // characteristics about it, such as its size and resolution. 4762 InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X); 4763 InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y); 4764 if (xRange != null && yRange != null) { 4765 mCurrentDeviceSupported = true; 4766 4767 // Infer the resolution if it not actually known. 4768 float xRes = xRange.getResolution(); 4769 if (xRes <= 0) { 4770 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS; 4771 } 4772 float yRes = yRange.getResolution(); 4773 if (yRes <= 0) { 4774 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS; 4775 } 4776 float nominalRes = (xRes + yRes) * 0.5f; 4777 4778 // Precompute all of the configuration thresholds we will need. 4779 mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes; 4780 mConfigMinFlingVelocity = 4781 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4782 mConfigMaxFlingVelocity = 4783 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4784 4785 if (LOCAL_DEBUG) { 4786 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId 4787 + " (" + Integer.toHexString(mCurrentSource) + "): " 4788 + ", mConfigTickDistance=" + mConfigTickDistance 4789 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity 4790 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity); 4791 } 4792 } 4793 } 4794 } 4795 if (!mCurrentDeviceSupported) { 4796 return; 4797 } 4798 4799 // Handle the event. 4800 final int action = event.getActionMasked(); 4801 switch (action) { 4802 case MotionEvent.ACTION_DOWN: { 4803 boolean caughtFling = mFlinging; 4804 finishKeys(time); 4805 finishTracking(time); 4806 mActivePointerId = event.getPointerId(0); 4807 mVelocityTracker = VelocityTracker.obtain(); 4808 mVelocityTracker.addMovement(event); 4809 mStartX = event.getX(); 4810 mStartY = event.getY(); 4811 mLastX = mStartX; 4812 mLastY = mStartY; 4813 mAccumulatedX = 0; 4814 mAccumulatedY = 0; 4815 4816 // If we caught a fling, then pretend that the tap slop has already 4817 // been exceeded to suppress taps whose only purpose is to stop the fling. 4818 mConsumedMovement = caughtFling; 4819 break; 4820 } 4821 4822 case MotionEvent.ACTION_MOVE: 4823 case MotionEvent.ACTION_UP: { 4824 if (mActivePointerId < 0) { 4825 break; 4826 } 4827 final int index = event.findPointerIndex(mActivePointerId); 4828 if (index < 0) { 4829 finishKeys(time); 4830 finishTracking(time); 4831 break; 4832 } 4833 4834 mVelocityTracker.addMovement(event); 4835 final float x = event.getX(index); 4836 final float y = event.getY(index); 4837 mAccumulatedX += x - mLastX; 4838 mAccumulatedY += y - mLastY; 4839 mLastX = x; 4840 mLastY = y; 4841 4842 // Consume any accumulated movement so far. 4843 final int metaState = event.getMetaState(); 4844 consumeAccumulatedMovement(time, metaState); 4845 4846 // Detect taps and flings. 4847 if (action == MotionEvent.ACTION_UP) { 4848 if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4849 // It might be a fling. 4850 mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity); 4851 final float vx = mVelocityTracker.getXVelocity(mActivePointerId); 4852 final float vy = mVelocityTracker.getYVelocity(mActivePointerId); 4853 if (!startFling(time, vx, vy)) { 4854 finishKeys(time); 4855 } 4856 } 4857 finishTracking(time); 4858 } 4859 break; 4860 } 4861 4862 case MotionEvent.ACTION_CANCEL: { 4863 finishKeys(time); 4864 finishTracking(time); 4865 break; 4866 } 4867 } 4868 } 4869 4870 public void cancel(MotionEvent event) { 4871 if (mCurrentDeviceId == event.getDeviceId() 4872 && mCurrentSource == event.getSource()) { 4873 final long time = event.getEventTime(); 4874 finishKeys(time); 4875 finishTracking(time); 4876 } 4877 } 4878 4879 private void finishKeys(long time) { 4880 cancelFling(); 4881 sendKeyUp(time); 4882 } 4883 4884 private void finishTracking(long time) { 4885 if (mActivePointerId >= 0) { 4886 mActivePointerId = -1; 4887 mVelocityTracker.recycle(); 4888 mVelocityTracker = null; 4889 } 4890 } 4891 4892 private void consumeAccumulatedMovement(long time, int metaState) { 4893 final float absX = Math.abs(mAccumulatedX); 4894 final float absY = Math.abs(mAccumulatedY); 4895 if (absX >= absY) { 4896 if (absX >= mConfigTickDistance) { 4897 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX, 4898 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT); 4899 mAccumulatedY = 0; 4900 mConsumedMovement = true; 4901 } 4902 } else { 4903 if (absY >= mConfigTickDistance) { 4904 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY, 4905 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN); 4906 mAccumulatedX = 0; 4907 mConsumedMovement = true; 4908 } 4909 } 4910 } 4911 4912 private float consumeAccumulatedMovement(long time, int metaState, 4913 float accumulator, int negativeKeyCode, int positiveKeyCode) { 4914 while (accumulator <= -mConfigTickDistance) { 4915 sendKeyDownOrRepeat(time, negativeKeyCode, metaState); 4916 accumulator += mConfigTickDistance; 4917 } 4918 while (accumulator >= mConfigTickDistance) { 4919 sendKeyDownOrRepeat(time, positiveKeyCode, metaState); 4920 accumulator -= mConfigTickDistance; 4921 } 4922 return accumulator; 4923 } 4924 4925 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) { 4926 if (mPendingKeyCode != keyCode) { 4927 sendKeyUp(time); 4928 mPendingKeyDownTime = time; 4929 mPendingKeyCode = keyCode; 4930 mPendingKeyRepeatCount = 0; 4931 } else { 4932 mPendingKeyRepeatCount += 1; 4933 } 4934 mPendingKeyMetaState = metaState; 4935 4936 // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1 4937 // but it doesn't quite make sense when simulating the events in this way. 4938 if (LOCAL_DEBUG) { 4939 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode 4940 + ", repeatCount=" + mPendingKeyRepeatCount 4941 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4942 } 4943 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4944 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount, 4945 mPendingKeyMetaState, mCurrentDeviceId, 4946 KeyEvent.FLAG_FALLBACK, mCurrentSource)); 4947 } 4948 4949 private void sendKeyUp(long time) { 4950 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4951 if (LOCAL_DEBUG) { 4952 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode 4953 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4954 } 4955 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4956 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState, 4957 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK, 4958 mCurrentSource)); 4959 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4960 } 4961 } 4962 4963 private boolean startFling(long time, float vx, float vy) { 4964 if (LOCAL_DEBUG) { 4965 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy 4966 + ", min=" + mConfigMinFlingVelocity); 4967 } 4968 4969 // Flings must be oriented in the same direction as the preceding movements. 4970 switch (mPendingKeyCode) { 4971 case KeyEvent.KEYCODE_DPAD_LEFT: 4972 if (-vx >= mConfigMinFlingVelocity 4973 && Math.abs(vy) < mConfigMinFlingVelocity) { 4974 mFlingVelocity = -vx; 4975 break; 4976 } 4977 return false; 4978 4979 case KeyEvent.KEYCODE_DPAD_RIGHT: 4980 if (vx >= mConfigMinFlingVelocity 4981 && Math.abs(vy) < mConfigMinFlingVelocity) { 4982 mFlingVelocity = vx; 4983 break; 4984 } 4985 return false; 4986 4987 case KeyEvent.KEYCODE_DPAD_UP: 4988 if (-vy >= mConfigMinFlingVelocity 4989 && Math.abs(vx) < mConfigMinFlingVelocity) { 4990 mFlingVelocity = -vy; 4991 break; 4992 } 4993 return false; 4994 4995 case KeyEvent.KEYCODE_DPAD_DOWN: 4996 if (vy >= mConfigMinFlingVelocity 4997 && Math.abs(vx) < mConfigMinFlingVelocity) { 4998 mFlingVelocity = vy; 4999 break; 5000 } 5001 return false; 5002 } 5003 5004 // Post the first fling event. 5005 mFlinging = postFling(time); 5006 return mFlinging; 5007 } 5008 5009 private boolean postFling(long time) { 5010 // The idea here is to estimate the time when the pointer would have 5011 // traveled one tick distance unit given the current fling velocity. 5012 // This effect creates continuity of motion. 5013 if (mFlingVelocity >= mConfigMinFlingVelocity) { 5014 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000); 5015 postAtTime(mFlingRunnable, time + delay); 5016 if (LOCAL_DEBUG) { 5017 Log.d(LOCAL_TAG, "Posted fling: velocity=" 5018 + mFlingVelocity + ", delay=" + delay 5019 + ", keyCode=" + mPendingKeyCode); 5020 } 5021 return true; 5022 } 5023 return false; 5024 } 5025 5026 private void cancelFling() { 5027 if (mFlinging) { 5028 removeCallbacks(mFlingRunnable); 5029 mFlinging = false; 5030 } 5031 } 5032 5033 private final Runnable mFlingRunnable = new Runnable() { 5034 @Override 5035 public void run() { 5036 final long time = SystemClock.uptimeMillis(); 5037 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState); 5038 mFlingVelocity *= FLING_TICK_DECAY; 5039 if (!postFling(time)) { 5040 mFlinging = false; 5041 finishKeys(time); 5042 } 5043 } 5044 }; 5045 } 5046 5047 final class SyntheticKeyboardHandler { 5048 public void process(KeyEvent event) { 5049 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) { 5050 return; 5051 } 5052 5053 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 5054 final int keyCode = event.getKeyCode(); 5055 final int metaState = event.getMetaState(); 5056 5057 // Check for fallback actions specified by the key character map. 5058 KeyCharacterMap.FallbackAction fallbackAction = 5059 kcm.getFallbackAction(keyCode, metaState); 5060 if (fallbackAction != null) { 5061 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 5062 KeyEvent fallbackEvent = KeyEvent.obtain( 5063 event.getDownTime(), event.getEventTime(), 5064 event.getAction(), fallbackAction.keyCode, 5065 event.getRepeatCount(), fallbackAction.metaState, 5066 event.getDeviceId(), event.getScanCode(), 5067 flags, event.getSource(), null); 5068 fallbackAction.recycle(); 5069 enqueueInputEvent(fallbackEvent); 5070 } 5071 } 5072 } 5073 5074 /** 5075 * Returns true if the key is used for keyboard navigation. 5076 * @param keyEvent The key event. 5077 * @return True if the key is used for keyboard navigation. 5078 */ 5079 private static boolean isNavigationKey(KeyEvent keyEvent) { 5080 switch (keyEvent.getKeyCode()) { 5081 case KeyEvent.KEYCODE_DPAD_LEFT: 5082 case KeyEvent.KEYCODE_DPAD_RIGHT: 5083 case KeyEvent.KEYCODE_DPAD_UP: 5084 case KeyEvent.KEYCODE_DPAD_DOWN: 5085 case KeyEvent.KEYCODE_DPAD_CENTER: 5086 case KeyEvent.KEYCODE_PAGE_UP: 5087 case KeyEvent.KEYCODE_PAGE_DOWN: 5088 case KeyEvent.KEYCODE_MOVE_HOME: 5089 case KeyEvent.KEYCODE_MOVE_END: 5090 case KeyEvent.KEYCODE_TAB: 5091 case KeyEvent.KEYCODE_SPACE: 5092 case KeyEvent.KEYCODE_ENTER: 5093 return true; 5094 } 5095 return false; 5096 } 5097 5098 /** 5099 * Returns true if the key is used for typing. 5100 * @param keyEvent The key event. 5101 * @return True if the key is used for typing. 5102 */ 5103 private static boolean isTypingKey(KeyEvent keyEvent) { 5104 return keyEvent.getUnicodeChar() > 0; 5105 } 5106 5107 /** 5108 * See if the key event means we should leave touch mode (and leave touch mode if so). 5109 * @param event The key event. 5110 * @return Whether this key event should be consumed (meaning the act of 5111 * leaving touch mode alone is considered the event). 5112 */ 5113 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 5114 // Only relevant in touch mode. 5115 if (!mAttachInfo.mInTouchMode) { 5116 return false; 5117 } 5118 5119 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 5120 final int action = event.getAction(); 5121 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 5122 return false; 5123 } 5124 5125 // Don't leave touch mode if the IME told us not to. 5126 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 5127 return false; 5128 } 5129 5130 // If the key can be used for keyboard navigation then leave touch mode 5131 // and select a focused view if needed (in ensureTouchMode). 5132 // When a new focused view is selected, we consume the navigation key because 5133 // navigation doesn't make much sense unless a view already has focus so 5134 // the key's purpose is to set focus. 5135 if (isNavigationKey(event)) { 5136 return ensureTouchMode(false); 5137 } 5138 5139 // If the key can be used for typing then leave touch mode 5140 // and select a focused view if needed (in ensureTouchMode). 5141 // Always allow the view to process the typing key. 5142 if (isTypingKey(event)) { 5143 ensureTouchMode(false); 5144 return false; 5145 } 5146 5147 return false; 5148 } 5149 5150 /* drag/drop */ 5151 void setLocalDragState(Object obj) { 5152 mLocalDragState = obj; 5153 } 5154 5155 private void handleDragEvent(DragEvent event) { 5156 // From the root, only drag start/end/location are dispatched. entered/exited 5157 // are determined and dispatched by the viewgroup hierarchy, who then report 5158 // that back here for ultimate reporting back to the framework. 5159 if (mView != null && mAdded) { 5160 final int what = event.mAction; 5161 5162 if (what == DragEvent.ACTION_DRAG_EXITED) { 5163 // A direct EXITED event means that the window manager knows we've just crossed 5164 // a window boundary, so the current drag target within this one must have 5165 // just been exited. Send it the usual notifications and then we're done 5166 // for now. 5167 mView.dispatchDragEvent(event); 5168 } else { 5169 // Cache the drag description when the operation starts, then fill it in 5170 // on subsequent calls as a convenience 5171 if (what == DragEvent.ACTION_DRAG_STARTED) { 5172 mCurrentDragView = null; // Start the current-recipient tracking 5173 mDragDescription = event.mClipDescription; 5174 } else { 5175 event.mClipDescription = mDragDescription; 5176 } 5177 5178 // For events with a [screen] location, translate into window coordinates 5179 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 5180 mDragPoint.set(event.mX, event.mY); 5181 if (mTranslator != null) { 5182 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 5183 } 5184 5185 if (mCurScrollY != 0) { 5186 mDragPoint.offset(0, mCurScrollY); 5187 } 5188 5189 event.mX = mDragPoint.x; 5190 event.mY = mDragPoint.y; 5191 } 5192 5193 // Remember who the current drag target is pre-dispatch 5194 final View prevDragView = mCurrentDragView; 5195 5196 // Now dispatch the drag/drop event 5197 boolean result = mView.dispatchDragEvent(event); 5198 5199 // If we changed apparent drag target, tell the OS about it 5200 if (prevDragView != mCurrentDragView) { 5201 try { 5202 if (prevDragView != null) { 5203 mWindowSession.dragRecipientExited(mWindow); 5204 } 5205 if (mCurrentDragView != null) { 5206 mWindowSession.dragRecipientEntered(mWindow); 5207 } 5208 } catch (RemoteException e) { 5209 Slog.e(TAG, "Unable to note drag target change"); 5210 } 5211 } 5212 5213 // Report the drop result when we're done 5214 if (what == DragEvent.ACTION_DROP) { 5215 mDragDescription = null; 5216 try { 5217 Log.i(TAG, "Reporting drop result: " + result); 5218 mWindowSession.reportDropResult(mWindow, result); 5219 } catch (RemoteException e) { 5220 Log.e(TAG, "Unable to report drop result"); 5221 } 5222 } 5223 5224 // When the drag operation ends, release any local state object 5225 // that may have been in use 5226 if (what == DragEvent.ACTION_DRAG_ENDED) { 5227 setLocalDragState(null); 5228 } 5229 } 5230 } 5231 event.recycle(); 5232 } 5233 5234 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 5235 if (mSeq != args.seq) { 5236 // The sequence has changed, so we need to update our value and make 5237 // sure to do a traversal afterward so the window manager is given our 5238 // most recent data. 5239 mSeq = args.seq; 5240 mAttachInfo.mForceReportNewAttributes = true; 5241 scheduleTraversals(); 5242 } 5243 if (mView == null) return; 5244 if (args.localChanges != 0) { 5245 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 5246 } 5247 5248 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 5249 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 5250 mAttachInfo.mGlobalSystemUiVisibility = visibility; 5251 mView.dispatchSystemUiVisibilityChanged(visibility); 5252 } 5253 } 5254 5255 public void handleDispatchWindowShown() { 5256 mAttachInfo.mTreeObserver.dispatchOnWindowShown(); 5257 } 5258 5259 public void getLastTouchPoint(Point outLocation) { 5260 outLocation.x = (int) mLastTouchPoint.x; 5261 outLocation.y = (int) mLastTouchPoint.y; 5262 } 5263 5264 public void setDragFocus(View newDragTarget) { 5265 if (mCurrentDragView != newDragTarget) { 5266 mCurrentDragView = newDragTarget; 5267 } 5268 } 5269 5270 private AudioManager getAudioManager() { 5271 if (mView == null) { 5272 throw new IllegalStateException("getAudioManager called when there is no mView"); 5273 } 5274 if (mAudioManager == null) { 5275 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 5276 } 5277 return mAudioManager; 5278 } 5279 5280 public AccessibilityInteractionController getAccessibilityInteractionController() { 5281 if (mView == null) { 5282 throw new IllegalStateException("getAccessibilityInteractionController" 5283 + " called when there is no mView"); 5284 } 5285 if (mAccessibilityInteractionController == null) { 5286 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 5287 } 5288 return mAccessibilityInteractionController; 5289 } 5290 5291 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 5292 boolean insetsPending) throws RemoteException { 5293 5294 float appScale = mAttachInfo.mApplicationScale; 5295 boolean restore = false; 5296 if (params != null && mTranslator != null) { 5297 restore = true; 5298 params.backup(); 5299 mTranslator.translateWindowLayout(params); 5300 } 5301 if (params != null) { 5302 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 5303 } 5304 mPendingConfiguration.seq = 0; 5305 //Log.d(TAG, ">>>>>> CALLING relayout"); 5306 if (params != null && mOrigWindowType != params.type) { 5307 // For compatibility with old apps, don't crash here. 5308 if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 5309 Slog.w(TAG, "Window type can not be changed after " 5310 + "the window is added; ignoring change of " + mView); 5311 params.type = mOrigWindowType; 5312 } 5313 } 5314 int relayoutResult = mWindowSession.relayout( 5315 mWindow, mSeq, params, 5316 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 5317 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 5318 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 5319 mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets, 5320 mPendingStableInsets, mPendingOutsets, mPendingConfiguration, mSurface); 5321 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 5322 if (restore) { 5323 params.restore(); 5324 } 5325 5326 if (mTranslator != null) { 5327 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 5328 mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets); 5329 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 5330 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 5331 mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets); 5332 } 5333 return relayoutResult; 5334 } 5335 5336 /** 5337 * {@inheritDoc} 5338 */ 5339 @Override 5340 public void playSoundEffect(int effectId) { 5341 checkThread(); 5342 5343 try { 5344 final AudioManager audioManager = getAudioManager(); 5345 5346 switch (effectId) { 5347 case SoundEffectConstants.CLICK: 5348 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 5349 return; 5350 case SoundEffectConstants.NAVIGATION_DOWN: 5351 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 5352 return; 5353 case SoundEffectConstants.NAVIGATION_LEFT: 5354 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 5355 return; 5356 case SoundEffectConstants.NAVIGATION_RIGHT: 5357 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 5358 return; 5359 case SoundEffectConstants.NAVIGATION_UP: 5360 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 5361 return; 5362 default: 5363 throw new IllegalArgumentException("unknown effect id " + effectId + 5364 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 5365 } 5366 } catch (IllegalStateException e) { 5367 // Exception thrown by getAudioManager() when mView is null 5368 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 5369 e.printStackTrace(); 5370 } 5371 } 5372 5373 /** 5374 * {@inheritDoc} 5375 */ 5376 @Override 5377 public boolean performHapticFeedback(int effectId, boolean always) { 5378 try { 5379 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 5380 } catch (RemoteException e) { 5381 return false; 5382 } 5383 } 5384 5385 /** 5386 * {@inheritDoc} 5387 */ 5388 @Override 5389 public View focusSearch(View focused, int direction) { 5390 checkThread(); 5391 if (!(mView instanceof ViewGroup)) { 5392 return null; 5393 } 5394 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 5395 } 5396 5397 public void debug() { 5398 mView.debug(); 5399 } 5400 5401 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 5402 String innerPrefix = prefix + " "; 5403 writer.print(prefix); writer.println("ViewRoot:"); 5404 writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded); 5405 writer.print(" mRemoved="); writer.println(mRemoved); 5406 writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled="); 5407 writer.println(mConsumeBatchedInputScheduled); 5408 writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled="); 5409 writer.println(mConsumeBatchedInputImmediatelyScheduled); 5410 writer.print(innerPrefix); writer.print("mPendingInputEventCount="); 5411 writer.println(mPendingInputEventCount); 5412 writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled="); 5413 writer.println(mProcessInputEventsScheduled); 5414 writer.print(innerPrefix); writer.print("mTraversalScheduled="); 5415 writer.print(mTraversalScheduled); 5416 if (mTraversalScheduled) { 5417 writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")"); 5418 } else { 5419 writer.println(); 5420 } 5421 mFirstInputStage.dump(innerPrefix, writer); 5422 5423 mChoreographer.dump(prefix, writer); 5424 5425 writer.print(prefix); writer.println("View Hierarchy:"); 5426 dumpViewHierarchy(innerPrefix, writer, mView); 5427 } 5428 5429 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) { 5430 writer.print(prefix); 5431 if (view == null) { 5432 writer.println("null"); 5433 return; 5434 } 5435 writer.println(view.toString()); 5436 if (!(view instanceof ViewGroup)) { 5437 return; 5438 } 5439 ViewGroup grp = (ViewGroup)view; 5440 final int N = grp.getChildCount(); 5441 if (N <= 0) { 5442 return; 5443 } 5444 prefix = prefix + " "; 5445 for (int i=0; i<N; i++) { 5446 dumpViewHierarchy(prefix, writer, grp.getChildAt(i)); 5447 } 5448 } 5449 5450 public void dumpGfxInfo(int[] info) { 5451 info[0] = info[1] = 0; 5452 if (mView != null) { 5453 getGfxInfo(mView, info); 5454 } 5455 } 5456 5457 private static void getGfxInfo(View view, int[] info) { 5458 RenderNode renderNode = view.mRenderNode; 5459 info[0]++; 5460 if (renderNode != null) { 5461 info[1] += renderNode.getDebugSize(); 5462 } 5463 5464 if (view instanceof ViewGroup) { 5465 ViewGroup group = (ViewGroup) view; 5466 5467 int count = group.getChildCount(); 5468 for (int i = 0; i < count; i++) { 5469 getGfxInfo(group.getChildAt(i), info); 5470 } 5471 } 5472 } 5473 5474 /** 5475 * @param immediate True, do now if not in traversal. False, put on queue and do later. 5476 * @return True, request has been queued. False, request has been completed. 5477 */ 5478 boolean die(boolean immediate) { 5479 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 5480 // done by dispatchDetachedFromWindow will cause havoc on return. 5481 if (immediate && !mIsInTraversal) { 5482 doDie(); 5483 return false; 5484 } 5485 5486 if (!mIsDrawing) { 5487 destroyHardwareRenderer(); 5488 } else { 5489 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 5490 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 5491 } 5492 mHandler.sendEmptyMessage(MSG_DIE); 5493 return true; 5494 } 5495 5496 void doDie() { 5497 checkThread(); 5498 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 5499 synchronized (this) { 5500 if (mRemoved) { 5501 return; 5502 } 5503 mRemoved = true; 5504 if (mAdded) { 5505 dispatchDetachedFromWindow(); 5506 } 5507 5508 if (mAdded && !mFirst) { 5509 destroyHardwareRenderer(); 5510 5511 if (mView != null) { 5512 int viewVisibility = mView.getVisibility(); 5513 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 5514 if (mWindowAttributesChanged || viewVisibilityChanged) { 5515 // If layout params have been changed, first give them 5516 // to the window manager to make sure it has the correct 5517 // animation info. 5518 try { 5519 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 5520 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 5521 mWindowSession.finishDrawing(mWindow); 5522 } 5523 } catch (RemoteException e) { 5524 } 5525 } 5526 5527 mSurface.release(); 5528 } 5529 } 5530 5531 mAdded = false; 5532 } 5533 WindowManagerGlobal.getInstance().doRemoveView(this); 5534 } 5535 5536 public void requestUpdateConfiguration(Configuration config) { 5537 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 5538 mHandler.sendMessage(msg); 5539 } 5540 5541 public void loadSystemProperties() { 5542 mHandler.post(new Runnable() { 5543 @Override 5544 public void run() { 5545 // Profiling 5546 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false); 5547 profileRendering(mAttachInfo.mHasWindowFocus); 5548 5549 // Hardware rendering 5550 if (mAttachInfo.mHardwareRenderer != null) { 5551 if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) { 5552 invalidate(); 5553 } 5554 } 5555 5556 // Layout debugging 5557 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false); 5558 if (layout != mAttachInfo.mDebugLayout) { 5559 mAttachInfo.mDebugLayout = layout; 5560 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 5561 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 5562 } 5563 } 5564 } 5565 }); 5566 } 5567 5568 private void destroyHardwareRenderer() { 5569 HardwareRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer; 5570 5571 if (hardwareRenderer != null) { 5572 if (mView != null) { 5573 hardwareRenderer.destroyHardwareResources(mView); 5574 } 5575 hardwareRenderer.destroy(); 5576 hardwareRenderer.setRequested(false); 5577 5578 mAttachInfo.mHardwareRenderer = null; 5579 mAttachInfo.mHardwareAccelerated = false; 5580 } 5581 } 5582 5583 public void dispatchFinishInputConnection(InputConnection connection) { 5584 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 5585 mHandler.sendMessage(msg); 5586 } 5587 5588 public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets, 5589 Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw, 5590 Configuration newConfig) { 5591 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 5592 + " contentInsets=" + contentInsets.toShortString() 5593 + " visibleInsets=" + visibleInsets.toShortString() 5594 + " reportDraw=" + reportDraw); 5595 5596 // Tell all listeners that we are resizing the window so that the chrome can get 5597 // updated as fast as possible on a separate thread, 5598 if (mDragResizing) { 5599 synchronized (mWindowCallbacks) { 5600 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) { 5601 mWindowCallbacks.get(i).onWindowSizeIsChanging(frame); 5602 } 5603 } 5604 } 5605 5606 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 5607 if (mTranslator != null) { 5608 mTranslator.translateRectInScreenToAppWindow(frame); 5609 mTranslator.translateRectInScreenToAppWindow(overscanInsets); 5610 mTranslator.translateRectInScreenToAppWindow(contentInsets); 5611 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 5612 } 5613 SomeArgs args = SomeArgs.obtain(); 5614 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 5615 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 5616 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 5617 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 5618 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 5619 args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets; 5620 args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets; 5621 args.arg7 = sameProcessCall ? new Rect(outsets) : outsets; 5622 msg.obj = args; 5623 mHandler.sendMessage(msg); 5624 } 5625 5626 public void dispatchMoved(int newX, int newY) { 5627 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 5628 if (mTranslator != null) { 5629 PointF point = new PointF(newX, newY); 5630 mTranslator.translatePointInScreenToAppWindow(point); 5631 newX = (int) (point.x + 0.5); 5632 newY = (int) (point.y + 0.5); 5633 } 5634 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 5635 mHandler.sendMessage(msg); 5636 } 5637 5638 /** 5639 * Represents a pending input event that is waiting in a queue. 5640 * 5641 * Input events are processed in serial order by the timestamp specified by 5642 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 5643 * one input event to the application at a time and waits for the application 5644 * to finish handling it before delivering the next one. 5645 * 5646 * However, because the application or IME can synthesize and inject multiple 5647 * key events at a time without going through the input dispatcher, we end up 5648 * needing a queue on the application's side. 5649 */ 5650 private static final class QueuedInputEvent { 5651 public static final int FLAG_DELIVER_POST_IME = 1 << 0; 5652 public static final int FLAG_DEFERRED = 1 << 1; 5653 public static final int FLAG_FINISHED = 1 << 2; 5654 public static final int FLAG_FINISHED_HANDLED = 1 << 3; 5655 public static final int FLAG_RESYNTHESIZED = 1 << 4; 5656 public static final int FLAG_UNHANDLED = 1 << 5; 5657 5658 public QueuedInputEvent mNext; 5659 5660 public InputEvent mEvent; 5661 public InputEventReceiver mReceiver; 5662 public int mFlags; 5663 5664 public boolean shouldSkipIme() { 5665 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) { 5666 return true; 5667 } 5668 return mEvent instanceof MotionEvent 5669 && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER); 5670 } 5671 5672 public boolean shouldSendToSynthesizer() { 5673 if ((mFlags & FLAG_UNHANDLED) != 0) { 5674 return true; 5675 } 5676 5677 return false; 5678 } 5679 5680 @Override 5681 public String toString() { 5682 StringBuilder sb = new StringBuilder("QueuedInputEvent{flags="); 5683 boolean hasPrevious = false; 5684 hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb); 5685 hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb); 5686 hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb); 5687 hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb); 5688 hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb); 5689 hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb); 5690 if (!hasPrevious) { 5691 sb.append("0"); 5692 } 5693 sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false")); 5694 sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false")); 5695 sb.append(", mEvent=" + mEvent + "}"); 5696 return sb.toString(); 5697 } 5698 5699 private boolean flagToString(String name, int flag, 5700 boolean hasPrevious, StringBuilder sb) { 5701 if ((mFlags & flag) != 0) { 5702 if (hasPrevious) { 5703 sb.append("|"); 5704 } 5705 sb.append(name); 5706 return true; 5707 } 5708 return hasPrevious; 5709 } 5710 } 5711 5712 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 5713 InputEventReceiver receiver, int flags) { 5714 QueuedInputEvent q = mQueuedInputEventPool; 5715 if (q != null) { 5716 mQueuedInputEventPoolSize -= 1; 5717 mQueuedInputEventPool = q.mNext; 5718 q.mNext = null; 5719 } else { 5720 q = new QueuedInputEvent(); 5721 } 5722 5723 q.mEvent = event; 5724 q.mReceiver = receiver; 5725 q.mFlags = flags; 5726 return q; 5727 } 5728 5729 private void recycleQueuedInputEvent(QueuedInputEvent q) { 5730 q.mEvent = null; 5731 q.mReceiver = null; 5732 5733 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 5734 mQueuedInputEventPoolSize += 1; 5735 q.mNext = mQueuedInputEventPool; 5736 mQueuedInputEventPool = q; 5737 } 5738 } 5739 5740 void enqueueInputEvent(InputEvent event) { 5741 enqueueInputEvent(event, null, 0, false); 5742 } 5743 5744 void enqueueInputEvent(InputEvent event, 5745 InputEventReceiver receiver, int flags, boolean processImmediately) { 5746 adjustInputEventForCompatibility(event); 5747 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 5748 5749 // Always enqueue the input event in order, regardless of its time stamp. 5750 // We do this because the application or the IME may inject key events 5751 // in response to touch events and we want to ensure that the injected keys 5752 // are processed in the order they were received and we cannot trust that 5753 // the time stamp of injected events are monotonic. 5754 QueuedInputEvent last = mPendingInputEventTail; 5755 if (last == null) { 5756 mPendingInputEventHead = q; 5757 mPendingInputEventTail = q; 5758 } else { 5759 last.mNext = q; 5760 mPendingInputEventTail = q; 5761 } 5762 mPendingInputEventCount += 1; 5763 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5764 mPendingInputEventCount); 5765 5766 if (processImmediately) { 5767 doProcessInputEvents(); 5768 } else { 5769 scheduleProcessInputEvents(); 5770 } 5771 } 5772 5773 private void scheduleProcessInputEvents() { 5774 if (!mProcessInputEventsScheduled) { 5775 mProcessInputEventsScheduled = true; 5776 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 5777 msg.setAsynchronous(true); 5778 mHandler.sendMessage(msg); 5779 } 5780 } 5781 5782 void doProcessInputEvents() { 5783 // Deliver all pending input events in the queue. 5784 while (mPendingInputEventHead != null) { 5785 QueuedInputEvent q = mPendingInputEventHead; 5786 mPendingInputEventHead = q.mNext; 5787 if (mPendingInputEventHead == null) { 5788 mPendingInputEventTail = null; 5789 } 5790 q.mNext = null; 5791 5792 mPendingInputEventCount -= 1; 5793 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5794 mPendingInputEventCount); 5795 5796 long eventTime = q.mEvent.getEventTimeNano(); 5797 long oldestEventTime = eventTime; 5798 if (q.mEvent instanceof MotionEvent) { 5799 MotionEvent me = (MotionEvent)q.mEvent; 5800 if (me.getHistorySize() > 0) { 5801 oldestEventTime = me.getHistoricalEventTimeNano(0); 5802 } 5803 } 5804 mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime); 5805 5806 deliverInputEvent(q); 5807 } 5808 5809 // We are done processing all input events that we can process right now 5810 // so we can clear the pending flag immediately. 5811 if (mProcessInputEventsScheduled) { 5812 mProcessInputEventsScheduled = false; 5813 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 5814 } 5815 } 5816 5817 private void deliverInputEvent(QueuedInputEvent q) { 5818 Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent", 5819 q.mEvent.getSequenceNumber()); 5820 if (mInputEventConsistencyVerifier != null) { 5821 mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0); 5822 } 5823 5824 InputStage stage; 5825 if (q.shouldSendToSynthesizer()) { 5826 stage = mSyntheticInputStage; 5827 } else { 5828 stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage; 5829 } 5830 5831 if (stage != null) { 5832 stage.deliver(q); 5833 } else { 5834 finishInputEvent(q); 5835 } 5836 } 5837 5838 private void finishInputEvent(QueuedInputEvent q) { 5839 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent", 5840 q.mEvent.getSequenceNumber()); 5841 5842 if (q.mReceiver != null) { 5843 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0; 5844 q.mReceiver.finishInputEvent(q.mEvent, handled); 5845 } else { 5846 q.mEvent.recycleIfNeededAfterDispatch(); 5847 } 5848 5849 recycleQueuedInputEvent(q); 5850 } 5851 5852 private void adjustInputEventForCompatibility(InputEvent e) { 5853 if (mTargetSdkVersion < Build.VERSION_CODES.M && e instanceof MotionEvent) { 5854 MotionEvent motion = (MotionEvent) e; 5855 final int mask = 5856 MotionEvent.BUTTON_STYLUS_PRIMARY | MotionEvent.BUTTON_STYLUS_SECONDARY; 5857 final int buttonState = motion.getButtonState(); 5858 final int compatButtonState = (buttonState & mask) >> 4; 5859 if (compatButtonState != 0) { 5860 motion.setButtonState(buttonState | compatButtonState); 5861 } 5862 } 5863 } 5864 5865 static boolean isTerminalInputEvent(InputEvent event) { 5866 if (event instanceof KeyEvent) { 5867 final KeyEvent keyEvent = (KeyEvent)event; 5868 return keyEvent.getAction() == KeyEvent.ACTION_UP; 5869 } else { 5870 final MotionEvent motionEvent = (MotionEvent)event; 5871 final int action = motionEvent.getAction(); 5872 return action == MotionEvent.ACTION_UP 5873 || action == MotionEvent.ACTION_CANCEL 5874 || action == MotionEvent.ACTION_HOVER_EXIT; 5875 } 5876 } 5877 5878 void scheduleConsumeBatchedInput() { 5879 if (!mConsumeBatchedInputScheduled) { 5880 mConsumeBatchedInputScheduled = true; 5881 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 5882 mConsumedBatchedInputRunnable, null); 5883 } 5884 } 5885 5886 void unscheduleConsumeBatchedInput() { 5887 if (mConsumeBatchedInputScheduled) { 5888 mConsumeBatchedInputScheduled = false; 5889 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 5890 mConsumedBatchedInputRunnable, null); 5891 } 5892 } 5893 5894 void scheduleConsumeBatchedInputImmediately() { 5895 if (!mConsumeBatchedInputImmediatelyScheduled) { 5896 unscheduleConsumeBatchedInput(); 5897 mConsumeBatchedInputImmediatelyScheduled = true; 5898 mHandler.post(mConsumeBatchedInputImmediatelyRunnable); 5899 } 5900 } 5901 5902 void doConsumeBatchedInput(long frameTimeNanos) { 5903 if (mConsumeBatchedInputScheduled) { 5904 mConsumeBatchedInputScheduled = false; 5905 if (mInputEventReceiver != null) { 5906 if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos) 5907 && frameTimeNanos != -1) { 5908 // If we consumed a batch here, we want to go ahead and schedule the 5909 // consumption of batched input events on the next frame. Otherwise, we would 5910 // wait until we have more input events pending and might get starved by other 5911 // things occurring in the process. If the frame time is -1, however, then 5912 // we're in a non-batching mode, so there's no need to schedule this. 5913 scheduleConsumeBatchedInput(); 5914 } 5915 } 5916 doProcessInputEvents(); 5917 } 5918 } 5919 5920 final class TraversalRunnable implements Runnable { 5921 @Override 5922 public void run() { 5923 doTraversal(); 5924 } 5925 } 5926 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 5927 5928 final class WindowInputEventReceiver extends InputEventReceiver { 5929 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 5930 super(inputChannel, looper); 5931 } 5932 5933 @Override 5934 public void onInputEvent(InputEvent event) { 5935 enqueueInputEvent(event, this, 0, true); 5936 } 5937 5938 @Override 5939 public void onBatchedInputEventPending() { 5940 if (mUnbufferedInputDispatch) { 5941 super.onBatchedInputEventPending(); 5942 } else { 5943 scheduleConsumeBatchedInput(); 5944 } 5945 } 5946 5947 @Override 5948 public void dispose() { 5949 unscheduleConsumeBatchedInput(); 5950 super.dispose(); 5951 } 5952 } 5953 WindowInputEventReceiver mInputEventReceiver; 5954 5955 final class ConsumeBatchedInputRunnable implements Runnable { 5956 @Override 5957 public void run() { 5958 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 5959 } 5960 } 5961 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 5962 new ConsumeBatchedInputRunnable(); 5963 boolean mConsumeBatchedInputScheduled; 5964 5965 final class ConsumeBatchedInputImmediatelyRunnable implements Runnable { 5966 @Override 5967 public void run() { 5968 doConsumeBatchedInput(-1); 5969 } 5970 } 5971 final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable = 5972 new ConsumeBatchedInputImmediatelyRunnable(); 5973 boolean mConsumeBatchedInputImmediatelyScheduled; 5974 5975 final class InvalidateOnAnimationRunnable implements Runnable { 5976 private boolean mPosted; 5977 private final ArrayList<View> mViews = new ArrayList<View>(); 5978 private final ArrayList<AttachInfo.InvalidateInfo> mViewRects = 5979 new ArrayList<AttachInfo.InvalidateInfo>(); 5980 private View[] mTempViews; 5981 private AttachInfo.InvalidateInfo[] mTempViewRects; 5982 5983 public void addView(View view) { 5984 synchronized (this) { 5985 mViews.add(view); 5986 postIfNeededLocked(); 5987 } 5988 } 5989 5990 public void addViewRect(AttachInfo.InvalidateInfo info) { 5991 synchronized (this) { 5992 mViewRects.add(info); 5993 postIfNeededLocked(); 5994 } 5995 } 5996 5997 public void removeView(View view) { 5998 synchronized (this) { 5999 mViews.remove(view); 6000 6001 for (int i = mViewRects.size(); i-- > 0; ) { 6002 AttachInfo.InvalidateInfo info = mViewRects.get(i); 6003 if (info.target == view) { 6004 mViewRects.remove(i); 6005 info.recycle(); 6006 } 6007 } 6008 6009 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 6010 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 6011 mPosted = false; 6012 } 6013 } 6014 } 6015 6016 @Override 6017 public void run() { 6018 final int viewCount; 6019 final int viewRectCount; 6020 synchronized (this) { 6021 mPosted = false; 6022 6023 viewCount = mViews.size(); 6024 if (viewCount != 0) { 6025 mTempViews = mViews.toArray(mTempViews != null 6026 ? mTempViews : new View[viewCount]); 6027 mViews.clear(); 6028 } 6029 6030 viewRectCount = mViewRects.size(); 6031 if (viewRectCount != 0) { 6032 mTempViewRects = mViewRects.toArray(mTempViewRects != null 6033 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 6034 mViewRects.clear(); 6035 } 6036 } 6037 6038 for (int i = 0; i < viewCount; i++) { 6039 mTempViews[i].invalidate(); 6040 mTempViews[i] = null; 6041 } 6042 6043 for (int i = 0; i < viewRectCount; i++) { 6044 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 6045 info.target.invalidate(info.left, info.top, info.right, info.bottom); 6046 info.recycle(); 6047 } 6048 } 6049 6050 private void postIfNeededLocked() { 6051 if (!mPosted) { 6052 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 6053 mPosted = true; 6054 } 6055 } 6056 } 6057 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 6058 new InvalidateOnAnimationRunnable(); 6059 6060 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 6061 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 6062 mHandler.sendMessageDelayed(msg, delayMilliseconds); 6063 } 6064 6065 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 6066 long delayMilliseconds) { 6067 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 6068 mHandler.sendMessageDelayed(msg, delayMilliseconds); 6069 } 6070 6071 public void dispatchInvalidateOnAnimation(View view) { 6072 mInvalidateOnAnimationRunnable.addView(view); 6073 } 6074 6075 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 6076 mInvalidateOnAnimationRunnable.addViewRect(info); 6077 } 6078 6079 public void cancelInvalidate(View view) { 6080 mHandler.removeMessages(MSG_INVALIDATE, view); 6081 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 6082 // them to the pool 6083 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 6084 mInvalidateOnAnimationRunnable.removeView(view); 6085 } 6086 6087 public void dispatchInputEvent(InputEvent event) { 6088 dispatchInputEvent(event, null); 6089 } 6090 6091 public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) { 6092 SomeArgs args = SomeArgs.obtain(); 6093 args.arg1 = event; 6094 args.arg2 = receiver; 6095 Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args); 6096 msg.setAsynchronous(true); 6097 mHandler.sendMessage(msg); 6098 } 6099 6100 public void synthesizeInputEvent(InputEvent event) { 6101 Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event); 6102 msg.setAsynchronous(true); 6103 mHandler.sendMessage(msg); 6104 } 6105 6106 public void dispatchKeyFromIme(KeyEvent event) { 6107 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 6108 msg.setAsynchronous(true); 6109 mHandler.sendMessage(msg); 6110 } 6111 6112 /** 6113 * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events. 6114 * 6115 * Note that it is the responsibility of the caller of this API to recycle the InputEvent it 6116 * passes in. 6117 */ 6118 public void dispatchUnhandledInputEvent(InputEvent event) { 6119 if (event instanceof MotionEvent) { 6120 event = MotionEvent.obtain((MotionEvent) event); 6121 } 6122 synthesizeInputEvent(event); 6123 } 6124 6125 public void dispatchAppVisibility(boolean visible) { 6126 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 6127 msg.arg1 = visible ? 1 : 0; 6128 mHandler.sendMessage(msg); 6129 } 6130 6131 public void dispatchGetNewSurface() { 6132 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 6133 mHandler.sendMessage(msg); 6134 } 6135 6136 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 6137 Message msg = Message.obtain(); 6138 msg.what = MSG_WINDOW_FOCUS_CHANGED; 6139 msg.arg1 = hasFocus ? 1 : 0; 6140 msg.arg2 = inTouchMode ? 1 : 0; 6141 mHandler.sendMessage(msg); 6142 } 6143 6144 public void dispatchWindowShown() { 6145 mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN); 6146 } 6147 6148 public void dispatchCloseSystemDialogs(String reason) { 6149 Message msg = Message.obtain(); 6150 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 6151 msg.obj = reason; 6152 mHandler.sendMessage(msg); 6153 } 6154 6155 public void dispatchDragEvent(DragEvent event) { 6156 final int what; 6157 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 6158 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 6159 mHandler.removeMessages(what); 6160 } else { 6161 what = MSG_DISPATCH_DRAG_EVENT; 6162 } 6163 Message msg = mHandler.obtainMessage(what, event); 6164 mHandler.sendMessage(msg); 6165 } 6166 6167 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 6168 int localValue, int localChanges) { 6169 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 6170 args.seq = seq; 6171 args.globalVisibility = globalVisibility; 6172 args.localValue = localValue; 6173 args.localChanges = localChanges; 6174 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 6175 } 6176 6177 public void dispatchCheckFocus() { 6178 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 6179 // This will result in a call to checkFocus() below. 6180 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 6181 } 6182 } 6183 6184 /** 6185 * Post a callback to send a 6186 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 6187 * This event is send at most once every 6188 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 6189 */ 6190 private void postSendWindowContentChangedCallback(View source, int changeType) { 6191 if (mSendWindowContentChangedAccessibilityEvent == null) { 6192 mSendWindowContentChangedAccessibilityEvent = 6193 new SendWindowContentChangedAccessibilityEvent(); 6194 } 6195 mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType); 6196 } 6197 6198 /** 6199 * Remove a posted callback to send a 6200 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 6201 */ 6202 private void removeSendWindowContentChangedCallback() { 6203 if (mSendWindowContentChangedAccessibilityEvent != null) { 6204 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 6205 } 6206 } 6207 6208 @Override 6209 public boolean showContextMenuForChild(View originalView) { 6210 return false; 6211 } 6212 6213 @Override 6214 public boolean showContextMenuForChild(View originalView, float x, float y) { 6215 return false; 6216 } 6217 6218 @Override 6219 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 6220 return null; 6221 } 6222 6223 @Override 6224 public ActionMode startActionModeForChild( 6225 View originalView, ActionMode.Callback callback, int type) { 6226 return null; 6227 } 6228 6229 @Override 6230 public void createContextMenu(ContextMenu menu) { 6231 } 6232 6233 @Override 6234 public void childDrawableStateChanged(View child) { 6235 } 6236 6237 @Override 6238 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 6239 if (mView == null || mStopped || mPausedForTransition) { 6240 return false; 6241 } 6242 // Intercept accessibility focus events fired by virtual nodes to keep 6243 // track of accessibility focus position in such nodes. 6244 final int eventType = event.getEventType(); 6245 switch (eventType) { 6246 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 6247 final long sourceNodeId = event.getSourceNodeId(); 6248 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 6249 sourceNodeId); 6250 View source = mView.findViewByAccessibilityId(accessibilityViewId); 6251 if (source != null) { 6252 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 6253 if (provider != null) { 6254 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 6255 sourceNodeId); 6256 final AccessibilityNodeInfo node; 6257 if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) { 6258 node = provider.createAccessibilityNodeInfo( 6259 AccessibilityNodeProvider.HOST_VIEW_ID); 6260 } else { 6261 node = provider.createAccessibilityNodeInfo(virtualNodeId); 6262 } 6263 setAccessibilityFocus(source, node); 6264 } 6265 } 6266 } break; 6267 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 6268 final long sourceNodeId = event.getSourceNodeId(); 6269 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 6270 sourceNodeId); 6271 View source = mView.findViewByAccessibilityId(accessibilityViewId); 6272 if (source != null) { 6273 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 6274 if (provider != null) { 6275 setAccessibilityFocus(null, null); 6276 } 6277 } 6278 } break; 6279 6280 6281 case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: { 6282 handleWindowContentChangedEvent(event); 6283 } break; 6284 } 6285 mAccessibilityManager.sendAccessibilityEvent(event); 6286 return true; 6287 } 6288 6289 /** 6290 * Updates the focused virtual view, when necessary, in response to a 6291 * content changed event. 6292 * <p> 6293 * This is necessary to get updated bounds after a position change. 6294 * 6295 * @param event an accessibility event of type 6296 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} 6297 */ 6298 private void handleWindowContentChangedEvent(AccessibilityEvent event) { 6299 final View focusedHost = mAccessibilityFocusedHost; 6300 if (focusedHost == null || mAccessibilityFocusedVirtualView == null) { 6301 // No virtual view focused, nothing to do here. 6302 return; 6303 } 6304 6305 final AccessibilityNodeProvider provider = focusedHost.getAccessibilityNodeProvider(); 6306 if (provider == null) { 6307 // Error state: virtual view with no provider. Clear focus. 6308 mAccessibilityFocusedHost = null; 6309 mAccessibilityFocusedVirtualView = null; 6310 focusedHost.clearAccessibilityFocusNoCallbacks(); 6311 return; 6312 } 6313 6314 // We only care about change types that may affect the bounds of the 6315 // focused virtual view. 6316 final int changes = event.getContentChangeTypes(); 6317 if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) == 0 6318 && changes != AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) { 6319 return; 6320 } 6321 6322 final long eventSourceNodeId = event.getSourceNodeId(); 6323 final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId); 6324 6325 // Search up the tree for subtree containment. 6326 boolean hostInSubtree = false; 6327 View root = mAccessibilityFocusedHost; 6328 while (root != null && !hostInSubtree) { 6329 if (changedViewId == root.getAccessibilityViewId()) { 6330 hostInSubtree = true; 6331 } else { 6332 final ViewParent parent = root.getParent(); 6333 if (parent instanceof View) { 6334 root = (View) parent; 6335 } else { 6336 root = null; 6337 } 6338 } 6339 } 6340 6341 // We care only about changes in subtrees containing the host view. 6342 if (!hostInSubtree) { 6343 return; 6344 } 6345 6346 final long focusedSourceNodeId = mAccessibilityFocusedVirtualView.getSourceNodeId(); 6347 int focusedChildId = AccessibilityNodeInfo.getVirtualDescendantId(focusedSourceNodeId); 6348 if (focusedChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) { 6349 // TODO: Should we clear the focused virtual view? 6350 focusedChildId = AccessibilityNodeProvider.HOST_VIEW_ID; 6351 } 6352 6353 // Refresh the node for the focused virtual view. 6354 final Rect oldBounds = mTempRect; 6355 mAccessibilityFocusedVirtualView.getBoundsInScreen(oldBounds); 6356 mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId); 6357 if (mAccessibilityFocusedVirtualView == null) { 6358 // Error state: The node no longer exists. Clear focus. 6359 mAccessibilityFocusedHost = null; 6360 focusedHost.clearAccessibilityFocusNoCallbacks(); 6361 6362 // This will probably fail, but try to keep the provider's internal 6363 // state consistent by clearing focus. 6364 provider.performAction(focusedChildId, 6365 AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS.getId(), null); 6366 invalidateRectOnScreen(oldBounds); 6367 } else { 6368 // The node was refreshed, invalidate bounds if necessary. 6369 final Rect newBounds = mAccessibilityFocusedVirtualView.getBoundsInScreen(); 6370 if (!oldBounds.equals(newBounds)) { 6371 oldBounds.union(newBounds); 6372 invalidateRectOnScreen(oldBounds); 6373 } 6374 } 6375 } 6376 6377 @Override 6378 public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { 6379 postSendWindowContentChangedCallback(source, changeType); 6380 } 6381 6382 @Override 6383 public boolean canResolveLayoutDirection() { 6384 return true; 6385 } 6386 6387 @Override 6388 public boolean isLayoutDirectionResolved() { 6389 return true; 6390 } 6391 6392 @Override 6393 public int getLayoutDirection() { 6394 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6395 } 6396 6397 @Override 6398 public boolean canResolveTextDirection() { 6399 return true; 6400 } 6401 6402 @Override 6403 public boolean isTextDirectionResolved() { 6404 return true; 6405 } 6406 6407 @Override 6408 public int getTextDirection() { 6409 return View.TEXT_DIRECTION_RESOLVED_DEFAULT; 6410 } 6411 6412 @Override 6413 public boolean canResolveTextAlignment() { 6414 return true; 6415 } 6416 6417 @Override 6418 public boolean isTextAlignmentResolved() { 6419 return true; 6420 } 6421 6422 @Override 6423 public int getTextAlignment() { 6424 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT; 6425 } 6426 6427 private View getCommonPredecessor(View first, View second) { 6428 if (mTempHashSet == null) { 6429 mTempHashSet = new HashSet<View>(); 6430 } 6431 HashSet<View> seen = mTempHashSet; 6432 seen.clear(); 6433 View firstCurrent = first; 6434 while (firstCurrent != null) { 6435 seen.add(firstCurrent); 6436 ViewParent firstCurrentParent = firstCurrent.mParent; 6437 if (firstCurrentParent instanceof View) { 6438 firstCurrent = (View) firstCurrentParent; 6439 } else { 6440 firstCurrent = null; 6441 } 6442 } 6443 View secondCurrent = second; 6444 while (secondCurrent != null) { 6445 if (seen.contains(secondCurrent)) { 6446 seen.clear(); 6447 return secondCurrent; 6448 } 6449 ViewParent secondCurrentParent = secondCurrent.mParent; 6450 if (secondCurrentParent instanceof View) { 6451 secondCurrent = (View) secondCurrentParent; 6452 } else { 6453 secondCurrent = null; 6454 } 6455 } 6456 seen.clear(); 6457 return null; 6458 } 6459 6460 void checkThread() { 6461 if (mThread != Thread.currentThread()) { 6462 throw new CalledFromWrongThreadException( 6463 "Only the original thread that created a view hierarchy can touch its views."); 6464 } 6465 } 6466 6467 @Override 6468 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 6469 // ViewAncestor never intercepts touch event, so this can be a no-op 6470 } 6471 6472 @Override 6473 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 6474 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 6475 if (rectangle != null) { 6476 mTempRect.set(rectangle); 6477 mTempRect.offset(0, -mCurScrollY); 6478 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6479 try { 6480 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect); 6481 } catch (RemoteException re) { 6482 /* ignore */ 6483 } 6484 } 6485 return scrolled; 6486 } 6487 6488 @Override 6489 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 6490 // Do nothing. 6491 } 6492 6493 @Override 6494 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { 6495 return false; 6496 } 6497 6498 @Override 6499 public void onStopNestedScroll(View target) { 6500 } 6501 6502 @Override 6503 public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) { 6504 } 6505 6506 @Override 6507 public void onNestedScroll(View target, int dxConsumed, int dyConsumed, 6508 int dxUnconsumed, int dyUnconsumed) { 6509 } 6510 6511 @Override 6512 public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { 6513 } 6514 6515 @Override 6516 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { 6517 return false; 6518 } 6519 6520 @Override 6521 public boolean onNestedPreFling(View target, float velocityX, float velocityY) { 6522 return false; 6523 } 6524 6525 @Override 6526 public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) { 6527 return false; 6528 } 6529 6530 /** 6531 * Force the window to report its next draw. 6532 * <p> 6533 * This method is only supposed to be used to speed up the interaction from SystemUI and window 6534 * manager when waiting for the first frame to be drawn when turning on the screen. DO NOT USE 6535 * unless you fully understand this interaction. 6536 * @hide 6537 */ 6538 public void setReportNextDraw() { 6539 mReportNextDraw = true; 6540 invalidate(); 6541 } 6542 6543 void changeCanvasOpacity(boolean opaque) { 6544 Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque); 6545 if (mAttachInfo.mHardwareRenderer != null) { 6546 mAttachInfo.mHardwareRenderer.setOpaque(opaque); 6547 } 6548 } 6549 6550 class TakenSurfaceHolder extends BaseSurfaceHolder { 6551 @Override 6552 public boolean onAllowLockCanvas() { 6553 return mDrawingAllowed; 6554 } 6555 6556 @Override 6557 public void onRelayoutContainer() { 6558 // Not currently interesting -- from changing between fixed and layout size. 6559 } 6560 6561 @Override 6562 public void setFormat(int format) { 6563 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 6564 } 6565 6566 @Override 6567 public void setType(int type) { 6568 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 6569 } 6570 6571 @Override 6572 public void onUpdateSurface() { 6573 // We take care of format and type changes on our own. 6574 throw new IllegalStateException("Shouldn't be here"); 6575 } 6576 6577 @Override 6578 public boolean isCreating() { 6579 return mIsCreating; 6580 } 6581 6582 @Override 6583 public void setFixedSize(int width, int height) { 6584 throw new UnsupportedOperationException( 6585 "Currently only support sizing from layout"); 6586 } 6587 6588 @Override 6589 public void setKeepScreenOn(boolean screenOn) { 6590 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 6591 } 6592 } 6593 6594 static class W extends IWindow.Stub { 6595 private final WeakReference<ViewRootImpl> mViewAncestor; 6596 private final IWindowSession mWindowSession; 6597 6598 W(ViewRootImpl viewAncestor) { 6599 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 6600 mWindowSession = viewAncestor.mWindowSession; 6601 } 6602 6603 @Override 6604 public void resized(Rect frame, Rect overscanInsets, Rect contentInsets, 6605 Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw, 6606 Configuration newConfig) { 6607 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6608 if (viewAncestor != null) { 6609 viewAncestor.dispatchResized(frame, overscanInsets, contentInsets, 6610 visibleInsets, stableInsets, outsets, reportDraw, newConfig); 6611 } 6612 } 6613 6614 @Override 6615 public void moved(int newX, int newY) { 6616 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6617 if (viewAncestor != null) { 6618 viewAncestor.dispatchMoved(newX, newY); 6619 } 6620 } 6621 6622 @Override 6623 public void dispatchAppVisibility(boolean visible) { 6624 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6625 if (viewAncestor != null) { 6626 viewAncestor.dispatchAppVisibility(visible); 6627 } 6628 } 6629 6630 @Override 6631 public void dispatchGetNewSurface() { 6632 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6633 if (viewAncestor != null) { 6634 viewAncestor.dispatchGetNewSurface(); 6635 } 6636 } 6637 6638 @Override 6639 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 6640 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6641 if (viewAncestor != null) { 6642 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 6643 } 6644 } 6645 6646 private static int checkCallingPermission(String permission) { 6647 try { 6648 return ActivityManagerNative.getDefault().checkPermission( 6649 permission, Binder.getCallingPid(), Binder.getCallingUid()); 6650 } catch (RemoteException e) { 6651 return PackageManager.PERMISSION_DENIED; 6652 } 6653 } 6654 6655 @Override 6656 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 6657 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6658 if (viewAncestor != null) { 6659 final View view = viewAncestor.mView; 6660 if (view != null) { 6661 if (checkCallingPermission(Manifest.permission.DUMP) != 6662 PackageManager.PERMISSION_GRANTED) { 6663 throw new SecurityException("Insufficient permissions to invoke" 6664 + " executeCommand() from pid=" + Binder.getCallingPid() 6665 + ", uid=" + Binder.getCallingUid()); 6666 } 6667 6668 OutputStream clientStream = null; 6669 try { 6670 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 6671 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 6672 } catch (IOException e) { 6673 e.printStackTrace(); 6674 } finally { 6675 if (clientStream != null) { 6676 try { 6677 clientStream.close(); 6678 } catch (IOException e) { 6679 e.printStackTrace(); 6680 } 6681 } 6682 } 6683 } 6684 } 6685 } 6686 6687 @Override 6688 public void closeSystemDialogs(String reason) { 6689 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6690 if (viewAncestor != null) { 6691 viewAncestor.dispatchCloseSystemDialogs(reason); 6692 } 6693 } 6694 6695 @Override 6696 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 6697 boolean sync) { 6698 if (sync) { 6699 try { 6700 mWindowSession.wallpaperOffsetsComplete(asBinder()); 6701 } catch (RemoteException e) { 6702 } 6703 } 6704 } 6705 6706 @Override 6707 public void dispatchWallpaperCommand(String action, int x, int y, 6708 int z, Bundle extras, boolean sync) { 6709 if (sync) { 6710 try { 6711 mWindowSession.wallpaperCommandComplete(asBinder(), null); 6712 } catch (RemoteException e) { 6713 } 6714 } 6715 } 6716 6717 /* Drag/drop */ 6718 @Override 6719 public void dispatchDragEvent(DragEvent event) { 6720 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6721 if (viewAncestor != null) { 6722 viewAncestor.dispatchDragEvent(event); 6723 } 6724 } 6725 6726 @Override 6727 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 6728 int localValue, int localChanges) { 6729 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6730 if (viewAncestor != null) { 6731 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 6732 localValue, localChanges); 6733 } 6734 } 6735 6736 @Override 6737 public void dispatchWindowShown() { 6738 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6739 if (viewAncestor != null) { 6740 viewAncestor.dispatchWindowShown(); 6741 } 6742 } 6743 } 6744 6745 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 6746 public CalledFromWrongThreadException(String msg) { 6747 super(msg); 6748 } 6749 } 6750 6751 static HandlerActionQueue getRunQueue() { 6752 HandlerActionQueue rq = sRunQueues.get(); 6753 if (rq != null) { 6754 return rq; 6755 } 6756 rq = new HandlerActionQueue(); 6757 sRunQueues.set(rq); 6758 return rq; 6759 } 6760 6761 /** 6762 * Start a drag resizing which will inform all listeners that a window resize is taking place. 6763 */ 6764 private void startDragResizing(Rect initialBounds) { 6765 if (!mDragResizing) { 6766 mDragResizing = true; 6767 synchronized (mWindowCallbacks) { 6768 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) { 6769 mWindowCallbacks.get(i).onWindowDragResizeStart(initialBounds); 6770 } 6771 } 6772 mFullRedrawNeeded = true; 6773 } 6774 } 6775 6776 /** 6777 * End a drag resize which will inform all listeners that a window resize has ended. 6778 */ 6779 private void endDragResizing() { 6780 if (mDragResizing) { 6781 mDragResizing = false; 6782 synchronized (mWindowCallbacks) { 6783 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) { 6784 mWindowCallbacks.get(i).onWindowDragResizeEnd(); 6785 } 6786 } 6787 mFullRedrawNeeded = true; 6788 } 6789 } 6790 6791 /** 6792 * Class for managing the accessibility interaction connection 6793 * based on the global accessibility state. 6794 */ 6795 final class AccessibilityInteractionConnectionManager 6796 implements AccessibilityStateChangeListener { 6797 @Override 6798 public void onAccessibilityStateChanged(boolean enabled) { 6799 if (enabled) { 6800 ensureConnection(); 6801 if (mAttachInfo.mHasWindowFocus) { 6802 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 6803 View focusedView = mView.findFocus(); 6804 if (focusedView != null && focusedView != mView) { 6805 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6806 } 6807 } 6808 } else { 6809 ensureNoConnection(); 6810 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 6811 } 6812 } 6813 6814 public void ensureConnection() { 6815 final boolean registered = 6816 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6817 if (!registered) { 6818 mAttachInfo.mAccessibilityWindowId = 6819 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 6820 new AccessibilityInteractionConnection(ViewRootImpl.this)); 6821 } 6822 } 6823 6824 public void ensureNoConnection() { 6825 final boolean registered = 6826 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6827 if (registered) { 6828 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6829 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 6830 } 6831 } 6832 } 6833 6834 final class HighContrastTextManager implements HighTextContrastChangeListener { 6835 HighContrastTextManager() { 6836 mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled(); 6837 } 6838 @Override 6839 public void onHighTextContrastStateChanged(boolean enabled) { 6840 mAttachInfo.mHighContrastText = enabled; 6841 6842 // Destroy Displaylists so they can be recreated with high contrast recordings 6843 destroyHardwareResources(); 6844 6845 // Schedule redraw, which will rerecord + redraw all text 6846 invalidate(); 6847 } 6848 } 6849 6850 /** 6851 * This class is an interface this ViewAncestor provides to the 6852 * AccessibilityManagerService to the latter can interact with 6853 * the view hierarchy in this ViewAncestor. 6854 */ 6855 static final class AccessibilityInteractionConnection 6856 extends IAccessibilityInteractionConnection.Stub { 6857 private final WeakReference<ViewRootImpl> mViewRootImpl; 6858 6859 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 6860 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 6861 } 6862 6863 @Override 6864 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 6865 Region interactiveRegion, int interactionId, 6866 IAccessibilityInteractionConnectionCallback callback, int flags, 6867 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6868 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6869 if (viewRootImpl != null && viewRootImpl.mView != null) { 6870 viewRootImpl.getAccessibilityInteractionController() 6871 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 6872 interactiveRegion, interactionId, callback, flags, interrogatingPid, 6873 interrogatingTid, spec); 6874 } else { 6875 // We cannot make the call and notify the caller so it does not wait. 6876 try { 6877 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6878 } catch (RemoteException re) { 6879 /* best effort - ignore */ 6880 } 6881 } 6882 } 6883 6884 @Override 6885 public void performAccessibilityAction(long accessibilityNodeId, int action, 6886 Bundle arguments, int interactionId, 6887 IAccessibilityInteractionConnectionCallback callback, int flags, 6888 int interrogatingPid, long interrogatingTid) { 6889 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6890 if (viewRootImpl != null && viewRootImpl.mView != null) { 6891 viewRootImpl.getAccessibilityInteractionController() 6892 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 6893 interactionId, callback, flags, interrogatingPid, interrogatingTid); 6894 } else { 6895 // We cannot make the call and notify the caller so it does not wait. 6896 try { 6897 callback.setPerformAccessibilityActionResult(false, interactionId); 6898 } catch (RemoteException re) { 6899 /* best effort - ignore */ 6900 } 6901 } 6902 } 6903 6904 @Override 6905 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId, 6906 String viewId, Region interactiveRegion, int interactionId, 6907 IAccessibilityInteractionConnectionCallback callback, int flags, 6908 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6909 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6910 if (viewRootImpl != null && viewRootImpl.mView != null) { 6911 viewRootImpl.getAccessibilityInteractionController() 6912 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId, 6913 viewId, interactiveRegion, interactionId, callback, flags, 6914 interrogatingPid, interrogatingTid, spec); 6915 } else { 6916 // We cannot make the call and notify the caller so it does not wait. 6917 try { 6918 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6919 } catch (RemoteException re) { 6920 /* best effort - ignore */ 6921 } 6922 } 6923 } 6924 6925 @Override 6926 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 6927 Region interactiveRegion, int interactionId, 6928 IAccessibilityInteractionConnectionCallback callback, int flags, 6929 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6930 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6931 if (viewRootImpl != null && viewRootImpl.mView != null) { 6932 viewRootImpl.getAccessibilityInteractionController() 6933 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 6934 interactiveRegion, interactionId, callback, flags, interrogatingPid, 6935 interrogatingTid, spec); 6936 } else { 6937 // We cannot make the call and notify the caller so it does not wait. 6938 try { 6939 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6940 } catch (RemoteException re) { 6941 /* best effort - ignore */ 6942 } 6943 } 6944 } 6945 6946 @Override 6947 public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion, 6948 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6949 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6950 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6951 if (viewRootImpl != null && viewRootImpl.mView != null) { 6952 viewRootImpl.getAccessibilityInteractionController() 6953 .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion, 6954 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6955 spec); 6956 } else { 6957 // We cannot make the call and notify the caller so it does not wait. 6958 try { 6959 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6960 } catch (RemoteException re) { 6961 /* best effort - ignore */ 6962 } 6963 } 6964 } 6965 6966 @Override 6967 public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion, 6968 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6969 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6970 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6971 if (viewRootImpl != null && viewRootImpl.mView != null) { 6972 viewRootImpl.getAccessibilityInteractionController() 6973 .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion, 6974 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6975 spec); 6976 } else { 6977 // We cannot make the call and notify the caller so it does not wait. 6978 try { 6979 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6980 } catch (RemoteException re) { 6981 /* best effort - ignore */ 6982 } 6983 } 6984 } 6985 } 6986 6987 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 6988 private int mChangeTypes = 0; 6989 6990 public View mSource; 6991 public long mLastEventTimeMillis; 6992 6993 @Override 6994 public void run() { 6995 // The accessibility may be turned off while we were waiting so check again. 6996 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6997 mLastEventTimeMillis = SystemClock.uptimeMillis(); 6998 AccessibilityEvent event = AccessibilityEvent.obtain(); 6999 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 7000 event.setContentChangeTypes(mChangeTypes); 7001 mSource.sendAccessibilityEventUnchecked(event); 7002 } else { 7003 mLastEventTimeMillis = 0; 7004 } 7005 // In any case reset to initial state. 7006 mSource.resetSubtreeAccessibilityStateChanged(); 7007 mSource = null; 7008 mChangeTypes = 0; 7009 } 7010 7011 public void runOrPost(View source, int changeType) { 7012 if (mSource != null) { 7013 // If there is no common predecessor, then mSource points to 7014 // a removed view, hence in this case always prefer the source. 7015 View predecessor = getCommonPredecessor(mSource, source); 7016 mSource = (predecessor != null) ? predecessor : source; 7017 mChangeTypes |= changeType; 7018 return; 7019 } 7020 mSource = source; 7021 mChangeTypes = changeType; 7022 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 7023 final long minEventIntevalMillis = 7024 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 7025 if (timeSinceLastMillis >= minEventIntevalMillis) { 7026 mSource.removeCallbacks(this); 7027 run(); 7028 } else { 7029 mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 7030 } 7031 } 7032 } 7033} 7034