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