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