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