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