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