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