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