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