ViewRootImpl.java revision 49d8fa473970265a182549cc1673719e5101320e
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 final int restoreCount = layerCanvas.save(); 1518 1519 int yoff; 1520 final boolean scrolling = mScroller != null 1521 && mScroller.computeScrollOffset(); 1522 if (scrolling) { 1523 yoff = mScroller.getCurrY(); 1524 mScroller.abortAnimation(); 1525 } else { 1526 yoff = mScrollY; 1527 } 1528 1529 layerCanvas.translate(0, -yoff); 1530 if (mTranslator != null) { 1531 mTranslator.translateCanvas(layerCanvas); 1532 } 1533 1534 RenderNode renderNode = mView.mRenderNode; 1535 if (renderNode != null && renderNode.isValid()) { 1536 layerCanvas.drawDisplayList(renderNode, null, 1537 RenderNode.FLAG_CLIP_CHILDREN); 1538 } else { 1539 mView.draw(layerCanvas); 1540 } 1541 1542 drawAccessibilityFocusedDrawableIfNeeded(layerCanvas); 1543 1544 mResizeBufferStartTime = SystemClock.uptimeMillis(); 1545 mResizeBufferDuration = mView.getResources().getInteger( 1546 com.android.internal.R.integer.config_mediumAnimTime); 1547 1548 layerCanvas.restoreToCount(restoreCount); 1549 layerRenderNode.end(layerCanvas); 1550 layerRenderNode.setCaching(true); 1551 layerRenderNode.setLeftTopRightBottom(0, 0, mWidth, mHeight); 1552 mTempRect.set(0, 0, mWidth, mHeight); 1553 mResizeBuffer.endRecording(mTempRect); 1554 mAttachInfo.mHardwareRenderer.flushLayerUpdates(); 1555 } 1556 mAttachInfo.mContentInsets.set(mPendingContentInsets); 1557 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: " 1558 + mAttachInfo.mContentInsets); 1559 } 1560 if (overscanInsetsChanged) { 1561 mAttachInfo.mOverscanInsets.set(mPendingOverscanInsets); 1562 if (DEBUG_LAYOUT) Log.v(TAG, "Overscan insets changing to: " 1563 + mAttachInfo.mOverscanInsets); 1564 // Need to relayout with content insets. 1565 contentInsetsChanged = true; 1566 } 1567 if (contentInsetsChanged || mLastSystemUiVisibility != 1568 mAttachInfo.mSystemUiVisibility || mFitSystemWindowsRequested 1569 || mLastOverscanRequested != mAttachInfo.mOverscanRequested) { 1570 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1571 mLastOverscanRequested = mAttachInfo.mOverscanRequested; 1572 mFitSystemWindowsRequested = false; 1573 dispatchApplyInsets(host); 1574 } 1575 if (visibleInsetsChanged) { 1576 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1577 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1578 + mAttachInfo.mVisibleInsets); 1579 } 1580 1581 if (!hadSurface) { 1582 if (mSurface.isValid()) { 1583 // If we are creating a new surface, then we need to 1584 // completely redraw it. Also, when we get to the 1585 // point of drawing it we will hold off and schedule 1586 // a new traversal instead. This is so we can tell the 1587 // window manager about all of the windows being displayed 1588 // before actually drawing them, so it can display then 1589 // all at once. 1590 newSurface = true; 1591 mFullRedrawNeeded = true; 1592 mPreviousTransparentRegion.setEmpty(); 1593 1594 if (mAttachInfo.mHardwareRenderer != null) { 1595 try { 1596 hwInitialized = mAttachInfo.mHardwareRenderer.initialize( 1597 mSurface); 1598 } catch (OutOfResourcesException e) { 1599 handleOutOfResourcesException(e); 1600 return; 1601 } 1602 } 1603 } 1604 } else if (!mSurface.isValid()) { 1605 // If the surface has been removed, then reset the scroll 1606 // positions. 1607 if (mLastScrolledFocus != null) { 1608 mLastScrolledFocus.clear(); 1609 } 1610 mScrollY = mCurScrollY = 0; 1611 if (mScroller != null) { 1612 mScroller.abortAnimation(); 1613 } 1614 disposeResizeBuffer(); 1615 // Our surface is gone 1616 if (mAttachInfo.mHardwareRenderer != null && 1617 mAttachInfo.mHardwareRenderer.isEnabled()) { 1618 mAttachInfo.mHardwareRenderer.destroy(true); 1619 } 1620 } else if (surfaceGenerationId != mSurface.getGenerationId() && 1621 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) { 1622 mFullRedrawNeeded = true; 1623 try { 1624 mAttachInfo.mHardwareRenderer.updateSurface(mSurface); 1625 } catch (OutOfResourcesException e) { 1626 handleOutOfResourcesException(e); 1627 return; 1628 } 1629 } 1630 } catch (RemoteException e) { 1631 } 1632 1633 if (DEBUG_ORIENTATION) Log.v( 1634 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface); 1635 1636 attachInfo.mWindowLeft = frame.left; 1637 attachInfo.mWindowTop = frame.top; 1638 1639 // !!FIXME!! This next section handles the case where we did not get the 1640 // window size we asked for. We should avoid this by getting a maximum size from 1641 // the window session beforehand. 1642 if (mWidth != frame.width() || mHeight != frame.height()) { 1643 mWidth = frame.width(); 1644 mHeight = frame.height(); 1645 } 1646 1647 if (mSurfaceHolder != null) { 1648 // The app owns the surface; tell it about what is going on. 1649 if (mSurface.isValid()) { 1650 // XXX .copyFrom() doesn't work! 1651 //mSurfaceHolder.mSurface.copyFrom(mSurface); 1652 mSurfaceHolder.mSurface = mSurface; 1653 } 1654 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight); 1655 mSurfaceHolder.mSurfaceLock.unlock(); 1656 if (mSurface.isValid()) { 1657 if (!hadSurface) { 1658 mSurfaceHolder.ungetCallbacks(); 1659 1660 mIsCreating = true; 1661 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder); 1662 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1663 if (callbacks != null) { 1664 for (SurfaceHolder.Callback c : callbacks) { 1665 c.surfaceCreated(mSurfaceHolder); 1666 } 1667 } 1668 surfaceChanged = true; 1669 } 1670 if (surfaceChanged) { 1671 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder, 1672 lp.format, mWidth, mHeight); 1673 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1674 if (callbacks != null) { 1675 for (SurfaceHolder.Callback c : callbacks) { 1676 c.surfaceChanged(mSurfaceHolder, lp.format, 1677 mWidth, mHeight); 1678 } 1679 } 1680 } 1681 mIsCreating = false; 1682 } else if (hadSurface) { 1683 mSurfaceHolder.ungetCallbacks(); 1684 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1685 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder); 1686 if (callbacks != null) { 1687 for (SurfaceHolder.Callback c : callbacks) { 1688 c.surfaceDestroyed(mSurfaceHolder); 1689 } 1690 } 1691 mSurfaceHolder.mSurfaceLock.lock(); 1692 try { 1693 mSurfaceHolder.mSurface = new Surface(); 1694 } finally { 1695 mSurfaceHolder.mSurfaceLock.unlock(); 1696 } 1697 } 1698 } 1699 1700 if (mAttachInfo.mHardwareRenderer != null && 1701 mAttachInfo.mHardwareRenderer.isEnabled()) { 1702 if (hwInitialized || 1703 mWidth != mAttachInfo.mHardwareRenderer.getWidth() || 1704 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) { 1705 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight); 1706 if (!hwInitialized) { 1707 mAttachInfo.mHardwareRenderer.invalidate(mSurface); 1708 mFullRedrawNeeded = true; 1709 } 1710 } 1711 } 1712 1713 if (!mStopped) { 1714 boolean focusChangedDueToTouchMode = ensureTouchModeLocally( 1715 (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0); 1716 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth() 1717 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) { 1718 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); 1719 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height); 1720 1721 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth=" 1722 + mWidth + " measuredWidth=" + host.getMeasuredWidth() 1723 + " mHeight=" + mHeight 1724 + " measuredHeight=" + host.getMeasuredHeight() 1725 + " coveredInsetsChanged=" + contentInsetsChanged); 1726 1727 // Ask host how big it wants to be 1728 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1729 1730 // Implementation of weights from WindowManager.LayoutParams 1731 // We just grow the dimensions as needed and re-measure if 1732 // needs be 1733 int width = host.getMeasuredWidth(); 1734 int height = host.getMeasuredHeight(); 1735 boolean measureAgain = false; 1736 1737 if (lp.horizontalWeight > 0.0f) { 1738 width += (int) ((mWidth - width) * lp.horizontalWeight); 1739 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, 1740 MeasureSpec.EXACTLY); 1741 measureAgain = true; 1742 } 1743 if (lp.verticalWeight > 0.0f) { 1744 height += (int) ((mHeight - height) * lp.verticalWeight); 1745 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, 1746 MeasureSpec.EXACTLY); 1747 measureAgain = true; 1748 } 1749 1750 if (measureAgain) { 1751 if (DEBUG_LAYOUT) Log.v(TAG, 1752 "And hey let's measure once more: width=" + width 1753 + " height=" + height); 1754 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1755 } 1756 1757 layoutRequested = true; 1758 } 1759 } 1760 } else { 1761 // Not the first pass and no window/insets/visibility change but the window 1762 // may have moved and we need check that and if so to update the left and right 1763 // in the attach info. We translate only the window frame since on window move 1764 // the window manager tells us only for the new frame but the insets are the 1765 // same and we do not want to translate them more than once. 1766 1767 // TODO: Well, we are checking whether the frame has changed similarly 1768 // to how this is done for the insets. This is however incorrect since 1769 // the insets and the frame are translated. For example, the old frame 1770 // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new 1771 // reported frame is (2, 2 - 2, 2) which implies no change but this is not 1772 // true since we are comparing a not translated value to a translated one. 1773 // This scenario is rare but we may want to fix that. 1774 1775 final boolean windowMoved = (attachInfo.mWindowLeft != frame.left 1776 || attachInfo.mWindowTop != frame.top); 1777 if (windowMoved) { 1778 if (mTranslator != null) { 1779 mTranslator.translateRectInScreenToAppWinFrame(frame); 1780 } 1781 attachInfo.mWindowLeft = frame.left; 1782 attachInfo.mWindowTop = frame.top; 1783 } 1784 } 1785 1786 final boolean didLayout = layoutRequested && !mStopped; 1787 boolean triggerGlobalLayoutListener = didLayout 1788 || attachInfo.mRecomputeGlobalAttributes; 1789 if (didLayout) { 1790 performLayout(lp, desiredWindowWidth, desiredWindowHeight); 1791 1792 // By this point all views have been sized and positioned 1793 // We can compute the transparent area 1794 1795 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 1796 // start out transparent 1797 // TODO: AVOID THAT CALL BY CACHING THE RESULT? 1798 host.getLocationInWindow(mTmpLocation); 1799 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1], 1800 mTmpLocation[0] + host.mRight - host.mLeft, 1801 mTmpLocation[1] + host.mBottom - host.mTop); 1802 1803 host.gatherTransparentRegion(mTransparentRegion); 1804 if (mTranslator != null) { 1805 mTranslator.translateRegionInWindowToScreen(mTransparentRegion); 1806 } 1807 1808 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) { 1809 mPreviousTransparentRegion.set(mTransparentRegion); 1810 mFullRedrawNeeded = true; 1811 // reconfigure window manager 1812 try { 1813 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion); 1814 } catch (RemoteException e) { 1815 } 1816 } 1817 } 1818 1819 if (DBG) { 1820 System.out.println("======================================"); 1821 System.out.println("performTraversals -- after setFrame"); 1822 host.debug(); 1823 } 1824 } 1825 1826 if (triggerGlobalLayoutListener) { 1827 attachInfo.mRecomputeGlobalAttributes = false; 1828 attachInfo.mTreeObserver.dispatchOnGlobalLayout(); 1829 } 1830 1831 if (computesInternalInsets) { 1832 // Clear the original insets. 1833 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets; 1834 insets.reset(); 1835 1836 // Compute new insets in place. 1837 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets); 1838 attachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty(); 1839 1840 // Tell the window manager. 1841 if (insetsPending || !mLastGivenInsets.equals(insets)) { 1842 mLastGivenInsets.set(insets); 1843 1844 // Translate insets to screen coordinates if needed. 1845 final Rect contentInsets; 1846 final Rect visibleInsets; 1847 final Region touchableRegion; 1848 if (mTranslator != null) { 1849 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets); 1850 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets); 1851 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion); 1852 } else { 1853 contentInsets = insets.contentInsets; 1854 visibleInsets = insets.visibleInsets; 1855 touchableRegion = insets.touchableRegion; 1856 } 1857 1858 try { 1859 mWindowSession.setInsets(mWindow, insets.mTouchableInsets, 1860 contentInsets, visibleInsets, touchableRegion); 1861 } catch (RemoteException e) { 1862 } 1863 } 1864 } 1865 1866 boolean skipDraw = false; 1867 1868 if (mFirst) { 1869 // handle first focus request 1870 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()=" 1871 + mView.hasFocus()); 1872 if (mView != null) { 1873 if (!mView.hasFocus()) { 1874 mView.requestFocus(View.FOCUS_FORWARD); 1875 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view=" 1876 + mView.findFocus()); 1877 } else { 1878 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view=" 1879 + mView.findFocus()); 1880 } 1881 } 1882 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) { 1883 // The first time we relayout the window, if the system is 1884 // doing window animations, we want to hold of on any future 1885 // draws until the animation is done. 1886 mWindowsAnimating = true; 1887 } 1888 } else if (mWindowsAnimating) { 1889 skipDraw = true; 1890 } 1891 1892 mFirst = false; 1893 mWillDrawSoon = false; 1894 mNewSurfaceNeeded = false; 1895 mViewVisibility = viewVisibility; 1896 1897 if (mAttachInfo.mHasWindowFocus && !isInLocalFocusMode()) { 1898 final boolean imTarget = WindowManager.LayoutParams 1899 .mayUseInputMethod(mWindowAttributes.flags); 1900 if (imTarget != mLastWasImTarget) { 1901 mLastWasImTarget = imTarget; 1902 InputMethodManager imm = InputMethodManager.peekInstance(); 1903 if (imm != null && imTarget) { 1904 imm.startGettingWindowFocus(mView); 1905 imm.onWindowFocus(mView, mView.findFocus(), 1906 mWindowAttributes.softInputMode, 1907 !mHasHadWindowFocus, mWindowAttributes.flags); 1908 } 1909 } 1910 } 1911 1912 // Remember if we must report the next draw. 1913 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 1914 mReportNextDraw = true; 1915 } 1916 1917 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() || 1918 viewVisibility != View.VISIBLE; 1919 1920 if (!cancelDraw && !newSurface) { 1921 if (!skipDraw || mReportNextDraw) { 1922 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1923 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1924 mPendingTransitions.get(i).startChangingAnimations(); 1925 } 1926 mPendingTransitions.clear(); 1927 } 1928 1929 performDraw(); 1930 } 1931 } else { 1932 if (viewVisibility == View.VISIBLE) { 1933 // Try again 1934 scheduleTraversals(); 1935 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1936 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1937 mPendingTransitions.get(i).endChangingAnimations(); 1938 } 1939 mPendingTransitions.clear(); 1940 } 1941 } 1942 1943 mIsInTraversal = false; 1944 } 1945 1946 private void handleOutOfResourcesException(Surface.OutOfResourcesException e) { 1947 Log.e(TAG, "OutOfResourcesException initializing HW surface", e); 1948 try { 1949 if (!mWindowSession.outOfMemory(mWindow) && 1950 Process.myUid() != Process.SYSTEM_UID) { 1951 Slog.w(TAG, "No processes killed for memory; killing self"); 1952 Process.killProcess(Process.myPid()); 1953 } 1954 } catch (RemoteException ex) { 1955 } 1956 mLayoutRequested = true; // ask wm for a new surface next time. 1957 } 1958 1959 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) { 1960 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure"); 1961 try { 1962 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1963 } finally { 1964 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 1965 } 1966 } 1967 1968 /** 1969 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy 1970 * is currently undergoing a layout pass. 1971 * 1972 * @return whether the view hierarchy is currently undergoing a layout pass 1973 */ 1974 boolean isInLayout() { 1975 return mInLayout; 1976 } 1977 1978 /** 1979 * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently 1980 * undergoing a layout pass. requestLayout() should not generally be called during layout, 1981 * unless the container hierarchy knows what it is doing (i.e., it is fine as long as 1982 * all children in that container hierarchy are measured and laid out at the end of the layout 1983 * pass for that container). If requestLayout() is called anyway, we handle it correctly 1984 * by registering all requesters during a frame as it proceeds. At the end of the frame, 1985 * we check all of those views to see if any still have pending layout requests, which 1986 * indicates that they were not correctly handled by their container hierarchy. If that is 1987 * the case, we clear all such flags in the tree, to remove the buggy flag state that leads 1988 * to blank containers, and force a second request/measure/layout pass in this frame. If 1989 * more requestLayout() calls are received during that second layout pass, we post those 1990 * requests to the next frame to avoid possible infinite loops. 1991 * 1992 * <p>The return value from this method indicates whether the request should proceed 1993 * (if it is a request during the first layout pass) or should be skipped and posted to the 1994 * next frame (if it is a request during the second layout pass).</p> 1995 * 1996 * @param view the view that requested the layout. 1997 * 1998 * @return true if request should proceed, false otherwise. 1999 */ 2000 boolean requestLayoutDuringLayout(final View view) { 2001 if (view.mParent == null || view.mAttachInfo == null) { 2002 // Would not normally trigger another layout, so just let it pass through as usual 2003 return true; 2004 } 2005 if (!mLayoutRequesters.contains(view)) { 2006 mLayoutRequesters.add(view); 2007 } 2008 if (!mHandlingLayoutInLayoutRequest) { 2009 // Let the request proceed normally; it will be processed in a second layout pass 2010 // if necessary 2011 return true; 2012 } else { 2013 // Don't let the request proceed during the second layout pass. 2014 // It will post to the next frame instead. 2015 return false; 2016 } 2017 } 2018 2019 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth, 2020 int desiredWindowHeight) { 2021 mLayoutRequested = false; 2022 mScrollMayChange = true; 2023 mInLayout = true; 2024 2025 final View host = mView; 2026 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) { 2027 Log.v(TAG, "Laying out " + host + " to (" + 2028 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")"); 2029 } 2030 2031 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout"); 2032 try { 2033 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 2034 2035 mInLayout = false; 2036 int numViewsRequestingLayout = mLayoutRequesters.size(); 2037 if (numViewsRequestingLayout > 0) { 2038 // requestLayout() was called during layout. 2039 // If no layout-request flags are set on the requesting views, there is no problem. 2040 // If some requests are still pending, then we need to clear those flags and do 2041 // a full request/measure/layout pass to handle this situation. 2042 ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, 2043 false); 2044 if (validLayoutRequesters != null) { 2045 // Set this flag to indicate that any further requests are happening during 2046 // the second pass, which may result in posting those requests to the next 2047 // frame instead 2048 mHandlingLayoutInLayoutRequest = true; 2049 2050 // Process fresh layout requests, then measure and layout 2051 int numValidRequests = validLayoutRequesters.size(); 2052 for (int i = 0; i < numValidRequests; ++i) { 2053 final View view = validLayoutRequesters.get(i); 2054 Log.w("View", "requestLayout() improperly called by " + view + 2055 " during layout: running second layout pass"); 2056 view.requestLayout(); 2057 } 2058 measureHierarchy(host, lp, mView.getContext().getResources(), 2059 desiredWindowWidth, desiredWindowHeight); 2060 mInLayout = true; 2061 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 2062 2063 mHandlingLayoutInLayoutRequest = false; 2064 2065 // Check the valid requests again, this time without checking/clearing the 2066 // layout flags, since requests happening during the second pass get noop'd 2067 validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true); 2068 if (validLayoutRequesters != null) { 2069 final ArrayList<View> finalRequesters = validLayoutRequesters; 2070 // Post second-pass requests to the next frame 2071 getRunQueue().post(new Runnable() { 2072 @Override 2073 public void run() { 2074 int numValidRequests = finalRequesters.size(); 2075 for (int i = 0; i < numValidRequests; ++i) { 2076 final View view = finalRequesters.get(i); 2077 Log.w("View", "requestLayout() improperly called by " + view + 2078 " during second layout pass: posting in next frame"); 2079 view.requestLayout(); 2080 } 2081 } 2082 }); 2083 } 2084 } 2085 2086 } 2087 } finally { 2088 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2089 } 2090 mInLayout = false; 2091 } 2092 2093 /** 2094 * This method is called during layout when there have been calls to requestLayout() during 2095 * layout. It walks through the list of views that requested layout to determine which ones 2096 * still need it, based on visibility in the hierarchy and whether they have already been 2097 * handled (as is usually the case with ListView children). 2098 * 2099 * @param layoutRequesters The list of views that requested layout during layout 2100 * @param secondLayoutRequests Whether the requests were issued during the second layout pass. 2101 * If so, the FORCE_LAYOUT flag was not set on requesters. 2102 * @return A list of the actual views that still need to be laid out. 2103 */ 2104 private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters, 2105 boolean secondLayoutRequests) { 2106 2107 int numViewsRequestingLayout = layoutRequesters.size(); 2108 ArrayList<View> validLayoutRequesters = null; 2109 for (int i = 0; i < numViewsRequestingLayout; ++i) { 2110 View view = layoutRequesters.get(i); 2111 if (view != null && view.mAttachInfo != null && view.mParent != null && 2112 (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == 2113 View.PFLAG_FORCE_LAYOUT)) { 2114 boolean gone = false; 2115 View parent = view; 2116 // Only trigger new requests for views in a non-GONE hierarchy 2117 while (parent != null) { 2118 if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) { 2119 gone = true; 2120 break; 2121 } 2122 if (parent.mParent instanceof View) { 2123 parent = (View) parent.mParent; 2124 } else { 2125 parent = null; 2126 } 2127 } 2128 if (!gone) { 2129 if (validLayoutRequesters == null) { 2130 validLayoutRequesters = new ArrayList<View>(); 2131 } 2132 validLayoutRequesters.add(view); 2133 } 2134 } 2135 } 2136 if (!secondLayoutRequests) { 2137 // If we're checking the layout flags, then we need to clean them up also 2138 for (int i = 0; i < numViewsRequestingLayout; ++i) { 2139 View view = layoutRequesters.get(i); 2140 while (view != null && 2141 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) { 2142 view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT; 2143 if (view.mParent instanceof View) { 2144 view = (View) view.mParent; 2145 } else { 2146 view = null; 2147 } 2148 } 2149 } 2150 } 2151 layoutRequesters.clear(); 2152 return validLayoutRequesters; 2153 } 2154 2155 @Override 2156 public void requestTransparentRegion(View child) { 2157 // the test below should not fail unless someone is messing with us 2158 checkThread(); 2159 if (mView == child) { 2160 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS; 2161 // Need to make sure we re-evaluate the window attributes next 2162 // time around, to ensure the window has the correct format. 2163 mWindowAttributesChanged = true; 2164 mWindowAttributesChangesFlag = 0; 2165 requestLayout(); 2166 } 2167 } 2168 2169 /** 2170 * Figures out the measure spec for the root view in a window based on it's 2171 * layout params. 2172 * 2173 * @param windowSize 2174 * The available width or height of the window 2175 * 2176 * @param rootDimension 2177 * The layout params for one dimension (width or height) of the 2178 * window. 2179 * 2180 * @return The measure spec to use to measure the root view. 2181 */ 2182 private static int getRootMeasureSpec(int windowSize, int rootDimension) { 2183 int measureSpec; 2184 switch (rootDimension) { 2185 2186 case ViewGroup.LayoutParams.MATCH_PARENT: 2187 // Window can't resize. Force root view to be windowSize. 2188 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); 2189 break; 2190 case ViewGroup.LayoutParams.WRAP_CONTENT: 2191 // Window can resize. Set max size for root view. 2192 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST); 2193 break; 2194 default: 2195 // Window wants to be an exact size. Force root view to be that size. 2196 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY); 2197 break; 2198 } 2199 return measureSpec; 2200 } 2201 2202 int mHardwareYOffset; 2203 int mResizeAlpha; 2204 final Paint mResizePaint = new Paint(); 2205 2206 @Override 2207 public void onHardwarePreDraw(HardwareCanvas canvas) { 2208 canvas.translate(0, -mHardwareYOffset); 2209 } 2210 2211 @Override 2212 public void onHardwarePostDraw(HardwareCanvas canvas) { 2213 if (mResizeBuffer != null) { 2214 mResizePaint.setAlpha(mResizeAlpha); 2215 canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint); 2216 } 2217 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2218 } 2219 2220 /** 2221 * @hide 2222 */ 2223 void outputDisplayList(View view) { 2224 RenderNode renderNode = view.getDisplayList(); 2225 if (renderNode != null) { 2226 renderNode.output(); 2227 } 2228 } 2229 2230 /** 2231 * @see #PROPERTY_PROFILE_RENDERING 2232 */ 2233 private void profileRendering(boolean enabled) { 2234 if (mProfileRendering) { 2235 mRenderProfilingEnabled = enabled; 2236 2237 if (mRenderProfiler != null) { 2238 mChoreographer.removeFrameCallback(mRenderProfiler); 2239 } 2240 if (mRenderProfilingEnabled) { 2241 if (mRenderProfiler == null) { 2242 mRenderProfiler = new Choreographer.FrameCallback() { 2243 @Override 2244 public void doFrame(long frameTimeNanos) { 2245 mDirty.set(0, 0, mWidth, mHeight); 2246 scheduleTraversals(); 2247 if (mRenderProfilingEnabled) { 2248 mChoreographer.postFrameCallback(mRenderProfiler); 2249 } 2250 } 2251 }; 2252 } 2253 mChoreographer.postFrameCallback(mRenderProfiler); 2254 } else { 2255 mRenderProfiler = null; 2256 } 2257 } 2258 } 2259 2260 /** 2261 * Called from draw() when DEBUG_FPS is enabled 2262 */ 2263 private void trackFPS() { 2264 // Tracks frames per second drawn. First value in a series of draws may be bogus 2265 // because it down not account for the intervening idle time 2266 long nowTime = System.currentTimeMillis(); 2267 if (mFpsStartTime < 0) { 2268 mFpsStartTime = mFpsPrevTime = nowTime; 2269 mFpsNumFrames = 0; 2270 } else { 2271 ++mFpsNumFrames; 2272 String thisHash = Integer.toHexString(System.identityHashCode(this)); 2273 long frameTime = nowTime - mFpsPrevTime; 2274 long totalTime = nowTime - mFpsStartTime; 2275 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime); 2276 mFpsPrevTime = nowTime; 2277 if (totalTime > 1000) { 2278 float fps = (float) mFpsNumFrames * 1000 / totalTime; 2279 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps); 2280 mFpsStartTime = nowTime; 2281 mFpsNumFrames = 0; 2282 } 2283 } 2284 } 2285 2286 private void performDraw() { 2287 if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) { 2288 return; 2289 } 2290 2291 final boolean fullRedrawNeeded = mFullRedrawNeeded; 2292 mFullRedrawNeeded = false; 2293 2294 mIsDrawing = true; 2295 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw"); 2296 try { 2297 draw(fullRedrawNeeded); 2298 } finally { 2299 mIsDrawing = false; 2300 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2301 } 2302 2303 if (mReportNextDraw) { 2304 mReportNextDraw = false; 2305 if (mAttachInfo.mHardwareRenderer != null) { 2306 mAttachInfo.mHardwareRenderer.fence(); 2307 } 2308 2309 if (LOCAL_LOGV) { 2310 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle()); 2311 } 2312 if (mSurfaceHolder != null && mSurface.isValid()) { 2313 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder); 2314 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 2315 if (callbacks != null) { 2316 for (SurfaceHolder.Callback c : callbacks) { 2317 if (c instanceof SurfaceHolder.Callback2) { 2318 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 2319 mSurfaceHolder); 2320 } 2321 } 2322 } 2323 } 2324 try { 2325 mWindowSession.finishDrawing(mWindow); 2326 } catch (RemoteException e) { 2327 } 2328 } 2329 } 2330 2331 private void draw(boolean fullRedrawNeeded) { 2332 Surface surface = mSurface; 2333 if (!surface.isValid()) { 2334 return; 2335 } 2336 2337 if (DEBUG_FPS) { 2338 trackFPS(); 2339 } 2340 2341 if (!sFirstDrawComplete) { 2342 synchronized (sFirstDrawHandlers) { 2343 sFirstDrawComplete = true; 2344 final int count = sFirstDrawHandlers.size(); 2345 for (int i = 0; i< count; i++) { 2346 mHandler.post(sFirstDrawHandlers.get(i)); 2347 } 2348 } 2349 } 2350 2351 scrollToRectOrFocus(null, false); 2352 2353 final AttachInfo attachInfo = mAttachInfo; 2354 if (attachInfo.mViewScrollChanged) { 2355 attachInfo.mViewScrollChanged = false; 2356 attachInfo.mTreeObserver.dispatchOnScrollChanged(); 2357 } 2358 2359 int yoff; 2360 boolean animating = mScroller != null && mScroller.computeScrollOffset(); 2361 if (animating) { 2362 yoff = mScroller.getCurrY(); 2363 } else { 2364 yoff = mScrollY; 2365 } 2366 if (mCurScrollY != yoff) { 2367 mCurScrollY = yoff; 2368 fullRedrawNeeded = true; 2369 } 2370 2371 final float appScale = attachInfo.mApplicationScale; 2372 final boolean scalingRequired = attachInfo.mScalingRequired; 2373 2374 int resizeAlpha = 0; 2375 if (mResizeBuffer != null) { 2376 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime; 2377 if (deltaTime < mResizeBufferDuration) { 2378 float amt = deltaTime/(float) mResizeBufferDuration; 2379 amt = mResizeInterpolator.getInterpolation(amt); 2380 animating = true; 2381 resizeAlpha = 255 - (int)(amt*255); 2382 } else { 2383 disposeResizeBuffer(); 2384 } 2385 } 2386 2387 final Rect dirty = mDirty; 2388 if (mSurfaceHolder != null) { 2389 // The app owns the surface, we won't draw. 2390 dirty.setEmpty(); 2391 if (animating) { 2392 if (mScroller != null) { 2393 mScroller.abortAnimation(); 2394 } 2395 disposeResizeBuffer(); 2396 } 2397 return; 2398 } 2399 2400 if (fullRedrawNeeded) { 2401 attachInfo.mIgnoreDirtyState = true; 2402 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 2403 } 2404 2405 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2406 Log.v(TAG, "Draw " + mView + "/" 2407 + mWindowAttributes.getTitle() 2408 + ": dirty={" + dirty.left + "," + dirty.top 2409 + "," + dirty.right + "," + dirty.bottom + "} surface=" 2410 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" + 2411 appScale + ", width=" + mWidth + ", height=" + mHeight); 2412 } 2413 2414 attachInfo.mTreeObserver.dispatchOnDraw(); 2415 2416 if (!dirty.isEmpty() || mIsAnimating) { 2417 if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) { 2418 // Draw with hardware renderer. 2419 mIsAnimating = false; 2420 mHardwareYOffset = yoff; 2421 mResizeAlpha = resizeAlpha; 2422 2423 mCurrentDirty.set(dirty); 2424 dirty.setEmpty(); 2425 2426 mBlockResizeBuffer = false; 2427 attachInfo.mHardwareRenderer.draw(mView, attachInfo, this, 2428 animating ? null : mCurrentDirty); 2429 } else { 2430 // If we get here with a disabled & requested hardware renderer, something went 2431 // wrong (an invalidate posted right before we destroyed the hardware surface 2432 // for instance) so we should just bail out. Locking the surface with software 2433 // rendering at this point would lock it forever and prevent hardware renderer 2434 // from doing its job when it comes back. 2435 // Before we request a new frame we must however attempt to reinitiliaze the 2436 // hardware renderer if it's in requested state. This would happen after an 2437 // eglTerminate() for instance. 2438 if (attachInfo.mHardwareRenderer != null && 2439 !attachInfo.mHardwareRenderer.isEnabled() && 2440 attachInfo.mHardwareRenderer.isRequested()) { 2441 2442 try { 2443 attachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2444 mSurface); 2445 } catch (OutOfResourcesException e) { 2446 handleOutOfResourcesException(e); 2447 return; 2448 } 2449 2450 mFullRedrawNeeded = true; 2451 scheduleTraversals(); 2452 return; 2453 } 2454 2455 if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) { 2456 return; 2457 } 2458 } 2459 } 2460 2461 if (animating) { 2462 mFullRedrawNeeded = true; 2463 scheduleTraversals(); 2464 } 2465 } 2466 2467 /** 2468 * @return true if drawing was succesfull, false if an error occurred 2469 */ 2470 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff, 2471 boolean scalingRequired, Rect dirty) { 2472 2473 // Draw with software renderer. 2474 Canvas canvas; 2475 try { 2476 int left = dirty.left; 2477 int top = dirty.top; 2478 int right = dirty.right; 2479 int bottom = dirty.bottom; 2480 2481 canvas = mSurface.lockCanvas(dirty); 2482 2483 // The dirty rectangle can be modified by Surface.lockCanvas() 2484 //noinspection ConstantConditions 2485 if (left != dirty.left || top != dirty.top || right != dirty.right || 2486 bottom != dirty.bottom) { 2487 attachInfo.mIgnoreDirtyState = true; 2488 } 2489 2490 // TODO: Do this in native 2491 canvas.setDensity(mDensity); 2492 } catch (Surface.OutOfResourcesException e) { 2493 handleOutOfResourcesException(e); 2494 return false; 2495 } catch (IllegalArgumentException e) { 2496 Log.e(TAG, "Could not lock surface", e); 2497 // Don't assume this is due to out of memory, it could be 2498 // something else, and if it is something else then we could 2499 // kill stuff (or ourself) for no reason. 2500 mLayoutRequested = true; // ask wm for a new surface next time. 2501 return false; 2502 } 2503 2504 try { 2505 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2506 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2507 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2508 //canvas.drawARGB(255, 255, 0, 0); 2509 } 2510 2511 // If this bitmap's format includes an alpha channel, we 2512 // need to clear it before drawing so that the child will 2513 // properly re-composite its drawing on a transparent 2514 // background. This automatically respects the clip/dirty region 2515 // or 2516 // If we are applying an offset, we need to clear the area 2517 // where the offset doesn't appear to avoid having garbage 2518 // left in the blank areas. 2519 if (!canvas.isOpaque() || yoff != 0) { 2520 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2521 } 2522 2523 dirty.setEmpty(); 2524 mIsAnimating = false; 2525 attachInfo.mDrawingTime = SystemClock.uptimeMillis(); 2526 mView.mPrivateFlags |= View.PFLAG_DRAWN; 2527 2528 if (DEBUG_DRAW) { 2529 Context cxt = mView.getContext(); 2530 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2531 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2532 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2533 } 2534 try { 2535 canvas.translate(0, -yoff); 2536 if (mTranslator != null) { 2537 mTranslator.translateCanvas(canvas); 2538 } 2539 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0); 2540 attachInfo.mSetIgnoreDirtyState = false; 2541 2542 mView.draw(canvas); 2543 2544 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2545 } finally { 2546 if (!attachInfo.mSetIgnoreDirtyState) { 2547 // Only clear the flag if it was not set during the mView.draw() call 2548 attachInfo.mIgnoreDirtyState = false; 2549 } 2550 } 2551 } finally { 2552 try { 2553 surface.unlockCanvasAndPost(canvas); 2554 } catch (IllegalArgumentException e) { 2555 Log.e(TAG, "Could not unlock surface", e); 2556 mLayoutRequested = true; // ask wm for a new surface next time. 2557 //noinspection ReturnInsideFinallyBlock 2558 return false; 2559 } 2560 2561 if (LOCAL_LOGV) { 2562 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2563 } 2564 } 2565 return true; 2566 } 2567 2568 /** 2569 * We want to draw a highlight around the current accessibility focused. 2570 * Since adding a style for all possible view is not a viable option we 2571 * have this specialized drawing method. 2572 * 2573 * Note: We are doing this here to be able to draw the highlight for 2574 * virtual views in addition to real ones. 2575 * 2576 * @param canvas The canvas on which to draw. 2577 */ 2578 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) { 2579 if (!mAttachInfo.mHasWindowFocus) { 2580 return; 2581 } 2582 2583 final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext); 2584 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 2585 return; 2586 } 2587 2588 final View host = mAccessibilityFocusedHost; 2589 if (host == null || host.mAttachInfo == null) { 2590 return; 2591 } 2592 2593 final Drawable drawable = getAccessibilityFocusedDrawable(); 2594 if (drawable == null) { 2595 return; 2596 } 2597 2598 final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider(); 2599 final Rect bounds = mView.mAttachInfo.mTmpInvalRect; 2600 if (provider == null) { 2601 host.getBoundsOnScreen(bounds); 2602 } else if (mAccessibilityFocusedVirtualView != null) { 2603 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds); 2604 } else { 2605 return; 2606 } 2607 2608 bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop); 2609 bounds.intersect(0, 0, mAttachInfo.mViewRootImpl.mWidth, mAttachInfo.mViewRootImpl.mHeight); 2610 drawable.setBounds(bounds); 2611 drawable.draw(canvas); 2612 } 2613 2614 private Drawable getAccessibilityFocusedDrawable() { 2615 if (mAttachInfo != null) { 2616 // Lazily load the accessibility focus drawable. 2617 if (mAttachInfo.mAccessibilityFocusDrawable == null) { 2618 TypedValue value = new TypedValue(); 2619 final boolean resolved = mView.mContext.getTheme().resolveAttribute( 2620 R.attr.accessibilityFocusedDrawable, value, true); 2621 if (resolved) { 2622 mAttachInfo.mAccessibilityFocusDrawable = 2623 mView.mContext.getDrawable(value.resourceId); 2624 } 2625 } 2626 return mAttachInfo.mAccessibilityFocusDrawable; 2627 } 2628 return null; 2629 } 2630 2631 /** 2632 * @hide 2633 */ 2634 public void setDrawDuringWindowsAnimating(boolean value) { 2635 mDrawDuringWindowsAnimating = value; 2636 if (value) { 2637 handleDispatchDoneAnimating(); 2638 } 2639 } 2640 2641 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2642 final View.AttachInfo attachInfo = mAttachInfo; 2643 final Rect ci = attachInfo.mContentInsets; 2644 final Rect vi = attachInfo.mVisibleInsets; 2645 int scrollY = 0; 2646 boolean handled = false; 2647 2648 if (vi.left > ci.left || vi.top > ci.top 2649 || vi.right > ci.right || vi.bottom > ci.bottom) { 2650 // We'll assume that we aren't going to change the scroll 2651 // offset, since we want to avoid that unless it is actually 2652 // going to make the focus visible... otherwise we scroll 2653 // all over the place. 2654 scrollY = mScrollY; 2655 // We can be called for two different situations: during a draw, 2656 // to update the scroll position if the focus has changed (in which 2657 // case 'rectangle' is null), or in response to a 2658 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2659 // is non-null and we just want to scroll to whatever that 2660 // rectangle is). 2661 final View focus = mView.findFocus(); 2662 if (focus == null) { 2663 return false; 2664 } 2665 View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null; 2666 if (focus != lastScrolledFocus) { 2667 // If the focus has changed, then ignore any requests to scroll 2668 // to a rectangle; first we want to make sure the entire focus 2669 // view is visible. 2670 rectangle = null; 2671 } 2672 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2673 + " rectangle=" + rectangle + " ci=" + ci 2674 + " vi=" + vi); 2675 if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) { 2676 // Optimization: if the focus hasn't changed since last 2677 // time, and no layout has happened, then just leave things 2678 // as they are. 2679 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2680 + mScrollY + " vi=" + vi.toShortString()); 2681 } else { 2682 // We need to determine if the currently focused view is 2683 // within the visible part of the window and, if not, apply 2684 // a pan so it can be seen. 2685 mLastScrolledFocus = new WeakReference<View>(focus); 2686 mScrollMayChange = false; 2687 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2688 // Try to find the rectangle from the focus view. 2689 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2690 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2691 + mView.getWidth() + " h=" + mView.getHeight() 2692 + " ci=" + ci.toShortString() 2693 + " vi=" + vi.toShortString()); 2694 if (rectangle == null) { 2695 focus.getFocusedRect(mTempRect); 2696 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2697 + ": focusRect=" + mTempRect.toShortString()); 2698 if (mView instanceof ViewGroup) { 2699 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2700 focus, mTempRect); 2701 } 2702 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2703 "Focus in window: focusRect=" 2704 + mTempRect.toShortString() 2705 + " visRect=" + mVisRect.toShortString()); 2706 } else { 2707 mTempRect.set(rectangle); 2708 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2709 "Request scroll to rect: " 2710 + mTempRect.toShortString() 2711 + " visRect=" + mVisRect.toShortString()); 2712 } 2713 if (mTempRect.intersect(mVisRect)) { 2714 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2715 "Focus window visible rect: " 2716 + mTempRect.toShortString()); 2717 if (mTempRect.height() > 2718 (mView.getHeight()-vi.top-vi.bottom)) { 2719 // If the focus simply is not going to fit, then 2720 // best is probably just to leave things as-is. 2721 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2722 "Too tall; leaving scrollY=" + scrollY); 2723 } else if ((mTempRect.top-scrollY) < vi.top) { 2724 scrollY -= vi.top - (mTempRect.top-scrollY); 2725 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2726 "Top covered; scrollY=" + scrollY); 2727 } else if ((mTempRect.bottom-scrollY) 2728 > (mView.getHeight()-vi.bottom)) { 2729 scrollY += (mTempRect.bottom-scrollY) 2730 - (mView.getHeight()-vi.bottom); 2731 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2732 "Bottom covered; scrollY=" + scrollY); 2733 } 2734 handled = true; 2735 } 2736 } 2737 } 2738 } 2739 2740 if (scrollY != mScrollY) { 2741 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2742 + mScrollY + " , new=" + scrollY); 2743 if (!immediate && mResizeBuffer == null) { 2744 if (mScroller == null) { 2745 mScroller = new Scroller(mView.getContext()); 2746 } 2747 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2748 } else if (mScroller != null) { 2749 mScroller.abortAnimation(); 2750 } 2751 mScrollY = scrollY; 2752 } 2753 2754 return handled; 2755 } 2756 2757 /** 2758 * @hide 2759 */ 2760 public View getAccessibilityFocusedHost() { 2761 return mAccessibilityFocusedHost; 2762 } 2763 2764 /** 2765 * @hide 2766 */ 2767 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() { 2768 return mAccessibilityFocusedVirtualView; 2769 } 2770 2771 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) { 2772 // If we have a virtual view with accessibility focus we need 2773 // to clear the focus and invalidate the virtual view bounds. 2774 if (mAccessibilityFocusedVirtualView != null) { 2775 2776 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView; 2777 View focusHost = mAccessibilityFocusedHost; 2778 2779 // Wipe the state of the current accessibility focus since 2780 // the call into the provider to clear accessibility focus 2781 // will fire an accessibility event which will end up calling 2782 // this method and we want to have clean state when this 2783 // invocation happens. 2784 mAccessibilityFocusedHost = null; 2785 mAccessibilityFocusedVirtualView = null; 2786 2787 // Clear accessibility focus on the host after clearing state since 2788 // this method may be reentrant. 2789 focusHost.clearAccessibilityFocusNoCallbacks(); 2790 2791 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider(); 2792 if (provider != null) { 2793 // Invalidate the area of the cleared accessibility focus. 2794 focusNode.getBoundsInParent(mTempRect); 2795 focusHost.invalidate(mTempRect); 2796 // Clear accessibility focus in the virtual node. 2797 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 2798 focusNode.getSourceNodeId()); 2799 provider.performAction(virtualNodeId, 2800 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); 2801 } 2802 focusNode.recycle(); 2803 } 2804 if (mAccessibilityFocusedHost != null) { 2805 // Clear accessibility focus in the view. 2806 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(); 2807 } 2808 2809 // Set the new focus host and node. 2810 mAccessibilityFocusedHost = view; 2811 mAccessibilityFocusedVirtualView = node; 2812 } 2813 2814 @Override 2815 public void requestChildFocus(View child, View focused) { 2816 if (DEBUG_INPUT_RESIZE) { 2817 Log.v(TAG, "Request child focus: focus now " + focused); 2818 } 2819 checkThread(); 2820 scheduleTraversals(); 2821 } 2822 2823 @Override 2824 public void clearChildFocus(View child) { 2825 if (DEBUG_INPUT_RESIZE) { 2826 Log.v(TAG, "Clearing child focus"); 2827 } 2828 checkThread(); 2829 scheduleTraversals(); 2830 } 2831 2832 @Override 2833 public ViewParent getParentForAccessibility() { 2834 return null; 2835 } 2836 2837 @Override 2838 public void focusableViewAvailable(View v) { 2839 checkThread(); 2840 if (mView != null) { 2841 if (!mView.hasFocus()) { 2842 v.requestFocus(); 2843 } else { 2844 // the one case where will transfer focus away from the current one 2845 // is if the current view is a view group that prefers to give focus 2846 // to its children first AND the view is a descendant of it. 2847 View focused = mView.findFocus(); 2848 if (focused instanceof ViewGroup) { 2849 ViewGroup group = (ViewGroup) focused; 2850 if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 2851 && isViewDescendantOf(v, focused)) { 2852 v.requestFocus(); 2853 } 2854 } 2855 } 2856 } 2857 } 2858 2859 @Override 2860 public void recomputeViewAttributes(View child) { 2861 checkThread(); 2862 if (mView == child) { 2863 mAttachInfo.mRecomputeGlobalAttributes = true; 2864 if (!mWillDrawSoon) { 2865 scheduleTraversals(); 2866 } 2867 } 2868 } 2869 2870 void dispatchDetachedFromWindow() { 2871 if (mView != null && mView.mAttachInfo != null) { 2872 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false); 2873 mView.dispatchDetachedFromWindow(); 2874 } 2875 2876 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2877 mAccessibilityManager.removeAccessibilityStateChangeListener( 2878 mAccessibilityInteractionConnectionManager); 2879 removeSendWindowContentChangedCallback(); 2880 2881 destroyHardwareRenderer(); 2882 2883 setAccessibilityFocus(null, null); 2884 2885 mView.assignParent(null); 2886 mView = null; 2887 mAttachInfo.mRootView = null; 2888 2889 mSurface.release(); 2890 2891 if (mInputQueueCallback != null && mInputQueue != null) { 2892 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2893 mInputQueue.dispose(); 2894 mInputQueueCallback = null; 2895 mInputQueue = null; 2896 } 2897 if (mInputEventReceiver != null) { 2898 mInputEventReceiver.dispose(); 2899 mInputEventReceiver = null; 2900 } 2901 try { 2902 mWindowSession.remove(mWindow); 2903 } catch (RemoteException e) { 2904 } 2905 2906 // Dispose the input channel after removing the window so the Window Manager 2907 // doesn't interpret the input channel being closed as an abnormal termination. 2908 if (mInputChannel != null) { 2909 mInputChannel.dispose(); 2910 mInputChannel = null; 2911 } 2912 2913 mDisplayManager.unregisterDisplayListener(mDisplayListener); 2914 2915 unscheduleTraversals(); 2916 } 2917 2918 void updateConfiguration(Configuration config, boolean force) { 2919 if (DEBUG_CONFIGURATION) Log.v(TAG, 2920 "Applying new config to window " 2921 + mWindowAttributes.getTitle() 2922 + ": " + config); 2923 2924 CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo(); 2925 if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) { 2926 config = new Configuration(config); 2927 ci.applyToConfiguration(mNoncompatDensity, config); 2928 } 2929 2930 synchronized (sConfigCallbacks) { 2931 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2932 sConfigCallbacks.get(i).onConfigurationChanged(config); 2933 } 2934 } 2935 if (mView != null) { 2936 // At this point the resources have been updated to 2937 // have the most recent config, whatever that is. Use 2938 // the one in them which may be newer. 2939 config = mView.getResources().getConfiguration(); 2940 if (force || mLastConfiguration.diff(config) != 0) { 2941 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection(); 2942 final int currentLayoutDirection = config.getLayoutDirection(); 2943 mLastConfiguration.setTo(config); 2944 if (lastLayoutDirection != currentLayoutDirection && 2945 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 2946 mView.setLayoutDirection(currentLayoutDirection); 2947 } 2948 mView.dispatchConfigurationChanged(config); 2949 } 2950 } 2951 } 2952 2953 /** 2954 * Return true if child is an ancestor of parent, (or equal to the parent). 2955 */ 2956 public static boolean isViewDescendantOf(View child, View parent) { 2957 if (child == parent) { 2958 return true; 2959 } 2960 2961 final ViewParent theParent = child.getParent(); 2962 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2963 } 2964 2965 private static void forceLayout(View view) { 2966 view.forceLayout(); 2967 if (view instanceof ViewGroup) { 2968 ViewGroup group = (ViewGroup) view; 2969 final int count = group.getChildCount(); 2970 for (int i = 0; i < count; i++) { 2971 forceLayout(group.getChildAt(i)); 2972 } 2973 } 2974 } 2975 2976 private final static int MSG_INVALIDATE = 1; 2977 private final static int MSG_INVALIDATE_RECT = 2; 2978 private final static int MSG_DIE = 3; 2979 private final static int MSG_RESIZED = 4; 2980 private final static int MSG_RESIZED_REPORT = 5; 2981 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 2982 private final static int MSG_DISPATCH_INPUT_EVENT = 7; 2983 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 2984 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 2985 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 2986 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 2987 private final static int MSG_CHECK_FOCUS = 13; 2988 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 2989 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 2990 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 2991 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 2992 private final static int MSG_UPDATE_CONFIGURATION = 18; 2993 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 2994 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21; 2995 private final static int MSG_DISPATCH_DONE_ANIMATING = 22; 2996 private final static int MSG_INVALIDATE_WORLD = 23; 2997 private final static int MSG_WINDOW_MOVED = 24; 2998 private final static int MSG_FLUSH_LAYER_UPDATES = 25; 2999 3000 final class ViewRootHandler extends Handler { 3001 @Override 3002 public String getMessageName(Message message) { 3003 switch (message.what) { 3004 case MSG_INVALIDATE: 3005 return "MSG_INVALIDATE"; 3006 case MSG_INVALIDATE_RECT: 3007 return "MSG_INVALIDATE_RECT"; 3008 case MSG_DIE: 3009 return "MSG_DIE"; 3010 case MSG_RESIZED: 3011 return "MSG_RESIZED"; 3012 case MSG_RESIZED_REPORT: 3013 return "MSG_RESIZED_REPORT"; 3014 case MSG_WINDOW_FOCUS_CHANGED: 3015 return "MSG_WINDOW_FOCUS_CHANGED"; 3016 case MSG_DISPATCH_INPUT_EVENT: 3017 return "MSG_DISPATCH_INPUT_EVENT"; 3018 case MSG_DISPATCH_APP_VISIBILITY: 3019 return "MSG_DISPATCH_APP_VISIBILITY"; 3020 case MSG_DISPATCH_GET_NEW_SURFACE: 3021 return "MSG_DISPATCH_GET_NEW_SURFACE"; 3022 case MSG_DISPATCH_KEY_FROM_IME: 3023 return "MSG_DISPATCH_KEY_FROM_IME"; 3024 case MSG_FINISH_INPUT_CONNECTION: 3025 return "MSG_FINISH_INPUT_CONNECTION"; 3026 case MSG_CHECK_FOCUS: 3027 return "MSG_CHECK_FOCUS"; 3028 case MSG_CLOSE_SYSTEM_DIALOGS: 3029 return "MSG_CLOSE_SYSTEM_DIALOGS"; 3030 case MSG_DISPATCH_DRAG_EVENT: 3031 return "MSG_DISPATCH_DRAG_EVENT"; 3032 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 3033 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 3034 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 3035 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 3036 case MSG_UPDATE_CONFIGURATION: 3037 return "MSG_UPDATE_CONFIGURATION"; 3038 case MSG_PROCESS_INPUT_EVENTS: 3039 return "MSG_PROCESS_INPUT_EVENTS"; 3040 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 3041 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 3042 case MSG_DISPATCH_DONE_ANIMATING: 3043 return "MSG_DISPATCH_DONE_ANIMATING"; 3044 case MSG_WINDOW_MOVED: 3045 return "MSG_WINDOW_MOVED"; 3046 case MSG_FLUSH_LAYER_UPDATES: 3047 return "MSG_FLUSH_LAYER_UPDATES"; 3048 } 3049 return super.getMessageName(message); 3050 } 3051 3052 @Override 3053 public void handleMessage(Message msg) { 3054 switch (msg.what) { 3055 case MSG_INVALIDATE: 3056 ((View) msg.obj).invalidate(); 3057 break; 3058 case MSG_INVALIDATE_RECT: 3059 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 3060 info.target.invalidate(info.left, info.top, info.right, info.bottom); 3061 info.recycle(); 3062 break; 3063 case MSG_PROCESS_INPUT_EVENTS: 3064 mProcessInputEventsScheduled = false; 3065 doProcessInputEvents(); 3066 break; 3067 case MSG_DISPATCH_APP_VISIBILITY: 3068 handleAppVisibility(msg.arg1 != 0); 3069 break; 3070 case MSG_DISPATCH_GET_NEW_SURFACE: 3071 handleGetNewSurface(); 3072 break; 3073 case MSG_RESIZED: { 3074 // Recycled in the fall through... 3075 SomeArgs args = (SomeArgs) msg.obj; 3076 if (mWinFrame.equals(args.arg1) 3077 && mPendingOverscanInsets.equals(args.arg5) 3078 && mPendingContentInsets.equals(args.arg2) 3079 && mPendingVisibleInsets.equals(args.arg3) 3080 && args.arg4 == null) { 3081 break; 3082 } 3083 } // fall through... 3084 case MSG_RESIZED_REPORT: 3085 if (mAdded) { 3086 SomeArgs args = (SomeArgs) msg.obj; 3087 3088 Configuration config = (Configuration) args.arg4; 3089 if (config != null) { 3090 updateConfiguration(config, false); 3091 } 3092 3093 mWinFrame.set((Rect) args.arg1); 3094 mPendingOverscanInsets.set((Rect) args.arg5); 3095 mPendingContentInsets.set((Rect) args.arg2); 3096 mPendingVisibleInsets.set((Rect) args.arg3); 3097 3098 args.recycle(); 3099 3100 if (msg.what == MSG_RESIZED_REPORT) { 3101 mReportNextDraw = true; 3102 } 3103 3104 if (mView != null) { 3105 forceLayout(mView); 3106 } 3107 3108 requestLayout(); 3109 } 3110 break; 3111 case MSG_WINDOW_MOVED: 3112 if (mAdded) { 3113 final int w = mWinFrame.width(); 3114 final int h = mWinFrame.height(); 3115 final int l = msg.arg1; 3116 final int t = msg.arg2; 3117 mWinFrame.left = l; 3118 mWinFrame.right = l + w; 3119 mWinFrame.top = t; 3120 mWinFrame.bottom = t + h; 3121 3122 if (mView != null) { 3123 forceLayout(mView); 3124 } 3125 requestLayout(); 3126 } 3127 break; 3128 case MSG_WINDOW_FOCUS_CHANGED: { 3129 if (mAdded) { 3130 boolean hasWindowFocus = msg.arg1 != 0; 3131 mAttachInfo.mHasWindowFocus = hasWindowFocus; 3132 3133 profileRendering(hasWindowFocus); 3134 3135 if (hasWindowFocus) { 3136 boolean inTouchMode = msg.arg2 != 0; 3137 ensureTouchModeLocally(inTouchMode); 3138 3139 if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){ 3140 mFullRedrawNeeded = true; 3141 try { 3142 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 3143 mWidth, mHeight, mSurface); 3144 } catch (OutOfResourcesException e) { 3145 Log.e(TAG, "OutOfResourcesException locking surface", e); 3146 try { 3147 if (!mWindowSession.outOfMemory(mWindow)) { 3148 Slog.w(TAG, "No processes killed for memory; killing self"); 3149 Process.killProcess(Process.myPid()); 3150 } 3151 } catch (RemoteException ex) { 3152 } 3153 // Retry in a bit. 3154 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 3155 return; 3156 } 3157 } 3158 } 3159 3160 mLastWasImTarget = WindowManager.LayoutParams 3161 .mayUseInputMethod(mWindowAttributes.flags); 3162 3163 InputMethodManager imm = InputMethodManager.peekInstance(); 3164 if (mView != null) { 3165 if (hasWindowFocus && imm != null && mLastWasImTarget && 3166 !isInLocalFocusMode()) { 3167 imm.startGettingWindowFocus(mView); 3168 } 3169 mAttachInfo.mKeyDispatchState.reset(); 3170 mView.dispatchWindowFocusChanged(hasWindowFocus); 3171 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus); 3172 } 3173 3174 // Note: must be done after the focus change callbacks, 3175 // so all of the view state is set up correctly. 3176 if (hasWindowFocus) { 3177 if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { 3178 imm.onWindowFocus(mView, mView.findFocus(), 3179 mWindowAttributes.softInputMode, 3180 !mHasHadWindowFocus, mWindowAttributes.flags); 3181 } 3182 // Clear the forward bit. We can just do this directly, since 3183 // the window manager doesn't care about it. 3184 mWindowAttributes.softInputMode &= 3185 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3186 ((WindowManager.LayoutParams)mView.getLayoutParams()) 3187 .softInputMode &= 3188 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3189 mHasHadWindowFocus = true; 3190 } 3191 3192 if (mView != null && mAccessibilityManager.isEnabled()) { 3193 if (hasWindowFocus) { 3194 mView.sendAccessibilityEvent( 3195 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 3196 } 3197 } 3198 } 3199 } break; 3200 case MSG_DIE: 3201 doDie(); 3202 break; 3203 case MSG_DISPATCH_INPUT_EVENT: { 3204 InputEvent event = (InputEvent)msg.obj; 3205 enqueueInputEvent(event, null, 0, true); 3206 } break; 3207 case MSG_DISPATCH_KEY_FROM_IME: { 3208 if (LOCAL_LOGV) Log.v( 3209 TAG, "Dispatching key " 3210 + msg.obj + " from IME to " + mView); 3211 KeyEvent event = (KeyEvent)msg.obj; 3212 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 3213 // The IME is trying to say this event is from the 3214 // system! Bad bad bad! 3215 //noinspection UnusedAssignment 3216 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 3217 } 3218 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 3219 } break; 3220 case MSG_FINISH_INPUT_CONNECTION: { 3221 InputMethodManager imm = InputMethodManager.peekInstance(); 3222 if (imm != null) { 3223 imm.reportFinishInputConnection((InputConnection)msg.obj); 3224 } 3225 } break; 3226 case MSG_CHECK_FOCUS: { 3227 InputMethodManager imm = InputMethodManager.peekInstance(); 3228 if (imm != null) { 3229 imm.checkFocus(); 3230 } 3231 } break; 3232 case MSG_CLOSE_SYSTEM_DIALOGS: { 3233 if (mView != null) { 3234 mView.onCloseSystemDialogs((String)msg.obj); 3235 } 3236 } break; 3237 case MSG_DISPATCH_DRAG_EVENT: 3238 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 3239 DragEvent event = (DragEvent)msg.obj; 3240 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 3241 handleDragEvent(event); 3242 } break; 3243 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 3244 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); 3245 } break; 3246 case MSG_UPDATE_CONFIGURATION: { 3247 Configuration config = (Configuration)msg.obj; 3248 if (config.isOtherSeqNewer(mLastConfiguration)) { 3249 config = mLastConfiguration; 3250 } 3251 updateConfiguration(config, false); 3252 } break; 3253 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3254 setAccessibilityFocus(null, null); 3255 } break; 3256 case MSG_DISPATCH_DONE_ANIMATING: { 3257 handleDispatchDoneAnimating(); 3258 } break; 3259 case MSG_INVALIDATE_WORLD: { 3260 if (mView != null) { 3261 invalidateWorld(mView); 3262 } 3263 } break; 3264 case MSG_FLUSH_LAYER_UPDATES: { 3265 flushHardwareLayerUpdates(); 3266 } break; 3267 } 3268 } 3269 } 3270 3271 final ViewRootHandler mHandler = new ViewRootHandler(); 3272 3273 /** 3274 * Something in the current window tells us we need to change the touch mode. For 3275 * example, we are not in touch mode, and the user touches the screen. 3276 * 3277 * If the touch mode has changed, tell the window manager, and handle it locally. 3278 * 3279 * @param inTouchMode Whether we want to be in touch mode. 3280 * @return True if the touch mode changed and focus changed was changed as a result 3281 */ 3282 boolean ensureTouchMode(boolean inTouchMode) { 3283 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3284 + "touch mode is " + mAttachInfo.mInTouchMode); 3285 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3286 3287 // tell the window manager 3288 try { 3289 if (!isInLocalFocusMode()) { 3290 mWindowSession.setInTouchMode(inTouchMode); 3291 } 3292 } catch (RemoteException e) { 3293 throw new RuntimeException(e); 3294 } 3295 3296 // handle the change 3297 return ensureTouchModeLocally(inTouchMode); 3298 } 3299 3300 /** 3301 * Ensure that the touch mode for this window is set, and if it is changing, 3302 * take the appropriate action. 3303 * @param inTouchMode Whether we want to be in touch mode. 3304 * @return True if the touch mode changed and focus changed was changed as a result 3305 */ 3306 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3307 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3308 + "touch mode is " + mAttachInfo.mInTouchMode); 3309 3310 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3311 3312 mAttachInfo.mInTouchMode = inTouchMode; 3313 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3314 3315 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3316 } 3317 3318 private boolean enterTouchMode() { 3319 if (mView != null && mView.hasFocus()) { 3320 // note: not relying on mFocusedView here because this could 3321 // be when the window is first being added, and mFocused isn't 3322 // set yet. 3323 final View focused = mView.findFocus(); 3324 if (focused != null && !focused.isFocusableInTouchMode()) { 3325 final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused); 3326 if (ancestorToTakeFocus != null) { 3327 // there is an ancestor that wants focus after its 3328 // descendants that is focusable in touch mode.. give it 3329 // focus 3330 return ancestorToTakeFocus.requestFocus(); 3331 } else { 3332 // There's nothing to focus. Clear and propagate through the 3333 // hierarchy, but don't attempt to place new focus. 3334 focused.clearFocusInternal(null, true, false); 3335 return true; 3336 } 3337 } 3338 } 3339 return false; 3340 } 3341 3342 /** 3343 * Find an ancestor of focused that wants focus after its descendants and is 3344 * focusable in touch mode. 3345 * @param focused The currently focused view. 3346 * @return An appropriate view, or null if no such view exists. 3347 */ 3348 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3349 ViewParent parent = focused.getParent(); 3350 while (parent instanceof ViewGroup) { 3351 final ViewGroup vgParent = (ViewGroup) parent; 3352 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3353 && vgParent.isFocusableInTouchMode()) { 3354 return vgParent; 3355 } 3356 if (vgParent.isRootNamespace()) { 3357 return null; 3358 } else { 3359 parent = vgParent.getParent(); 3360 } 3361 } 3362 return null; 3363 } 3364 3365 private boolean leaveTouchMode() { 3366 if (mView != null) { 3367 if (mView.hasFocus()) { 3368 View focusedView = mView.findFocus(); 3369 if (!(focusedView instanceof ViewGroup)) { 3370 // some view has focus, let it keep it 3371 return false; 3372 } else if (((ViewGroup) focusedView).getDescendantFocusability() != 3373 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3374 // some view group has focus, and doesn't prefer its children 3375 // over itself for focus, so let them keep it. 3376 return false; 3377 } 3378 } 3379 3380 // find the best view to give focus to in this brave new non-touch-mode 3381 // world 3382 final View focused = focusSearch(null, View.FOCUS_DOWN); 3383 if (focused != null) { 3384 return focused.requestFocus(View.FOCUS_DOWN); 3385 } 3386 } 3387 return false; 3388 } 3389 3390 /** 3391 * Base class for implementing a stage in the chain of responsibility 3392 * for processing input events. 3393 * <p> 3394 * Events are delivered to the stage by the {@link #deliver} method. The stage 3395 * then has the choice of finishing the event or forwarding it to the next stage. 3396 * </p> 3397 */ 3398 abstract class InputStage { 3399 private final InputStage mNext; 3400 3401 protected static final int FORWARD = 0; 3402 protected static final int FINISH_HANDLED = 1; 3403 protected static final int FINISH_NOT_HANDLED = 2; 3404 3405 /** 3406 * Creates an input stage. 3407 * @param next The next stage to which events should be forwarded. 3408 */ 3409 public InputStage(InputStage next) { 3410 mNext = next; 3411 } 3412 3413 /** 3414 * Delivers an event to be processed. 3415 */ 3416 public final void deliver(QueuedInputEvent q) { 3417 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) { 3418 forward(q); 3419 } else if (shouldDropInputEvent(q)) { 3420 finish(q, false); 3421 } else { 3422 apply(q, onProcess(q)); 3423 } 3424 } 3425 3426 /** 3427 * Marks the the input event as finished then forwards it to the next stage. 3428 */ 3429 protected void finish(QueuedInputEvent q, boolean handled) { 3430 q.mFlags |= QueuedInputEvent.FLAG_FINISHED; 3431 if (handled) { 3432 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED; 3433 } 3434 forward(q); 3435 } 3436 3437 /** 3438 * Forwards the event to the next stage. 3439 */ 3440 protected void forward(QueuedInputEvent q) { 3441 onDeliverToNext(q); 3442 } 3443 3444 /** 3445 * Applies a result code from {@link #onProcess} to the specified event. 3446 */ 3447 protected void apply(QueuedInputEvent q, int result) { 3448 if (result == FORWARD) { 3449 forward(q); 3450 } else if (result == FINISH_HANDLED) { 3451 finish(q, true); 3452 } else if (result == FINISH_NOT_HANDLED) { 3453 finish(q, false); 3454 } else { 3455 throw new IllegalArgumentException("Invalid result: " + result); 3456 } 3457 } 3458 3459 /** 3460 * Called when an event is ready to be processed. 3461 * @return A result code indicating how the event was handled. 3462 */ 3463 protected int onProcess(QueuedInputEvent q) { 3464 return FORWARD; 3465 } 3466 3467 /** 3468 * Called when an event is being delivered to the next stage. 3469 */ 3470 protected void onDeliverToNext(QueuedInputEvent q) { 3471 if (mNext != null) { 3472 mNext.deliver(q); 3473 } else { 3474 finishInputEvent(q); 3475 } 3476 } 3477 3478 protected boolean shouldDropInputEvent(QueuedInputEvent q) { 3479 if (mView == null || !mAdded) { 3480 Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent); 3481 return true; 3482 } else if (!mAttachInfo.mHasWindowFocus && 3483 !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER) && 3484 !isTerminalInputEvent(q.mEvent)) { 3485 // If this is a focused event and the window doesn't currently have input focus, 3486 // then drop this event. This could be an event that came back from the previous 3487 // stage but the window has lost focus in the meantime. 3488 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent); 3489 return true; 3490 } 3491 return false; 3492 } 3493 3494 void dump(String prefix, PrintWriter writer) { 3495 if (mNext != null) { 3496 mNext.dump(prefix, writer); 3497 } 3498 } 3499 } 3500 3501 /** 3502 * Base class for implementing an input pipeline stage that supports 3503 * asynchronous and out-of-order processing of input events. 3504 * <p> 3505 * In addition to what a normal input stage can do, an asynchronous 3506 * input stage may also defer an input event that has been delivered to it 3507 * and finish or forward it later. 3508 * </p> 3509 */ 3510 abstract class AsyncInputStage extends InputStage { 3511 private final String mTraceCounter; 3512 3513 private QueuedInputEvent mQueueHead; 3514 private QueuedInputEvent mQueueTail; 3515 private int mQueueLength; 3516 3517 protected static final int DEFER = 3; 3518 3519 /** 3520 * Creates an asynchronous input stage. 3521 * @param next The next stage to which events should be forwarded. 3522 * @param traceCounter The name of a counter to record the size of 3523 * the queue of pending events. 3524 */ 3525 public AsyncInputStage(InputStage next, String traceCounter) { 3526 super(next); 3527 mTraceCounter = traceCounter; 3528 } 3529 3530 /** 3531 * Marks the event as deferred, which is to say that it will be handled 3532 * asynchronously. The caller is responsible for calling {@link #forward} 3533 * or {@link #finish} later when it is done handling the event. 3534 */ 3535 protected void defer(QueuedInputEvent q) { 3536 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED; 3537 enqueue(q); 3538 } 3539 3540 @Override 3541 protected void forward(QueuedInputEvent q) { 3542 // Clear the deferred flag. 3543 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED; 3544 3545 // Fast path if the queue is empty. 3546 QueuedInputEvent curr = mQueueHead; 3547 if (curr == null) { 3548 super.forward(q); 3549 return; 3550 } 3551 3552 // Determine whether the event must be serialized behind any others 3553 // before it can be delivered to the next stage. This is done because 3554 // deferred events might be handled out of order by the stage. 3555 final int deviceId = q.mEvent.getDeviceId(); 3556 QueuedInputEvent prev = null; 3557 boolean blocked = false; 3558 while (curr != null && curr != q) { 3559 if (!blocked && deviceId == curr.mEvent.getDeviceId()) { 3560 blocked = true; 3561 } 3562 prev = curr; 3563 curr = curr.mNext; 3564 } 3565 3566 // If the event is blocked, then leave it in the queue to be delivered later. 3567 // Note that the event might not yet be in the queue if it was not previously 3568 // deferred so we will enqueue it if needed. 3569 if (blocked) { 3570 if (curr == null) { 3571 enqueue(q); 3572 } 3573 return; 3574 } 3575 3576 // The event is not blocked. Deliver it immediately. 3577 if (curr != null) { 3578 curr = curr.mNext; 3579 dequeue(q, prev); 3580 } 3581 super.forward(q); 3582 3583 // Dequeuing this event may have unblocked successors. Deliver them. 3584 while (curr != null) { 3585 if (deviceId == curr.mEvent.getDeviceId()) { 3586 if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) { 3587 break; 3588 } 3589 QueuedInputEvent next = curr.mNext; 3590 dequeue(curr, prev); 3591 super.forward(curr); 3592 curr = next; 3593 } else { 3594 prev = curr; 3595 curr = curr.mNext; 3596 } 3597 } 3598 } 3599 3600 @Override 3601 protected void apply(QueuedInputEvent q, int result) { 3602 if (result == DEFER) { 3603 defer(q); 3604 } else { 3605 super.apply(q, result); 3606 } 3607 } 3608 3609 private void enqueue(QueuedInputEvent q) { 3610 if (mQueueTail == null) { 3611 mQueueHead = q; 3612 mQueueTail = q; 3613 } else { 3614 mQueueTail.mNext = q; 3615 mQueueTail = q; 3616 } 3617 3618 mQueueLength += 1; 3619 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3620 } 3621 3622 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) { 3623 if (prev == null) { 3624 mQueueHead = q.mNext; 3625 } else { 3626 prev.mNext = q.mNext; 3627 } 3628 if (mQueueTail == q) { 3629 mQueueTail = prev; 3630 } 3631 q.mNext = null; 3632 3633 mQueueLength -= 1; 3634 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3635 } 3636 3637 @Override 3638 void dump(String prefix, PrintWriter writer) { 3639 writer.print(prefix); 3640 writer.print(getClass().getName()); 3641 writer.print(": mQueueLength="); 3642 writer.println(mQueueLength); 3643 3644 super.dump(prefix, writer); 3645 } 3646 } 3647 3648 /** 3649 * Delivers pre-ime input events to a native activity. 3650 * Does not support pointer events. 3651 */ 3652 final class NativePreImeInputStage extends AsyncInputStage 3653 implements InputQueue.FinishedInputEventCallback { 3654 public NativePreImeInputStage(InputStage next, String traceCounter) { 3655 super(next, traceCounter); 3656 } 3657 3658 @Override 3659 protected int onProcess(QueuedInputEvent q) { 3660 if (mInputQueue != null && q.mEvent instanceof KeyEvent) { 3661 mInputQueue.sendInputEvent(q.mEvent, q, true, this); 3662 return DEFER; 3663 } 3664 return FORWARD; 3665 } 3666 3667 @Override 3668 public void onFinishedInputEvent(Object token, boolean handled) { 3669 QueuedInputEvent q = (QueuedInputEvent)token; 3670 if (handled) { 3671 finish(q, true); 3672 return; 3673 } 3674 forward(q); 3675 } 3676 } 3677 3678 /** 3679 * Delivers pre-ime input events to the view hierarchy. 3680 * Does not support pointer events. 3681 */ 3682 final class ViewPreImeInputStage extends InputStage { 3683 public ViewPreImeInputStage(InputStage next) { 3684 super(next); 3685 } 3686 3687 @Override 3688 protected int onProcess(QueuedInputEvent q) { 3689 if (q.mEvent instanceof KeyEvent) { 3690 return processKeyEvent(q); 3691 } 3692 return FORWARD; 3693 } 3694 3695 private int processKeyEvent(QueuedInputEvent q) { 3696 final KeyEvent event = (KeyEvent)q.mEvent; 3697 if (mView.dispatchKeyEventPreIme(event)) { 3698 return FINISH_HANDLED; 3699 } 3700 return FORWARD; 3701 } 3702 } 3703 3704 /** 3705 * Delivers input events to the ime. 3706 * Does not support pointer events. 3707 */ 3708 final class ImeInputStage extends AsyncInputStage 3709 implements InputMethodManager.FinishedInputEventCallback { 3710 public ImeInputStage(InputStage next, String traceCounter) { 3711 super(next, traceCounter); 3712 } 3713 3714 @Override 3715 protected int onProcess(QueuedInputEvent q) { 3716 if (mLastWasImTarget && !isInLocalFocusMode()) { 3717 InputMethodManager imm = InputMethodManager.peekInstance(); 3718 if (imm != null) { 3719 final InputEvent event = q.mEvent; 3720 if (DEBUG_IMF) Log.v(TAG, "Sending input event to IME: " + event); 3721 int result = imm.dispatchInputEvent(event, q, this, mHandler); 3722 if (result == InputMethodManager.DISPATCH_HANDLED) { 3723 return FINISH_HANDLED; 3724 } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) { 3725 // The IME could not handle it, so skip along to the next InputStage 3726 return FORWARD; 3727 } else { 3728 return DEFER; // callback will be invoked later 3729 } 3730 } 3731 } 3732 return FORWARD; 3733 } 3734 3735 @Override 3736 public void onFinishedInputEvent(Object token, boolean handled) { 3737 QueuedInputEvent q = (QueuedInputEvent)token; 3738 if (handled) { 3739 finish(q, true); 3740 return; 3741 } 3742 forward(q); 3743 } 3744 } 3745 3746 /** 3747 * Performs early processing of post-ime input events. 3748 */ 3749 final class EarlyPostImeInputStage extends InputStage { 3750 public EarlyPostImeInputStage(InputStage next) { 3751 super(next); 3752 } 3753 3754 @Override 3755 protected int onProcess(QueuedInputEvent q) { 3756 if (q.mEvent instanceof KeyEvent) { 3757 return processKeyEvent(q); 3758 } else { 3759 final int source = q.mEvent.getSource(); 3760 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3761 return processPointerEvent(q); 3762 } 3763 } 3764 return FORWARD; 3765 } 3766 3767 private int processKeyEvent(QueuedInputEvent q) { 3768 final KeyEvent event = (KeyEvent)q.mEvent; 3769 3770 // If the key's purpose is to exit touch mode then we consume it 3771 // and consider it handled. 3772 if (checkForLeavingTouchModeAndConsume(event)) { 3773 return FINISH_HANDLED; 3774 } 3775 3776 // Make sure the fallback event policy sees all keys that will be 3777 // delivered to the view hierarchy. 3778 mFallbackEventHandler.preDispatchKeyEvent(event); 3779 return FORWARD; 3780 } 3781 3782 private int processPointerEvent(QueuedInputEvent q) { 3783 final MotionEvent event = (MotionEvent)q.mEvent; 3784 3785 // Translate the pointer event for compatibility, if needed. 3786 if (mTranslator != null) { 3787 mTranslator.translateEventInScreenToAppWindow(event); 3788 } 3789 3790 // Enter touch mode on down or scroll. 3791 final int action = event.getAction(); 3792 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3793 ensureTouchMode(true); 3794 } 3795 3796 // Offset the scroll position. 3797 if (mCurScrollY != 0) { 3798 event.offsetLocation(0, mCurScrollY); 3799 } 3800 3801 // Remember the touch position for possible drag-initiation. 3802 if (event.isTouchEvent()) { 3803 mLastTouchPoint.x = event.getRawX(); 3804 mLastTouchPoint.y = event.getRawY(); 3805 } 3806 return FORWARD; 3807 } 3808 } 3809 3810 /** 3811 * Delivers post-ime input events to a native activity. 3812 */ 3813 final class NativePostImeInputStage extends AsyncInputStage 3814 implements InputQueue.FinishedInputEventCallback { 3815 public NativePostImeInputStage(InputStage next, String traceCounter) { 3816 super(next, traceCounter); 3817 } 3818 3819 @Override 3820 protected int onProcess(QueuedInputEvent q) { 3821 if (mInputQueue != null) { 3822 mInputQueue.sendInputEvent(q.mEvent, q, false, this); 3823 return DEFER; 3824 } 3825 return FORWARD; 3826 } 3827 3828 @Override 3829 public void onFinishedInputEvent(Object token, boolean handled) { 3830 QueuedInputEvent q = (QueuedInputEvent)token; 3831 if (handled) { 3832 finish(q, true); 3833 return; 3834 } 3835 forward(q); 3836 } 3837 } 3838 3839 /** 3840 * Delivers post-ime input events to the view hierarchy. 3841 */ 3842 final class ViewPostImeInputStage extends InputStage { 3843 public ViewPostImeInputStage(InputStage next) { 3844 super(next); 3845 } 3846 3847 @Override 3848 protected int onProcess(QueuedInputEvent q) { 3849 if (q.mEvent instanceof KeyEvent) { 3850 return processKeyEvent(q); 3851 } else { 3852 // If delivering a new non-key event, make sure the window is 3853 // now allowed to start updating. 3854 handleDispatchDoneAnimating(); 3855 final int source = q.mEvent.getSource(); 3856 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3857 return processPointerEvent(q); 3858 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3859 return processTrackballEvent(q); 3860 } else { 3861 return processGenericMotionEvent(q); 3862 } 3863 } 3864 } 3865 3866 private int processKeyEvent(QueuedInputEvent q) { 3867 final KeyEvent event = (KeyEvent)q.mEvent; 3868 3869 if (event.getAction() != KeyEvent.ACTION_UP) { 3870 // If delivering a new key event, make sure the window is 3871 // now allowed to start updating. 3872 handleDispatchDoneAnimating(); 3873 } 3874 3875 // Deliver the key to the view hierarchy. 3876 if (mView.dispatchKeyEvent(event)) { 3877 return FINISH_HANDLED; 3878 } 3879 3880 if (shouldDropInputEvent(q)) { 3881 return FINISH_NOT_HANDLED; 3882 } 3883 3884 // If the Control modifier is held, try to interpret the key as a shortcut. 3885 if (event.getAction() == KeyEvent.ACTION_DOWN 3886 && event.isCtrlPressed() 3887 && event.getRepeatCount() == 0 3888 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3889 if (mView.dispatchKeyShortcutEvent(event)) { 3890 return FINISH_HANDLED; 3891 } 3892 if (shouldDropInputEvent(q)) { 3893 return FINISH_NOT_HANDLED; 3894 } 3895 } 3896 3897 // Apply the fallback event policy. 3898 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3899 return FINISH_HANDLED; 3900 } 3901 if (shouldDropInputEvent(q)) { 3902 return FINISH_NOT_HANDLED; 3903 } 3904 3905 // Handle automatic focus changes. 3906 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3907 int direction = 0; 3908 switch (event.getKeyCode()) { 3909 case KeyEvent.KEYCODE_DPAD_LEFT: 3910 if (event.hasNoModifiers()) { 3911 direction = View.FOCUS_LEFT; 3912 } 3913 break; 3914 case KeyEvent.KEYCODE_DPAD_RIGHT: 3915 if (event.hasNoModifiers()) { 3916 direction = View.FOCUS_RIGHT; 3917 } 3918 break; 3919 case KeyEvent.KEYCODE_DPAD_UP: 3920 if (event.hasNoModifiers()) { 3921 direction = View.FOCUS_UP; 3922 } 3923 break; 3924 case KeyEvent.KEYCODE_DPAD_DOWN: 3925 if (event.hasNoModifiers()) { 3926 direction = View.FOCUS_DOWN; 3927 } 3928 break; 3929 case KeyEvent.KEYCODE_TAB: 3930 if (event.hasNoModifiers()) { 3931 direction = View.FOCUS_FORWARD; 3932 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3933 direction = View.FOCUS_BACKWARD; 3934 } 3935 break; 3936 } 3937 if (direction != 0) { 3938 View focused = mView.findFocus(); 3939 if (focused != null) { 3940 View v = focused.focusSearch(direction); 3941 if (v != null && v != focused) { 3942 // do the math the get the interesting rect 3943 // of previous focused into the coord system of 3944 // newly focused view 3945 focused.getFocusedRect(mTempRect); 3946 if (mView instanceof ViewGroup) { 3947 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3948 focused, mTempRect); 3949 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3950 v, mTempRect); 3951 } 3952 if (v.requestFocus(direction, mTempRect)) { 3953 playSoundEffect(SoundEffectConstants 3954 .getContantForFocusDirection(direction)); 3955 return FINISH_HANDLED; 3956 } 3957 } 3958 3959 // Give the focused view a last chance to handle the dpad key. 3960 if (mView.dispatchUnhandledMove(focused, direction)) { 3961 return FINISH_HANDLED; 3962 } 3963 } else { 3964 // find the best view to give focus to in this non-touch-mode with no-focus 3965 View v = focusSearch(null, direction); 3966 if (v != null && v.requestFocus(direction)) { 3967 return FINISH_HANDLED; 3968 } 3969 } 3970 } 3971 } 3972 return FORWARD; 3973 } 3974 3975 private int processPointerEvent(QueuedInputEvent q) { 3976 final MotionEvent event = (MotionEvent)q.mEvent; 3977 3978 if (mView.dispatchPointerEvent(event)) { 3979 return FINISH_HANDLED; 3980 } 3981 return FORWARD; 3982 } 3983 3984 private int processTrackballEvent(QueuedInputEvent q) { 3985 final MotionEvent event = (MotionEvent)q.mEvent; 3986 3987 if (mView.dispatchTrackballEvent(event)) { 3988 return FINISH_HANDLED; 3989 } 3990 return FORWARD; 3991 } 3992 3993 private int processGenericMotionEvent(QueuedInputEvent q) { 3994 final MotionEvent event = (MotionEvent)q.mEvent; 3995 3996 // Deliver the event to the view. 3997 if (mView.dispatchGenericMotionEvent(event)) { 3998 return FINISH_HANDLED; 3999 } 4000 return FORWARD; 4001 } 4002 } 4003 4004 /** 4005 * Performs synthesis of new input events from unhandled input events. 4006 */ 4007 final class SyntheticInputStage extends InputStage { 4008 private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler(); 4009 private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler(); 4010 private final SyntheticTouchNavigationHandler mTouchNavigation = 4011 new SyntheticTouchNavigationHandler(); 4012 4013 public SyntheticInputStage() { 4014 super(null); 4015 } 4016 4017 @Override 4018 protected int onProcess(QueuedInputEvent q) { 4019 q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED; 4020 if (q.mEvent instanceof MotionEvent) { 4021 final MotionEvent event = (MotionEvent)q.mEvent; 4022 final int source = event.getSource(); 4023 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 4024 mTrackball.process(event); 4025 return FINISH_HANDLED; 4026 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 4027 mJoystick.process(event); 4028 return FINISH_HANDLED; 4029 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 4030 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 4031 mTouchNavigation.process(event); 4032 return FINISH_HANDLED; 4033 } 4034 } 4035 return FORWARD; 4036 } 4037 4038 @Override 4039 protected void onDeliverToNext(QueuedInputEvent q) { 4040 if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) { 4041 // Cancel related synthetic events if any prior stage has handled the event. 4042 if (q.mEvent instanceof MotionEvent) { 4043 final MotionEvent event = (MotionEvent)q.mEvent; 4044 final int source = event.getSource(); 4045 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 4046 mTrackball.cancel(event); 4047 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 4048 mJoystick.cancel(event); 4049 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 4050 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 4051 mTouchNavigation.cancel(event); 4052 } 4053 } 4054 } 4055 super.onDeliverToNext(q); 4056 } 4057 } 4058 4059 /** 4060 * Creates dpad events from unhandled trackball movements. 4061 */ 4062 final class SyntheticTrackballHandler { 4063 private final TrackballAxis mX = new TrackballAxis(); 4064 private final TrackballAxis mY = new TrackballAxis(); 4065 private long mLastTime; 4066 4067 public void process(MotionEvent event) { 4068 // Translate the trackball event into DPAD keys and try to deliver those. 4069 long curTime = SystemClock.uptimeMillis(); 4070 if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) { 4071 // It has been too long since the last movement, 4072 // so restart at the beginning. 4073 mX.reset(0); 4074 mY.reset(0); 4075 mLastTime = curTime; 4076 } 4077 4078 final int action = event.getAction(); 4079 final int metaState = event.getMetaState(); 4080 switch (action) { 4081 case MotionEvent.ACTION_DOWN: 4082 mX.reset(2); 4083 mY.reset(2); 4084 enqueueInputEvent(new KeyEvent(curTime, curTime, 4085 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 4086 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4087 InputDevice.SOURCE_KEYBOARD)); 4088 break; 4089 case MotionEvent.ACTION_UP: 4090 mX.reset(2); 4091 mY.reset(2); 4092 enqueueInputEvent(new KeyEvent(curTime, curTime, 4093 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 4094 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4095 InputDevice.SOURCE_KEYBOARD)); 4096 break; 4097 } 4098 4099 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step=" 4100 + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration 4101 + " move=" + event.getX() 4102 + " / Y=" + mY.position + " step=" 4103 + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration 4104 + " move=" + event.getY()); 4105 final float xOff = mX.collect(event.getX(), event.getEventTime(), "X"); 4106 final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y"); 4107 4108 // Generate DPAD events based on the trackball movement. 4109 // We pick the axis that has moved the most as the direction of 4110 // the DPAD. When we generate DPAD events for one axis, then the 4111 // other axis is reset -- we don't want to perform DPAD jumps due 4112 // to slight movements in the trackball when making major movements 4113 // along the other axis. 4114 int keycode = 0; 4115 int movement = 0; 4116 float accel = 1; 4117 if (xOff > yOff) { 4118 movement = mX.generate(); 4119 if (movement != 0) { 4120 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 4121 : KeyEvent.KEYCODE_DPAD_LEFT; 4122 accel = mX.acceleration; 4123 mY.reset(2); 4124 } 4125 } else if (yOff > 0) { 4126 movement = mY.generate(); 4127 if (movement != 0) { 4128 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 4129 : KeyEvent.KEYCODE_DPAD_UP; 4130 accel = mY.acceleration; 4131 mX.reset(2); 4132 } 4133 } 4134 4135 if (keycode != 0) { 4136 if (movement < 0) movement = -movement; 4137 int accelMovement = (int)(movement * accel); 4138 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 4139 + " accelMovement=" + accelMovement 4140 + " accel=" + accel); 4141 if (accelMovement > movement) { 4142 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4143 + keycode); 4144 movement--; 4145 int repeatCount = accelMovement - movement; 4146 enqueueInputEvent(new KeyEvent(curTime, curTime, 4147 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 4148 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4149 InputDevice.SOURCE_KEYBOARD)); 4150 } 4151 while (movement > 0) { 4152 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4153 + keycode); 4154 movement--; 4155 curTime = SystemClock.uptimeMillis(); 4156 enqueueInputEvent(new KeyEvent(curTime, curTime, 4157 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 4158 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4159 InputDevice.SOURCE_KEYBOARD)); 4160 enqueueInputEvent(new KeyEvent(curTime, curTime, 4161 KeyEvent.ACTION_UP, keycode, 0, metaState, 4162 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4163 InputDevice.SOURCE_KEYBOARD)); 4164 } 4165 mLastTime = curTime; 4166 } 4167 } 4168 4169 public void cancel(MotionEvent event) { 4170 mLastTime = Integer.MIN_VALUE; 4171 4172 // If we reach this, we consumed a trackball event. 4173 // Because we will not translate the trackball event into a key event, 4174 // touch mode will not exit, so we exit touch mode here. 4175 if (mView != null && mAdded) { 4176 ensureTouchMode(false); 4177 } 4178 } 4179 } 4180 4181 /** 4182 * Maintains state information for a single trackball axis, generating 4183 * discrete (DPAD) movements based on raw trackball motion. 4184 */ 4185 static final class TrackballAxis { 4186 /** 4187 * The maximum amount of acceleration we will apply. 4188 */ 4189 static final float MAX_ACCELERATION = 20; 4190 4191 /** 4192 * The maximum amount of time (in milliseconds) between events in order 4193 * for us to consider the user to be doing fast trackball movements, 4194 * and thus apply an acceleration. 4195 */ 4196 static final long FAST_MOVE_TIME = 150; 4197 4198 /** 4199 * Scaling factor to the time (in milliseconds) between events to how 4200 * much to multiple/divide the current acceleration. When movement 4201 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4202 * FAST_MOVE_TIME it divides it. 4203 */ 4204 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4205 4206 static final float FIRST_MOVEMENT_THRESHOLD = 0.5f; 4207 static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f; 4208 static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f; 4209 4210 float position; 4211 float acceleration = 1; 4212 long lastMoveTime = 0; 4213 int step; 4214 int dir; 4215 int nonAccelMovement; 4216 4217 void reset(int _step) { 4218 position = 0; 4219 acceleration = 1; 4220 lastMoveTime = 0; 4221 step = _step; 4222 dir = 0; 4223 } 4224 4225 /** 4226 * Add trackball movement into the state. If the direction of movement 4227 * has been reversed, the state is reset before adding the 4228 * movement (so that you don't have to compensate for any previously 4229 * collected movement before see the result of the movement in the 4230 * new direction). 4231 * 4232 * @return Returns the absolute value of the amount of movement 4233 * collected so far. 4234 */ 4235 float collect(float off, long time, String axis) { 4236 long normTime; 4237 if (off > 0) { 4238 normTime = (long)(off * FAST_MOVE_TIME); 4239 if (dir < 0) { 4240 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4241 position = 0; 4242 step = 0; 4243 acceleration = 1; 4244 lastMoveTime = 0; 4245 } 4246 dir = 1; 4247 } else if (off < 0) { 4248 normTime = (long)((-off) * FAST_MOVE_TIME); 4249 if (dir > 0) { 4250 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4251 position = 0; 4252 step = 0; 4253 acceleration = 1; 4254 lastMoveTime = 0; 4255 } 4256 dir = -1; 4257 } else { 4258 normTime = 0; 4259 } 4260 4261 // The number of milliseconds between each movement that is 4262 // considered "normal" and will not result in any acceleration 4263 // or deceleration, scaled by the offset we have here. 4264 if (normTime > 0) { 4265 long delta = time - lastMoveTime; 4266 lastMoveTime = time; 4267 float acc = acceleration; 4268 if (delta < normTime) { 4269 // The user is scrolling rapidly, so increase acceleration. 4270 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4271 if (scale > 1) acc *= scale; 4272 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4273 + off + " normTime=" + normTime + " delta=" + delta 4274 + " scale=" + scale + " acc=" + acc); 4275 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4276 } else { 4277 // The user is scrolling slowly, so decrease acceleration. 4278 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4279 if (scale > 1) acc /= scale; 4280 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4281 + off + " normTime=" + normTime + " delta=" + delta 4282 + " scale=" + scale + " acc=" + acc); 4283 acceleration = acc > 1 ? acc : 1; 4284 } 4285 } 4286 position += off; 4287 return Math.abs(position); 4288 } 4289 4290 /** 4291 * Generate the number of discrete movement events appropriate for 4292 * the currently collected trackball movement. 4293 * 4294 * @return Returns the number of discrete movements, either positive 4295 * or negative, or 0 if there is not enough trackball movement yet 4296 * for a discrete movement. 4297 */ 4298 int generate() { 4299 int movement = 0; 4300 nonAccelMovement = 0; 4301 do { 4302 final int dir = position >= 0 ? 1 : -1; 4303 switch (step) { 4304 // If we are going to execute the first step, then we want 4305 // to do this as soon as possible instead of waiting for 4306 // a full movement, in order to make things look responsive. 4307 case 0: 4308 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) { 4309 return movement; 4310 } 4311 movement += dir; 4312 nonAccelMovement += dir; 4313 step = 1; 4314 break; 4315 // If we have generated the first movement, then we need 4316 // to wait for the second complete trackball motion before 4317 // generating the second discrete movement. 4318 case 1: 4319 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) { 4320 return movement; 4321 } 4322 movement += dir; 4323 nonAccelMovement += dir; 4324 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir; 4325 step = 2; 4326 break; 4327 // After the first two, we generate discrete movements 4328 // consistently with the trackball, applying an acceleration 4329 // if the trackball is moving quickly. This is a simple 4330 // acceleration on top of what we already compute based 4331 // on how quickly the wheel is being turned, to apply 4332 // a longer increasing acceleration to continuous movement 4333 // in one direction. 4334 default: 4335 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) { 4336 return movement; 4337 } 4338 movement += dir; 4339 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD; 4340 float acc = acceleration; 4341 acc *= 1.1f; 4342 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4343 break; 4344 } 4345 } while (true); 4346 } 4347 } 4348 4349 /** 4350 * Creates dpad events from unhandled joystick movements. 4351 */ 4352 final class SyntheticJoystickHandler extends Handler { 4353 private final static String TAG = "SyntheticJoystickHandler"; 4354 private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1; 4355 private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2; 4356 4357 private int mLastXDirection; 4358 private int mLastYDirection; 4359 private int mLastXKeyCode; 4360 private int mLastYKeyCode; 4361 4362 public SyntheticJoystickHandler() { 4363 super(true); 4364 } 4365 4366 @Override 4367 public void handleMessage(Message msg) { 4368 switch (msg.what) { 4369 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT: 4370 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: { 4371 KeyEvent oldEvent = (KeyEvent)msg.obj; 4372 KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent, 4373 SystemClock.uptimeMillis(), 4374 oldEvent.getRepeatCount() + 1); 4375 if (mAttachInfo.mHasWindowFocus) { 4376 enqueueInputEvent(e); 4377 Message m = obtainMessage(msg.what, e); 4378 m.setAsynchronous(true); 4379 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay()); 4380 } 4381 } break; 4382 } 4383 } 4384 4385 public void process(MotionEvent event) { 4386 switch(event.getActionMasked()) { 4387 case MotionEvent.ACTION_CANCEL: 4388 cancel(event); 4389 break; 4390 case MotionEvent.ACTION_MOVE: 4391 update(event, true); 4392 break; 4393 default: 4394 Log.w(TAG, "Unexpected action: " + event.getActionMasked()); 4395 } 4396 } 4397 4398 private void cancel(MotionEvent event) { 4399 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4400 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4401 update(event, false); 4402 } 4403 4404 private void update(MotionEvent event, boolean synthesizeNewKeys) { 4405 final long time = event.getEventTime(); 4406 final int metaState = event.getMetaState(); 4407 final int deviceId = event.getDeviceId(); 4408 final int source = event.getSource(); 4409 4410 int xDirection = joystickAxisValueToDirection( 4411 event.getAxisValue(MotionEvent.AXIS_HAT_X)); 4412 if (xDirection == 0) { 4413 xDirection = joystickAxisValueToDirection(event.getX()); 4414 } 4415 4416 int yDirection = joystickAxisValueToDirection( 4417 event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 4418 if (yDirection == 0) { 4419 yDirection = joystickAxisValueToDirection(event.getY()); 4420 } 4421 4422 if (xDirection != mLastXDirection) { 4423 if (mLastXKeyCode != 0) { 4424 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4425 enqueueInputEvent(new KeyEvent(time, time, 4426 KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState, 4427 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4428 mLastXKeyCode = 0; 4429 } 4430 4431 mLastXDirection = xDirection; 4432 4433 if (xDirection != 0 && synthesizeNewKeys) { 4434 mLastXKeyCode = xDirection > 0 4435 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 4436 final KeyEvent e = new KeyEvent(time, time, 4437 KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState, 4438 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4439 enqueueInputEvent(e); 4440 Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e); 4441 m.setAsynchronous(true); 4442 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4443 } 4444 } 4445 4446 if (yDirection != mLastYDirection) { 4447 if (mLastYKeyCode != 0) { 4448 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4449 enqueueInputEvent(new KeyEvent(time, time, 4450 KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState, 4451 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4452 mLastYKeyCode = 0; 4453 } 4454 4455 mLastYDirection = yDirection; 4456 4457 if (yDirection != 0 && synthesizeNewKeys) { 4458 mLastYKeyCode = yDirection > 0 4459 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 4460 final KeyEvent e = new KeyEvent(time, time, 4461 KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState, 4462 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4463 enqueueInputEvent(e); 4464 Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e); 4465 m.setAsynchronous(true); 4466 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4467 } 4468 } 4469 } 4470 4471 private int joystickAxisValueToDirection(float value) { 4472 if (value >= 0.5f) { 4473 return 1; 4474 } else if (value <= -0.5f) { 4475 return -1; 4476 } else { 4477 return 0; 4478 } 4479 } 4480 } 4481 4482 /** 4483 * Creates dpad events from unhandled touch navigation movements. 4484 */ 4485 final class SyntheticTouchNavigationHandler extends Handler { 4486 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler"; 4487 private static final boolean LOCAL_DEBUG = false; 4488 4489 // Assumed nominal width and height in millimeters of a touch navigation pad, 4490 // if no resolution information is available from the input system. 4491 private static final float DEFAULT_WIDTH_MILLIMETERS = 48; 4492 private static final float DEFAULT_HEIGHT_MILLIMETERS = 48; 4493 4494 /* TODO: These constants should eventually be moved to ViewConfiguration. */ 4495 4496 // The nominal distance traveled to move by one unit. 4497 private static final int TICK_DISTANCE_MILLIMETERS = 12; 4498 4499 // Minimum and maximum fling velocity in ticks per second. 4500 // The minimum velocity should be set such that we perform enough ticks per 4501 // second that the fling appears to be fluid. For example, if we set the minimum 4502 // to 2 ticks per second, then there may be up to half a second delay between the next 4503 // to last and last ticks which is noticeably discrete and jerky. This value should 4504 // probably not be set to anything less than about 4. 4505 // If fling accuracy is a problem then consider tuning the tick distance instead. 4506 private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f; 4507 private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f; 4508 4509 // Fling velocity decay factor applied after each new key is emitted. 4510 // This parameter controls the deceleration and overall duration of the fling. 4511 // The fling stops automatically when its velocity drops below the minimum 4512 // fling velocity defined above. 4513 private static final float FLING_TICK_DECAY = 0.8f; 4514 4515 /* The input device that we are tracking. */ 4516 4517 private int mCurrentDeviceId = -1; 4518 private int mCurrentSource; 4519 private boolean mCurrentDeviceSupported; 4520 4521 /* Configuration for the current input device. */ 4522 4523 // The scaled tick distance. A movement of this amount should generally translate 4524 // into a single dpad event in a given direction. 4525 private float mConfigTickDistance; 4526 4527 // The minimum and maximum scaled fling velocity. 4528 private float mConfigMinFlingVelocity; 4529 private float mConfigMaxFlingVelocity; 4530 4531 /* Tracking state. */ 4532 4533 // The velocity tracker for detecting flings. 4534 private VelocityTracker mVelocityTracker; 4535 4536 // The active pointer id, or -1 if none. 4537 private int mActivePointerId = -1; 4538 4539 // Location where tracking started. 4540 private float mStartX; 4541 private float mStartY; 4542 4543 // Most recently observed position. 4544 private float mLastX; 4545 private float mLastY; 4546 4547 // Accumulated movement delta since the last direction key was sent. 4548 private float mAccumulatedX; 4549 private float mAccumulatedY; 4550 4551 // Set to true if any movement was delivered to the app. 4552 // Implies that tap slop was exceeded. 4553 private boolean mConsumedMovement; 4554 4555 // The most recently sent key down event. 4556 // The keycode remains set until the direction changes or a fling ends 4557 // so that repeated key events may be generated as required. 4558 private long mPendingKeyDownTime; 4559 private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4560 private int mPendingKeyRepeatCount; 4561 private int mPendingKeyMetaState; 4562 4563 // The current fling velocity while a fling is in progress. 4564 private boolean mFlinging; 4565 private float mFlingVelocity; 4566 4567 public SyntheticTouchNavigationHandler() { 4568 super(true); 4569 } 4570 4571 public void process(MotionEvent event) { 4572 // Update the current device information. 4573 final long time = event.getEventTime(); 4574 final int deviceId = event.getDeviceId(); 4575 final int source = event.getSource(); 4576 if (mCurrentDeviceId != deviceId || mCurrentSource != source) { 4577 finishKeys(time); 4578 finishTracking(time); 4579 mCurrentDeviceId = deviceId; 4580 mCurrentSource = source; 4581 mCurrentDeviceSupported = false; 4582 InputDevice device = event.getDevice(); 4583 if (device != null) { 4584 // In order to support an input device, we must know certain 4585 // characteristics about it, such as its size and resolution. 4586 InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X); 4587 InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y); 4588 if (xRange != null && yRange != null) { 4589 mCurrentDeviceSupported = true; 4590 4591 // Infer the resolution if it not actually known. 4592 float xRes = xRange.getResolution(); 4593 if (xRes <= 0) { 4594 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS; 4595 } 4596 float yRes = yRange.getResolution(); 4597 if (yRes <= 0) { 4598 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS; 4599 } 4600 float nominalRes = (xRes + yRes) * 0.5f; 4601 4602 // Precompute all of the configuration thresholds we will need. 4603 mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes; 4604 mConfigMinFlingVelocity = 4605 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4606 mConfigMaxFlingVelocity = 4607 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4608 4609 if (LOCAL_DEBUG) { 4610 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId 4611 + " (" + Integer.toHexString(mCurrentSource) + "): " 4612 + ", mConfigTickDistance=" + mConfigTickDistance 4613 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity 4614 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity); 4615 } 4616 } 4617 } 4618 } 4619 if (!mCurrentDeviceSupported) { 4620 return; 4621 } 4622 4623 // Handle the event. 4624 final int action = event.getActionMasked(); 4625 switch (action) { 4626 case MotionEvent.ACTION_DOWN: { 4627 boolean caughtFling = mFlinging; 4628 finishKeys(time); 4629 finishTracking(time); 4630 mActivePointerId = event.getPointerId(0); 4631 mVelocityTracker = VelocityTracker.obtain(); 4632 mVelocityTracker.addMovement(event); 4633 mStartX = event.getX(); 4634 mStartY = event.getY(); 4635 mLastX = mStartX; 4636 mLastY = mStartY; 4637 mAccumulatedX = 0; 4638 mAccumulatedY = 0; 4639 4640 // If we caught a fling, then pretend that the tap slop has already 4641 // been exceeded to suppress taps whose only purpose is to stop the fling. 4642 mConsumedMovement = caughtFling; 4643 break; 4644 } 4645 4646 case MotionEvent.ACTION_MOVE: 4647 case MotionEvent.ACTION_UP: { 4648 if (mActivePointerId < 0) { 4649 break; 4650 } 4651 final int index = event.findPointerIndex(mActivePointerId); 4652 if (index < 0) { 4653 finishKeys(time); 4654 finishTracking(time); 4655 break; 4656 } 4657 4658 mVelocityTracker.addMovement(event); 4659 final float x = event.getX(index); 4660 final float y = event.getY(index); 4661 mAccumulatedX += x - mLastX; 4662 mAccumulatedY += y - mLastY; 4663 mLastX = x; 4664 mLastY = y; 4665 4666 // Consume any accumulated movement so far. 4667 final int metaState = event.getMetaState(); 4668 consumeAccumulatedMovement(time, metaState); 4669 4670 // Detect taps and flings. 4671 if (action == MotionEvent.ACTION_UP) { 4672 if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4673 // It might be a fling. 4674 mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity); 4675 final float vx = mVelocityTracker.getXVelocity(mActivePointerId); 4676 final float vy = mVelocityTracker.getYVelocity(mActivePointerId); 4677 if (!startFling(time, vx, vy)) { 4678 finishKeys(time); 4679 } 4680 } 4681 finishTracking(time); 4682 } 4683 break; 4684 } 4685 4686 case MotionEvent.ACTION_CANCEL: { 4687 finishKeys(time); 4688 finishTracking(time); 4689 break; 4690 } 4691 } 4692 } 4693 4694 public void cancel(MotionEvent event) { 4695 if (mCurrentDeviceId == event.getDeviceId() 4696 && mCurrentSource == event.getSource()) { 4697 final long time = event.getEventTime(); 4698 finishKeys(time); 4699 finishTracking(time); 4700 } 4701 } 4702 4703 private void finishKeys(long time) { 4704 cancelFling(); 4705 sendKeyUp(time); 4706 } 4707 4708 private void finishTracking(long time) { 4709 if (mActivePointerId >= 0) { 4710 mActivePointerId = -1; 4711 mVelocityTracker.recycle(); 4712 mVelocityTracker = null; 4713 } 4714 } 4715 4716 private void consumeAccumulatedMovement(long time, int metaState) { 4717 final float absX = Math.abs(mAccumulatedX); 4718 final float absY = Math.abs(mAccumulatedY); 4719 if (absX >= absY) { 4720 if (absX >= mConfigTickDistance) { 4721 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX, 4722 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT); 4723 mAccumulatedY = 0; 4724 mConsumedMovement = true; 4725 } 4726 } else { 4727 if (absY >= mConfigTickDistance) { 4728 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY, 4729 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN); 4730 mAccumulatedX = 0; 4731 mConsumedMovement = true; 4732 } 4733 } 4734 } 4735 4736 private float consumeAccumulatedMovement(long time, int metaState, 4737 float accumulator, int negativeKeyCode, int positiveKeyCode) { 4738 while (accumulator <= -mConfigTickDistance) { 4739 sendKeyDownOrRepeat(time, negativeKeyCode, metaState); 4740 accumulator += mConfigTickDistance; 4741 } 4742 while (accumulator >= mConfigTickDistance) { 4743 sendKeyDownOrRepeat(time, positiveKeyCode, metaState); 4744 accumulator -= mConfigTickDistance; 4745 } 4746 return accumulator; 4747 } 4748 4749 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) { 4750 if (mPendingKeyCode != keyCode) { 4751 sendKeyUp(time); 4752 mPendingKeyDownTime = time; 4753 mPendingKeyCode = keyCode; 4754 mPendingKeyRepeatCount = 0; 4755 } else { 4756 mPendingKeyRepeatCount += 1; 4757 } 4758 mPendingKeyMetaState = metaState; 4759 4760 // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1 4761 // but it doesn't quite make sense when simulating the events in this way. 4762 if (LOCAL_DEBUG) { 4763 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode 4764 + ", repeatCount=" + mPendingKeyRepeatCount 4765 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4766 } 4767 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4768 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount, 4769 mPendingKeyMetaState, mCurrentDeviceId, 4770 KeyEvent.FLAG_FALLBACK, mCurrentSource)); 4771 } 4772 4773 private void sendKeyUp(long time) { 4774 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4775 if (LOCAL_DEBUG) { 4776 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode 4777 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4778 } 4779 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4780 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState, 4781 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK, 4782 mCurrentSource)); 4783 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4784 } 4785 } 4786 4787 private boolean startFling(long time, float vx, float vy) { 4788 if (LOCAL_DEBUG) { 4789 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy 4790 + ", min=" + mConfigMinFlingVelocity); 4791 } 4792 4793 // Flings must be oriented in the same direction as the preceding movements. 4794 switch (mPendingKeyCode) { 4795 case KeyEvent.KEYCODE_DPAD_LEFT: 4796 if (-vx >= mConfigMinFlingVelocity 4797 && Math.abs(vy) < mConfigMinFlingVelocity) { 4798 mFlingVelocity = -vx; 4799 break; 4800 } 4801 return false; 4802 4803 case KeyEvent.KEYCODE_DPAD_RIGHT: 4804 if (vx >= mConfigMinFlingVelocity 4805 && Math.abs(vy) < mConfigMinFlingVelocity) { 4806 mFlingVelocity = vx; 4807 break; 4808 } 4809 return false; 4810 4811 case KeyEvent.KEYCODE_DPAD_UP: 4812 if (-vy >= mConfigMinFlingVelocity 4813 && Math.abs(vx) < mConfigMinFlingVelocity) { 4814 mFlingVelocity = -vy; 4815 break; 4816 } 4817 return false; 4818 4819 case KeyEvent.KEYCODE_DPAD_DOWN: 4820 if (vy >= mConfigMinFlingVelocity 4821 && Math.abs(vx) < mConfigMinFlingVelocity) { 4822 mFlingVelocity = vy; 4823 break; 4824 } 4825 return false; 4826 } 4827 4828 // Post the first fling event. 4829 mFlinging = postFling(time); 4830 return mFlinging; 4831 } 4832 4833 private boolean postFling(long time) { 4834 // The idea here is to estimate the time when the pointer would have 4835 // traveled one tick distance unit given the current fling velocity. 4836 // This effect creates continuity of motion. 4837 if (mFlingVelocity >= mConfigMinFlingVelocity) { 4838 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000); 4839 postAtTime(mFlingRunnable, time + delay); 4840 if (LOCAL_DEBUG) { 4841 Log.d(LOCAL_TAG, "Posted fling: velocity=" 4842 + mFlingVelocity + ", delay=" + delay 4843 + ", keyCode=" + mPendingKeyCode); 4844 } 4845 return true; 4846 } 4847 return false; 4848 } 4849 4850 private void cancelFling() { 4851 if (mFlinging) { 4852 removeCallbacks(mFlingRunnable); 4853 mFlinging = false; 4854 } 4855 } 4856 4857 private final Runnable mFlingRunnable = new Runnable() { 4858 @Override 4859 public void run() { 4860 final long time = SystemClock.uptimeMillis(); 4861 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState); 4862 mFlingVelocity *= FLING_TICK_DECAY; 4863 if (!postFling(time)) { 4864 mFlinging = false; 4865 finishKeys(time); 4866 } 4867 } 4868 }; 4869 } 4870 4871 /** 4872 * Returns true if the key is used for keyboard navigation. 4873 * @param keyEvent The key event. 4874 * @return True if the key is used for keyboard navigation. 4875 */ 4876 private static boolean isNavigationKey(KeyEvent keyEvent) { 4877 switch (keyEvent.getKeyCode()) { 4878 case KeyEvent.KEYCODE_DPAD_LEFT: 4879 case KeyEvent.KEYCODE_DPAD_RIGHT: 4880 case KeyEvent.KEYCODE_DPAD_UP: 4881 case KeyEvent.KEYCODE_DPAD_DOWN: 4882 case KeyEvent.KEYCODE_DPAD_CENTER: 4883 case KeyEvent.KEYCODE_PAGE_UP: 4884 case KeyEvent.KEYCODE_PAGE_DOWN: 4885 case KeyEvent.KEYCODE_MOVE_HOME: 4886 case KeyEvent.KEYCODE_MOVE_END: 4887 case KeyEvent.KEYCODE_TAB: 4888 case KeyEvent.KEYCODE_SPACE: 4889 case KeyEvent.KEYCODE_ENTER: 4890 return true; 4891 } 4892 return false; 4893 } 4894 4895 /** 4896 * Returns true if the key is used for typing. 4897 * @param keyEvent The key event. 4898 * @return True if the key is used for typing. 4899 */ 4900 private static boolean isTypingKey(KeyEvent keyEvent) { 4901 return keyEvent.getUnicodeChar() > 0; 4902 } 4903 4904 /** 4905 * See if the key event means we should leave touch mode (and leave touch mode if so). 4906 * @param event The key event. 4907 * @return Whether this key event should be consumed (meaning the act of 4908 * leaving touch mode alone is considered the event). 4909 */ 4910 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 4911 // Only relevant in touch mode. 4912 if (!mAttachInfo.mInTouchMode) { 4913 return false; 4914 } 4915 4916 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 4917 final int action = event.getAction(); 4918 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 4919 return false; 4920 } 4921 4922 // Don't leave touch mode if the IME told us not to. 4923 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 4924 return false; 4925 } 4926 4927 // If the key can be used for keyboard navigation then leave touch mode 4928 // and select a focused view if needed (in ensureTouchMode). 4929 // When a new focused view is selected, we consume the navigation key because 4930 // navigation doesn't make much sense unless a view already has focus so 4931 // the key's purpose is to set focus. 4932 if (isNavigationKey(event)) { 4933 return ensureTouchMode(false); 4934 } 4935 4936 // If the key can be used for typing then leave touch mode 4937 // and select a focused view if needed (in ensureTouchMode). 4938 // Always allow the view to process the typing key. 4939 if (isTypingKey(event)) { 4940 ensureTouchMode(false); 4941 return false; 4942 } 4943 4944 return false; 4945 } 4946 4947 /* drag/drop */ 4948 void setLocalDragState(Object obj) { 4949 mLocalDragState = obj; 4950 } 4951 4952 private void handleDragEvent(DragEvent event) { 4953 // From the root, only drag start/end/location are dispatched. entered/exited 4954 // are determined and dispatched by the viewgroup hierarchy, who then report 4955 // that back here for ultimate reporting back to the framework. 4956 if (mView != null && mAdded) { 4957 final int what = event.mAction; 4958 4959 if (what == DragEvent.ACTION_DRAG_EXITED) { 4960 // A direct EXITED event means that the window manager knows we've just crossed 4961 // a window boundary, so the current drag target within this one must have 4962 // just been exited. Send it the usual notifications and then we're done 4963 // for now. 4964 mView.dispatchDragEvent(event); 4965 } else { 4966 // Cache the drag description when the operation starts, then fill it in 4967 // on subsequent calls as a convenience 4968 if (what == DragEvent.ACTION_DRAG_STARTED) { 4969 mCurrentDragView = null; // Start the current-recipient tracking 4970 mDragDescription = event.mClipDescription; 4971 } else { 4972 event.mClipDescription = mDragDescription; 4973 } 4974 4975 // For events with a [screen] location, translate into window coordinates 4976 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 4977 mDragPoint.set(event.mX, event.mY); 4978 if (mTranslator != null) { 4979 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 4980 } 4981 4982 if (mCurScrollY != 0) { 4983 mDragPoint.offset(0, mCurScrollY); 4984 } 4985 4986 event.mX = mDragPoint.x; 4987 event.mY = mDragPoint.y; 4988 } 4989 4990 // Remember who the current drag target is pre-dispatch 4991 final View prevDragView = mCurrentDragView; 4992 4993 // Now dispatch the drag/drop event 4994 boolean result = mView.dispatchDragEvent(event); 4995 4996 // If we changed apparent drag target, tell the OS about it 4997 if (prevDragView != mCurrentDragView) { 4998 try { 4999 if (prevDragView != null) { 5000 mWindowSession.dragRecipientExited(mWindow); 5001 } 5002 if (mCurrentDragView != null) { 5003 mWindowSession.dragRecipientEntered(mWindow); 5004 } 5005 } catch (RemoteException e) { 5006 Slog.e(TAG, "Unable to note drag target change"); 5007 } 5008 } 5009 5010 // Report the drop result when we're done 5011 if (what == DragEvent.ACTION_DROP) { 5012 mDragDescription = null; 5013 try { 5014 Log.i(TAG, "Reporting drop result: " + result); 5015 mWindowSession.reportDropResult(mWindow, result); 5016 } catch (RemoteException e) { 5017 Log.e(TAG, "Unable to report drop result"); 5018 } 5019 } 5020 5021 // When the drag operation ends, release any local state object 5022 // that may have been in use 5023 if (what == DragEvent.ACTION_DRAG_ENDED) { 5024 setLocalDragState(null); 5025 } 5026 } 5027 } 5028 event.recycle(); 5029 } 5030 5031 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 5032 if (mSeq != args.seq) { 5033 // The sequence has changed, so we need to update our value and make 5034 // sure to do a traversal afterward so the window manager is given our 5035 // most recent data. 5036 mSeq = args.seq; 5037 mAttachInfo.mForceReportNewAttributes = true; 5038 scheduleTraversals(); 5039 } 5040 if (mView == null) return; 5041 if (args.localChanges != 0) { 5042 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 5043 } 5044 if (mAttachInfo != null) { 5045 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 5046 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 5047 mAttachInfo.mGlobalSystemUiVisibility = visibility; 5048 mView.dispatchSystemUiVisibilityChanged(visibility); 5049 } 5050 } 5051 } 5052 5053 public void handleDispatchDoneAnimating() { 5054 if (mWindowsAnimating) { 5055 mWindowsAnimating = false; 5056 if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded) { 5057 scheduleTraversals(); 5058 } 5059 } 5060 } 5061 5062 public void getLastTouchPoint(Point outLocation) { 5063 outLocation.x = (int) mLastTouchPoint.x; 5064 outLocation.y = (int) mLastTouchPoint.y; 5065 } 5066 5067 public void setDragFocus(View newDragTarget) { 5068 if (mCurrentDragView != newDragTarget) { 5069 mCurrentDragView = newDragTarget; 5070 } 5071 } 5072 5073 private AudioManager getAudioManager() { 5074 if (mView == null) { 5075 throw new IllegalStateException("getAudioManager called when there is no mView"); 5076 } 5077 if (mAudioManager == null) { 5078 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 5079 } 5080 return mAudioManager; 5081 } 5082 5083 public AccessibilityInteractionController getAccessibilityInteractionController() { 5084 if (mView == null) { 5085 throw new IllegalStateException("getAccessibilityInteractionController" 5086 + " called when there is no mView"); 5087 } 5088 if (mAccessibilityInteractionController == null) { 5089 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 5090 } 5091 return mAccessibilityInteractionController; 5092 } 5093 5094 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 5095 boolean insetsPending) throws RemoteException { 5096 5097 float appScale = mAttachInfo.mApplicationScale; 5098 boolean restore = false; 5099 if (params != null && mTranslator != null) { 5100 restore = true; 5101 params.backup(); 5102 mTranslator.translateWindowLayout(params); 5103 } 5104 if (params != null) { 5105 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 5106 } 5107 mPendingConfiguration.seq = 0; 5108 //Log.d(TAG, ">>>>>> CALLING relayout"); 5109 if (params != null && mOrigWindowType != params.type) { 5110 // For compatibility with old apps, don't crash here. 5111 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 5112 Slog.w(TAG, "Window type can not be changed after " 5113 + "the window is added; ignoring change of " + mView); 5114 params.type = mOrigWindowType; 5115 } 5116 } 5117 int relayoutResult = mWindowSession.relayout( 5118 mWindow, mSeq, params, 5119 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 5120 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 5121 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 5122 mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets, 5123 mPendingConfiguration, mSurface); 5124 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 5125 if (restore) { 5126 params.restore(); 5127 } 5128 5129 if (mTranslator != null) { 5130 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 5131 mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets); 5132 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 5133 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 5134 } 5135 return relayoutResult; 5136 } 5137 5138 /** 5139 * {@inheritDoc} 5140 */ 5141 @Override 5142 public void playSoundEffect(int effectId) { 5143 checkThread(); 5144 5145 if (mMediaDisabled) { 5146 return; 5147 } 5148 5149 try { 5150 final AudioManager audioManager = getAudioManager(); 5151 5152 switch (effectId) { 5153 case SoundEffectConstants.CLICK: 5154 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 5155 return; 5156 case SoundEffectConstants.NAVIGATION_DOWN: 5157 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 5158 return; 5159 case SoundEffectConstants.NAVIGATION_LEFT: 5160 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 5161 return; 5162 case SoundEffectConstants.NAVIGATION_RIGHT: 5163 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 5164 return; 5165 case SoundEffectConstants.NAVIGATION_UP: 5166 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 5167 return; 5168 default: 5169 throw new IllegalArgumentException("unknown effect id " + effectId + 5170 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 5171 } 5172 } catch (IllegalStateException e) { 5173 // Exception thrown by getAudioManager() when mView is null 5174 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 5175 e.printStackTrace(); 5176 } 5177 } 5178 5179 /** 5180 * {@inheritDoc} 5181 */ 5182 @Override 5183 public boolean performHapticFeedback(int effectId, boolean always) { 5184 try { 5185 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 5186 } catch (RemoteException e) { 5187 return false; 5188 } 5189 } 5190 5191 /** 5192 * {@inheritDoc} 5193 */ 5194 @Override 5195 public View focusSearch(View focused, int direction) { 5196 checkThread(); 5197 if (!(mView instanceof ViewGroup)) { 5198 return null; 5199 } 5200 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 5201 } 5202 5203 public void debug() { 5204 mView.debug(); 5205 } 5206 5207 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 5208 String innerPrefix = prefix + " "; 5209 writer.print(prefix); writer.println("ViewRoot:"); 5210 writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded); 5211 writer.print(" mRemoved="); writer.println(mRemoved); 5212 writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled="); 5213 writer.println(mConsumeBatchedInputScheduled); 5214 writer.print(innerPrefix); writer.print("mPendingInputEventCount="); 5215 writer.println(mPendingInputEventCount); 5216 writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled="); 5217 writer.println(mProcessInputEventsScheduled); 5218 writer.print(innerPrefix); writer.print("mTraversalScheduled="); 5219 writer.print(mTraversalScheduled); 5220 if (mTraversalScheduled) { 5221 writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")"); 5222 } else { 5223 writer.println(); 5224 } 5225 mFirstInputStage.dump(innerPrefix, writer); 5226 5227 mChoreographer.dump(prefix, writer); 5228 5229 writer.print(prefix); writer.println("View Hierarchy:"); 5230 dumpViewHierarchy(innerPrefix, writer, mView); 5231 } 5232 5233 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) { 5234 writer.print(prefix); 5235 if (view == null) { 5236 writer.println("null"); 5237 return; 5238 } 5239 writer.println(view.toString()); 5240 if (!(view instanceof ViewGroup)) { 5241 return; 5242 } 5243 ViewGroup grp = (ViewGroup)view; 5244 final int N = grp.getChildCount(); 5245 if (N <= 0) { 5246 return; 5247 } 5248 prefix = prefix + " "; 5249 for (int i=0; i<N; i++) { 5250 dumpViewHierarchy(prefix, writer, grp.getChildAt(i)); 5251 } 5252 } 5253 5254 public void dumpGfxInfo(int[] info) { 5255 info[0] = info[1] = 0; 5256 if (mView != null) { 5257 getGfxInfo(mView, info); 5258 } 5259 } 5260 5261 private static void getGfxInfo(View view, int[] info) { 5262 RenderNode renderNode = view.mRenderNode; 5263 info[0]++; 5264 if (renderNode != null) { 5265 info[1] += 0; /* TODO: Memory used by RenderNodes (properties + DisplayLists) */ 5266 } 5267 5268 if (view instanceof ViewGroup) { 5269 ViewGroup group = (ViewGroup) view; 5270 5271 int count = group.getChildCount(); 5272 for (int i = 0; i < count; i++) { 5273 getGfxInfo(group.getChildAt(i), info); 5274 } 5275 } 5276 } 5277 5278 /** 5279 * @param immediate True, do now if not in traversal. False, put on queue and do later. 5280 * @return True, request has been queued. False, request has been completed. 5281 */ 5282 boolean die(boolean immediate) { 5283 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 5284 // done by dispatchDetachedFromWindow will cause havoc on return. 5285 if (immediate && !mIsInTraversal) { 5286 doDie(); 5287 return false; 5288 } 5289 5290 if (!mIsDrawing) { 5291 destroyHardwareRenderer(); 5292 } else { 5293 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 5294 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 5295 } 5296 mHandler.sendEmptyMessage(MSG_DIE); 5297 return true; 5298 } 5299 5300 void doDie() { 5301 checkThread(); 5302 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 5303 synchronized (this) { 5304 if (mRemoved) { 5305 return; 5306 } 5307 mRemoved = true; 5308 if (mAdded) { 5309 dispatchDetachedFromWindow(); 5310 } 5311 5312 if (mAdded && !mFirst) { 5313 destroyHardwareRenderer(); 5314 5315 if (mView != null) { 5316 int viewVisibility = mView.getVisibility(); 5317 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 5318 if (mWindowAttributesChanged || viewVisibilityChanged) { 5319 // If layout params have been changed, first give them 5320 // to the window manager to make sure it has the correct 5321 // animation info. 5322 try { 5323 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 5324 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 5325 mWindowSession.finishDrawing(mWindow); 5326 } 5327 } catch (RemoteException e) { 5328 } 5329 } 5330 5331 mSurface.release(); 5332 } 5333 } 5334 5335 mAdded = false; 5336 } 5337 WindowManagerGlobal.getInstance().doRemoveView(this); 5338 } 5339 5340 public void requestUpdateConfiguration(Configuration config) { 5341 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 5342 mHandler.sendMessage(msg); 5343 } 5344 5345 public void loadSystemProperties() { 5346 mHandler.post(new Runnable() { 5347 @Override 5348 public void run() { 5349 // Profiling 5350 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false); 5351 profileRendering(mAttachInfo.mHasWindowFocus); 5352 5353 // Media (used by sound effects) 5354 mMediaDisabled = SystemProperties.getBoolean(PROPERTY_MEDIA_DISABLED, false); 5355 5356 // Hardware rendering 5357 if (mAttachInfo.mHardwareRenderer != null) { 5358 if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) { 5359 invalidate(); 5360 } 5361 } 5362 5363 // Layout debugging 5364 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false); 5365 if (layout != mAttachInfo.mDebugLayout) { 5366 mAttachInfo.mDebugLayout = layout; 5367 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 5368 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 5369 } 5370 } 5371 } 5372 }); 5373 } 5374 5375 private void destroyHardwareRenderer() { 5376 AttachInfo attachInfo = mAttachInfo; 5377 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 5378 5379 if (hardwareRenderer != null) { 5380 if (mView != null) { 5381 hardwareRenderer.destroyHardwareResources(mView); 5382 } 5383 hardwareRenderer.destroy(true); 5384 hardwareRenderer.setRequested(false); 5385 5386 attachInfo.mHardwareRenderer = null; 5387 attachInfo.mHardwareAccelerated = false; 5388 } 5389 } 5390 5391 public void dispatchFinishInputConnection(InputConnection connection) { 5392 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 5393 mHandler.sendMessage(msg); 5394 } 5395 5396 public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets, 5397 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 5398 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 5399 + " contentInsets=" + contentInsets.toShortString() 5400 + " visibleInsets=" + visibleInsets.toShortString() 5401 + " reportDraw=" + reportDraw); 5402 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 5403 if (mTranslator != null) { 5404 mTranslator.translateRectInScreenToAppWindow(frame); 5405 mTranslator.translateRectInScreenToAppWindow(overscanInsets); 5406 mTranslator.translateRectInScreenToAppWindow(contentInsets); 5407 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 5408 } 5409 SomeArgs args = SomeArgs.obtain(); 5410 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 5411 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 5412 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 5413 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 5414 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 5415 args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets; 5416 msg.obj = args; 5417 mHandler.sendMessage(msg); 5418 } 5419 5420 public void dispatchMoved(int newX, int newY) { 5421 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 5422 if (mTranslator != null) { 5423 PointF point = new PointF(newX, newY); 5424 mTranslator.translatePointInScreenToAppWindow(point); 5425 newX = (int) (point.x + 0.5); 5426 newY = (int) (point.y + 0.5); 5427 } 5428 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 5429 mHandler.sendMessage(msg); 5430 } 5431 5432 /** 5433 * Represents a pending input event that is waiting in a queue. 5434 * 5435 * Input events are processed in serial order by the timestamp specified by 5436 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 5437 * one input event to the application at a time and waits for the application 5438 * to finish handling it before delivering the next one. 5439 * 5440 * However, because the application or IME can synthesize and inject multiple 5441 * key events at a time without going through the input dispatcher, we end up 5442 * needing a queue on the application's side. 5443 */ 5444 private static final class QueuedInputEvent { 5445 public static final int FLAG_DELIVER_POST_IME = 1 << 0; 5446 public static final int FLAG_DEFERRED = 1 << 1; 5447 public static final int FLAG_FINISHED = 1 << 2; 5448 public static final int FLAG_FINISHED_HANDLED = 1 << 3; 5449 public static final int FLAG_RESYNTHESIZED = 1 << 4; 5450 5451 public QueuedInputEvent mNext; 5452 5453 public InputEvent mEvent; 5454 public InputEventReceiver mReceiver; 5455 public int mFlags; 5456 5457 public boolean shouldSkipIme() { 5458 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) { 5459 return true; 5460 } 5461 return mEvent instanceof MotionEvent 5462 && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER); 5463 } 5464 } 5465 5466 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 5467 InputEventReceiver receiver, int flags) { 5468 QueuedInputEvent q = mQueuedInputEventPool; 5469 if (q != null) { 5470 mQueuedInputEventPoolSize -= 1; 5471 mQueuedInputEventPool = q.mNext; 5472 q.mNext = null; 5473 } else { 5474 q = new QueuedInputEvent(); 5475 } 5476 5477 q.mEvent = event; 5478 q.mReceiver = receiver; 5479 q.mFlags = flags; 5480 return q; 5481 } 5482 5483 private void recycleQueuedInputEvent(QueuedInputEvent q) { 5484 q.mEvent = null; 5485 q.mReceiver = null; 5486 5487 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 5488 mQueuedInputEventPoolSize += 1; 5489 q.mNext = mQueuedInputEventPool; 5490 mQueuedInputEventPool = q; 5491 } 5492 } 5493 5494 void enqueueInputEvent(InputEvent event) { 5495 enqueueInputEvent(event, null, 0, false); 5496 } 5497 5498 void enqueueInputEvent(InputEvent event, 5499 InputEventReceiver receiver, int flags, boolean processImmediately) { 5500 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 5501 5502 // Always enqueue the input event in order, regardless of its time stamp. 5503 // We do this because the application or the IME may inject key events 5504 // in response to touch events and we want to ensure that the injected keys 5505 // are processed in the order they were received and we cannot trust that 5506 // the time stamp of injected events are monotonic. 5507 QueuedInputEvent last = mPendingInputEventTail; 5508 if (last == null) { 5509 mPendingInputEventHead = q; 5510 mPendingInputEventTail = q; 5511 } else { 5512 last.mNext = q; 5513 mPendingInputEventTail = q; 5514 } 5515 mPendingInputEventCount += 1; 5516 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5517 mPendingInputEventCount); 5518 5519 if (processImmediately) { 5520 doProcessInputEvents(); 5521 } else { 5522 scheduleProcessInputEvents(); 5523 } 5524 } 5525 5526 private void scheduleProcessInputEvents() { 5527 if (!mProcessInputEventsScheduled) { 5528 mProcessInputEventsScheduled = true; 5529 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 5530 msg.setAsynchronous(true); 5531 mHandler.sendMessage(msg); 5532 } 5533 } 5534 5535 void doProcessInputEvents() { 5536 // Deliver all pending input events in the queue. 5537 while (mPendingInputEventHead != null) { 5538 QueuedInputEvent q = mPendingInputEventHead; 5539 mPendingInputEventHead = q.mNext; 5540 if (mPendingInputEventHead == null) { 5541 mPendingInputEventTail = null; 5542 } 5543 q.mNext = null; 5544 5545 mPendingInputEventCount -= 1; 5546 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5547 mPendingInputEventCount); 5548 5549 deliverInputEvent(q); 5550 } 5551 5552 // We are done processing all input events that we can process right now 5553 // so we can clear the pending flag immediately. 5554 if (mProcessInputEventsScheduled) { 5555 mProcessInputEventsScheduled = false; 5556 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 5557 } 5558 } 5559 5560 private void deliverInputEvent(QueuedInputEvent q) { 5561 Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent", 5562 q.mEvent.getSequenceNumber()); 5563 if (mInputEventConsistencyVerifier != null) { 5564 mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0); 5565 } 5566 5567 InputStage stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage; 5568 if (stage != null) { 5569 stage.deliver(q); 5570 } else { 5571 finishInputEvent(q); 5572 } 5573 } 5574 5575 private void finishInputEvent(QueuedInputEvent q) { 5576 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent", 5577 q.mEvent.getSequenceNumber()); 5578 if (q.mReceiver != null) { 5579 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0; 5580 q.mReceiver.finishInputEvent(q.mEvent, handled); 5581 } else { 5582 q.mEvent.recycleIfNeededAfterDispatch(); 5583 } 5584 5585 recycleQueuedInputEvent(q); 5586 } 5587 5588 static boolean isTerminalInputEvent(InputEvent event) { 5589 if (event instanceof KeyEvent) { 5590 final KeyEvent keyEvent = (KeyEvent)event; 5591 return keyEvent.getAction() == KeyEvent.ACTION_UP; 5592 } else { 5593 final MotionEvent motionEvent = (MotionEvent)event; 5594 final int action = motionEvent.getAction(); 5595 return action == MotionEvent.ACTION_UP 5596 || action == MotionEvent.ACTION_CANCEL 5597 || action == MotionEvent.ACTION_HOVER_EXIT; 5598 } 5599 } 5600 5601 void scheduleConsumeBatchedInput() { 5602 if (!mConsumeBatchedInputScheduled) { 5603 mConsumeBatchedInputScheduled = true; 5604 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 5605 mConsumedBatchedInputRunnable, null); 5606 } 5607 } 5608 5609 void unscheduleConsumeBatchedInput() { 5610 if (mConsumeBatchedInputScheduled) { 5611 mConsumeBatchedInputScheduled = false; 5612 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 5613 mConsumedBatchedInputRunnable, null); 5614 } 5615 } 5616 5617 void doConsumeBatchedInput(long frameTimeNanos) { 5618 if (mConsumeBatchedInputScheduled) { 5619 mConsumeBatchedInputScheduled = false; 5620 if (mInputEventReceiver != null) { 5621 if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)) { 5622 // If we consumed a batch here, we want to go ahead and schedule the 5623 // consumption of batched input events on the next frame. Otherwise, we would 5624 // wait until we have more input events pending and might get starved by other 5625 // things occurring in the process. 5626 scheduleConsumeBatchedInput(); 5627 } 5628 } 5629 doProcessInputEvents(); 5630 } 5631 } 5632 5633 final class TraversalRunnable implements Runnable { 5634 @Override 5635 public void run() { 5636 doTraversal(); 5637 } 5638 } 5639 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 5640 5641 final class WindowInputEventReceiver extends InputEventReceiver { 5642 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 5643 super(inputChannel, looper); 5644 } 5645 5646 @Override 5647 public void onInputEvent(InputEvent event) { 5648 enqueueInputEvent(event, this, 0, true); 5649 } 5650 5651 @Override 5652 public void onBatchedInputEventPending() { 5653 scheduleConsumeBatchedInput(); 5654 } 5655 5656 @Override 5657 public void dispose() { 5658 unscheduleConsumeBatchedInput(); 5659 super.dispose(); 5660 } 5661 } 5662 WindowInputEventReceiver mInputEventReceiver; 5663 5664 final class ConsumeBatchedInputRunnable implements Runnable { 5665 @Override 5666 public void run() { 5667 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 5668 } 5669 } 5670 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 5671 new ConsumeBatchedInputRunnable(); 5672 boolean mConsumeBatchedInputScheduled; 5673 5674 final class InvalidateOnAnimationRunnable implements Runnable { 5675 private boolean mPosted; 5676 private final ArrayList<View> mViews = new ArrayList<View>(); 5677 private final ArrayList<AttachInfo.InvalidateInfo> mViewRects = 5678 new ArrayList<AttachInfo.InvalidateInfo>(); 5679 private View[] mTempViews; 5680 private AttachInfo.InvalidateInfo[] mTempViewRects; 5681 5682 public void addView(View view) { 5683 synchronized (this) { 5684 mViews.add(view); 5685 postIfNeededLocked(); 5686 } 5687 } 5688 5689 public void addViewRect(AttachInfo.InvalidateInfo info) { 5690 synchronized (this) { 5691 mViewRects.add(info); 5692 postIfNeededLocked(); 5693 } 5694 } 5695 5696 public void removeView(View view) { 5697 synchronized (this) { 5698 mViews.remove(view); 5699 5700 for (int i = mViewRects.size(); i-- > 0; ) { 5701 AttachInfo.InvalidateInfo info = mViewRects.get(i); 5702 if (info.target == view) { 5703 mViewRects.remove(i); 5704 info.recycle(); 5705 } 5706 } 5707 5708 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 5709 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 5710 mPosted = false; 5711 } 5712 } 5713 } 5714 5715 @Override 5716 public void run() { 5717 final int viewCount; 5718 final int viewRectCount; 5719 synchronized (this) { 5720 mPosted = false; 5721 5722 viewCount = mViews.size(); 5723 if (viewCount != 0) { 5724 mTempViews = mViews.toArray(mTempViews != null 5725 ? mTempViews : new View[viewCount]); 5726 mViews.clear(); 5727 } 5728 5729 viewRectCount = mViewRects.size(); 5730 if (viewRectCount != 0) { 5731 mTempViewRects = mViewRects.toArray(mTempViewRects != null 5732 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 5733 mViewRects.clear(); 5734 } 5735 } 5736 5737 for (int i = 0; i < viewCount; i++) { 5738 mTempViews[i].invalidate(); 5739 mTempViews[i] = null; 5740 } 5741 5742 for (int i = 0; i < viewRectCount; i++) { 5743 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 5744 info.target.invalidate(info.left, info.top, info.right, info.bottom); 5745 info.recycle(); 5746 } 5747 } 5748 5749 private void postIfNeededLocked() { 5750 if (!mPosted) { 5751 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 5752 mPosted = true; 5753 } 5754 } 5755 } 5756 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 5757 new InvalidateOnAnimationRunnable(); 5758 5759 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 5760 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 5761 mHandler.sendMessageDelayed(msg, delayMilliseconds); 5762 } 5763 5764 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 5765 long delayMilliseconds) { 5766 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 5767 mHandler.sendMessageDelayed(msg, delayMilliseconds); 5768 } 5769 5770 public void dispatchInvalidateOnAnimation(View view) { 5771 mInvalidateOnAnimationRunnable.addView(view); 5772 } 5773 5774 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 5775 mInvalidateOnAnimationRunnable.addViewRect(info); 5776 } 5777 5778 public void cancelInvalidate(View view) { 5779 mHandler.removeMessages(MSG_INVALIDATE, view); 5780 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 5781 // them to the pool 5782 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 5783 mInvalidateOnAnimationRunnable.removeView(view); 5784 } 5785 5786 public void dispatchInputEvent(InputEvent event) { 5787 Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, event); 5788 msg.setAsynchronous(true); 5789 mHandler.sendMessage(msg); 5790 } 5791 5792 public void dispatchKeyFromIme(KeyEvent event) { 5793 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 5794 msg.setAsynchronous(true); 5795 mHandler.sendMessage(msg); 5796 } 5797 5798 public void dispatchUnhandledKey(KeyEvent event) { 5799 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 5800 // Some fallback keys are decided by the ViewRoot as they might have special 5801 // properties (e.g. are locale aware). These take precedence over fallbacks defined by 5802 // the kcm. 5803 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 5804 final int keyCode = event.getKeyCode(); 5805 final int metaState = event.getMetaState(); 5806 5807 // Check for fallback actions specified by the key character map. 5808 KeyCharacterMap.FallbackAction fallbackAction = 5809 kcm.getFallbackAction(keyCode, metaState); 5810 if (fallbackAction != null) { 5811 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 5812 KeyEvent fallbackEvent = KeyEvent.obtain( 5813 event.getDownTime(), event.getEventTime(), 5814 event.getAction(), fallbackAction.keyCode, 5815 event.getRepeatCount(), fallbackAction.metaState, 5816 event.getDeviceId(), event.getScanCode(), 5817 flags, event.getSource(), null); 5818 fallbackAction.recycle(); 5819 dispatchInputEvent(fallbackEvent); 5820 } 5821 } 5822 } 5823 5824 public void dispatchAppVisibility(boolean visible) { 5825 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 5826 msg.arg1 = visible ? 1 : 0; 5827 mHandler.sendMessage(msg); 5828 } 5829 5830 public void dispatchGetNewSurface() { 5831 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 5832 mHandler.sendMessage(msg); 5833 } 5834 5835 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 5836 Message msg = Message.obtain(); 5837 msg.what = MSG_WINDOW_FOCUS_CHANGED; 5838 msg.arg1 = hasFocus ? 1 : 0; 5839 msg.arg2 = inTouchMode ? 1 : 0; 5840 mHandler.sendMessage(msg); 5841 } 5842 5843 public void dispatchCloseSystemDialogs(String reason) { 5844 Message msg = Message.obtain(); 5845 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 5846 msg.obj = reason; 5847 mHandler.sendMessage(msg); 5848 } 5849 5850 public void dispatchDragEvent(DragEvent event) { 5851 final int what; 5852 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 5853 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 5854 mHandler.removeMessages(what); 5855 } else { 5856 what = MSG_DISPATCH_DRAG_EVENT; 5857 } 5858 Message msg = mHandler.obtainMessage(what, event); 5859 mHandler.sendMessage(msg); 5860 } 5861 5862 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 5863 int localValue, int localChanges) { 5864 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 5865 args.seq = seq; 5866 args.globalVisibility = globalVisibility; 5867 args.localValue = localValue; 5868 args.localChanges = localChanges; 5869 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 5870 } 5871 5872 public void dispatchDoneAnimating() { 5873 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 5874 } 5875 5876 public void dispatchCheckFocus() { 5877 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 5878 // This will result in a call to checkFocus() below. 5879 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 5880 } 5881 } 5882 5883 /** 5884 * Post a callback to send a 5885 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 5886 * This event is send at most once every 5887 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 5888 */ 5889 private void postSendWindowContentChangedCallback(View source, int changeType) { 5890 if (mSendWindowContentChangedAccessibilityEvent == null) { 5891 mSendWindowContentChangedAccessibilityEvent = 5892 new SendWindowContentChangedAccessibilityEvent(); 5893 } 5894 mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType); 5895 } 5896 5897 /** 5898 * Remove a posted callback to send a 5899 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 5900 */ 5901 private void removeSendWindowContentChangedCallback() { 5902 if (mSendWindowContentChangedAccessibilityEvent != null) { 5903 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 5904 } 5905 } 5906 5907 @Override 5908 public boolean showContextMenuForChild(View originalView) { 5909 return false; 5910 } 5911 5912 @Override 5913 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 5914 return null; 5915 } 5916 5917 @Override 5918 public void createContextMenu(ContextMenu menu) { 5919 } 5920 5921 @Override 5922 public void childDrawableStateChanged(View child) { 5923 } 5924 5925 @Override 5926 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 5927 if (mView == null) { 5928 return false; 5929 } 5930 // Intercept accessibility focus events fired by virtual nodes to keep 5931 // track of accessibility focus position in such nodes. 5932 final int eventType = event.getEventType(); 5933 switch (eventType) { 5934 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 5935 final long sourceNodeId = event.getSourceNodeId(); 5936 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5937 sourceNodeId); 5938 View source = mView.findViewByAccessibilityId(accessibilityViewId); 5939 if (source != null) { 5940 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 5941 if (provider != null) { 5942 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo( 5943 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId)); 5944 setAccessibilityFocus(source, node); 5945 } 5946 } 5947 } break; 5948 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 5949 final long sourceNodeId = event.getSourceNodeId(); 5950 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5951 sourceNodeId); 5952 View source = mView.findViewByAccessibilityId(accessibilityViewId); 5953 if (source != null) { 5954 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 5955 if (provider != null) { 5956 setAccessibilityFocus(null, null); 5957 } 5958 } 5959 } break; 5960 } 5961 mAccessibilityManager.sendAccessibilityEvent(event); 5962 return true; 5963 } 5964 5965 @Override 5966 public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) { 5967 postSendWindowContentChangedCallback(source, changeType); 5968 } 5969 5970 @Override 5971 public boolean canResolveLayoutDirection() { 5972 return true; 5973 } 5974 5975 @Override 5976 public boolean isLayoutDirectionResolved() { 5977 return true; 5978 } 5979 5980 @Override 5981 public int getLayoutDirection() { 5982 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT; 5983 } 5984 5985 @Override 5986 public boolean canResolveTextDirection() { 5987 return true; 5988 } 5989 5990 @Override 5991 public boolean isTextDirectionResolved() { 5992 return true; 5993 } 5994 5995 @Override 5996 public int getTextDirection() { 5997 return View.TEXT_DIRECTION_RESOLVED_DEFAULT; 5998 } 5999 6000 @Override 6001 public boolean canResolveTextAlignment() { 6002 return true; 6003 } 6004 6005 @Override 6006 public boolean isTextAlignmentResolved() { 6007 return true; 6008 } 6009 6010 @Override 6011 public int getTextAlignment() { 6012 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT; 6013 } 6014 6015 private View getCommonPredecessor(View first, View second) { 6016 if (mAttachInfo != null) { 6017 if (mTempHashSet == null) { 6018 mTempHashSet = new HashSet<View>(); 6019 } 6020 HashSet<View> seen = mTempHashSet; 6021 seen.clear(); 6022 View firstCurrent = first; 6023 while (firstCurrent != null) { 6024 seen.add(firstCurrent); 6025 ViewParent firstCurrentParent = firstCurrent.mParent; 6026 if (firstCurrentParent instanceof View) { 6027 firstCurrent = (View) firstCurrentParent; 6028 } else { 6029 firstCurrent = null; 6030 } 6031 } 6032 View secondCurrent = second; 6033 while (secondCurrent != null) { 6034 if (seen.contains(secondCurrent)) { 6035 seen.clear(); 6036 return secondCurrent; 6037 } 6038 ViewParent secondCurrentParent = secondCurrent.mParent; 6039 if (secondCurrentParent instanceof View) { 6040 secondCurrent = (View) secondCurrentParent; 6041 } else { 6042 secondCurrent = null; 6043 } 6044 } 6045 seen.clear(); 6046 } 6047 return null; 6048 } 6049 6050 void checkThread() { 6051 if (mThread != Thread.currentThread()) { 6052 throw new CalledFromWrongThreadException( 6053 "Only the original thread that created a view hierarchy can touch its views."); 6054 } 6055 } 6056 6057 @Override 6058 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 6059 // ViewAncestor never intercepts touch event, so this can be a no-op 6060 } 6061 6062 @Override 6063 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 6064 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 6065 if (rectangle != null) { 6066 mTempRect.set(rectangle); 6067 mTempRect.offset(0, -mCurScrollY); 6068 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6069 try { 6070 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate); 6071 } catch (RemoteException re) { 6072 /* ignore */ 6073 } 6074 } 6075 return scrolled; 6076 } 6077 6078 @Override 6079 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 6080 // Do nothing. 6081 } 6082 6083 void changeCanvasOpacity(boolean opaque) { 6084 // TODO(romainguy): recreate Canvas (software or hardware) to reflect the opacity change. 6085 Log.d(TAG, "changeCanvasOpacity: opaque=" + opaque); 6086 } 6087 6088 class TakenSurfaceHolder extends BaseSurfaceHolder { 6089 @Override 6090 public boolean onAllowLockCanvas() { 6091 return mDrawingAllowed; 6092 } 6093 6094 @Override 6095 public void onRelayoutContainer() { 6096 // Not currently interesting -- from changing between fixed and layout size. 6097 } 6098 6099 @Override 6100 public void setFormat(int format) { 6101 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 6102 } 6103 6104 @Override 6105 public void setType(int type) { 6106 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 6107 } 6108 6109 @Override 6110 public void onUpdateSurface() { 6111 // We take care of format and type changes on our own. 6112 throw new IllegalStateException("Shouldn't be here"); 6113 } 6114 6115 @Override 6116 public boolean isCreating() { 6117 return mIsCreating; 6118 } 6119 6120 @Override 6121 public void setFixedSize(int width, int height) { 6122 throw new UnsupportedOperationException( 6123 "Currently only support sizing from layout"); 6124 } 6125 6126 @Override 6127 public void setKeepScreenOn(boolean screenOn) { 6128 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 6129 } 6130 } 6131 6132 static class W extends IWindow.Stub { 6133 private final WeakReference<ViewRootImpl> mViewAncestor; 6134 private final IWindowSession mWindowSession; 6135 6136 W(ViewRootImpl viewAncestor) { 6137 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 6138 mWindowSession = viewAncestor.mWindowSession; 6139 } 6140 6141 @Override 6142 public void resized(Rect frame, Rect overscanInsets, Rect contentInsets, 6143 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 6144 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6145 if (viewAncestor != null) { 6146 viewAncestor.dispatchResized(frame, overscanInsets, contentInsets, 6147 visibleInsets, reportDraw, newConfig); 6148 } 6149 } 6150 6151 @Override 6152 public void moved(int newX, int newY) { 6153 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6154 if (viewAncestor != null) { 6155 viewAncestor.dispatchMoved(newX, newY); 6156 } 6157 } 6158 6159 @Override 6160 public void dispatchAppVisibility(boolean visible) { 6161 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6162 if (viewAncestor != null) { 6163 viewAncestor.dispatchAppVisibility(visible); 6164 } 6165 } 6166 6167 @Override 6168 public void dispatchGetNewSurface() { 6169 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6170 if (viewAncestor != null) { 6171 viewAncestor.dispatchGetNewSurface(); 6172 } 6173 } 6174 6175 @Override 6176 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 6177 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6178 if (viewAncestor != null) { 6179 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 6180 } 6181 } 6182 6183 private static int checkCallingPermission(String permission) { 6184 try { 6185 return ActivityManagerNative.getDefault().checkPermission( 6186 permission, Binder.getCallingPid(), Binder.getCallingUid()); 6187 } catch (RemoteException e) { 6188 return PackageManager.PERMISSION_DENIED; 6189 } 6190 } 6191 6192 @Override 6193 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 6194 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6195 if (viewAncestor != null) { 6196 final View view = viewAncestor.mView; 6197 if (view != null) { 6198 if (checkCallingPermission(Manifest.permission.DUMP) != 6199 PackageManager.PERMISSION_GRANTED) { 6200 throw new SecurityException("Insufficient permissions to invoke" 6201 + " executeCommand() from pid=" + Binder.getCallingPid() 6202 + ", uid=" + Binder.getCallingUid()); 6203 } 6204 6205 OutputStream clientStream = null; 6206 try { 6207 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 6208 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 6209 } catch (IOException e) { 6210 e.printStackTrace(); 6211 } finally { 6212 if (clientStream != null) { 6213 try { 6214 clientStream.close(); 6215 } catch (IOException e) { 6216 e.printStackTrace(); 6217 } 6218 } 6219 } 6220 } 6221 } 6222 } 6223 6224 @Override 6225 public void closeSystemDialogs(String reason) { 6226 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6227 if (viewAncestor != null) { 6228 viewAncestor.dispatchCloseSystemDialogs(reason); 6229 } 6230 } 6231 6232 @Override 6233 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 6234 boolean sync) { 6235 if (sync) { 6236 try { 6237 mWindowSession.wallpaperOffsetsComplete(asBinder()); 6238 } catch (RemoteException e) { 6239 } 6240 } 6241 } 6242 6243 @Override 6244 public void dispatchWallpaperCommand(String action, int x, int y, 6245 int z, Bundle extras, boolean sync) { 6246 if (sync) { 6247 try { 6248 mWindowSession.wallpaperCommandComplete(asBinder(), null); 6249 } catch (RemoteException e) { 6250 } 6251 } 6252 } 6253 6254 /* Drag/drop */ 6255 @Override 6256 public void dispatchDragEvent(DragEvent event) { 6257 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6258 if (viewAncestor != null) { 6259 viewAncestor.dispatchDragEvent(event); 6260 } 6261 } 6262 6263 @Override 6264 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 6265 int localValue, int localChanges) { 6266 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6267 if (viewAncestor != null) { 6268 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 6269 localValue, localChanges); 6270 } 6271 } 6272 6273 @Override 6274 public void doneAnimating() { 6275 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6276 if (viewAncestor != null) { 6277 viewAncestor.dispatchDoneAnimating(); 6278 } 6279 } 6280 } 6281 6282 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 6283 public CalledFromWrongThreadException(String msg) { 6284 super(msg); 6285 } 6286 } 6287 6288 static RunQueue getRunQueue() { 6289 RunQueue rq = sRunQueues.get(); 6290 if (rq != null) { 6291 return rq; 6292 } 6293 rq = new RunQueue(); 6294 sRunQueues.set(rq); 6295 return rq; 6296 } 6297 6298 /** 6299 * The run queue is used to enqueue pending work from Views when no Handler is 6300 * attached. The work is executed during the next call to performTraversals on 6301 * the thread. 6302 * @hide 6303 */ 6304 static final class RunQueue { 6305 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 6306 6307 void post(Runnable action) { 6308 postDelayed(action, 0); 6309 } 6310 6311 void postDelayed(Runnable action, long delayMillis) { 6312 HandlerAction handlerAction = new HandlerAction(); 6313 handlerAction.action = action; 6314 handlerAction.delay = delayMillis; 6315 6316 synchronized (mActions) { 6317 mActions.add(handlerAction); 6318 } 6319 } 6320 6321 void removeCallbacks(Runnable action) { 6322 final HandlerAction handlerAction = new HandlerAction(); 6323 handlerAction.action = action; 6324 6325 synchronized (mActions) { 6326 final ArrayList<HandlerAction> actions = mActions; 6327 6328 while (actions.remove(handlerAction)) { 6329 // Keep going 6330 } 6331 } 6332 } 6333 6334 void executeActions(Handler handler) { 6335 synchronized (mActions) { 6336 final ArrayList<HandlerAction> actions = mActions; 6337 final int count = actions.size(); 6338 6339 for (int i = 0; i < count; i++) { 6340 final HandlerAction handlerAction = actions.get(i); 6341 handler.postDelayed(handlerAction.action, handlerAction.delay); 6342 } 6343 6344 actions.clear(); 6345 } 6346 } 6347 6348 private static class HandlerAction { 6349 Runnable action; 6350 long delay; 6351 6352 @Override 6353 public boolean equals(Object o) { 6354 if (this == o) return true; 6355 if (o == null || getClass() != o.getClass()) return false; 6356 6357 HandlerAction that = (HandlerAction) o; 6358 return !(action != null ? !action.equals(that.action) : that.action != null); 6359 6360 } 6361 6362 @Override 6363 public int hashCode() { 6364 int result = action != null ? action.hashCode() : 0; 6365 result = 31 * result + (int) (delay ^ (delay >>> 32)); 6366 return result; 6367 } 6368 } 6369 } 6370 6371 /** 6372 * Class for managing the accessibility interaction connection 6373 * based on the global accessibility state. 6374 */ 6375 final class AccessibilityInteractionConnectionManager 6376 implements AccessibilityStateChangeListener { 6377 @Override 6378 public void onAccessibilityStateChanged(boolean enabled) { 6379 if (enabled) { 6380 ensureConnection(); 6381 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 6382 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 6383 View focusedView = mView.findFocus(); 6384 if (focusedView != null && focusedView != mView) { 6385 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6386 } 6387 } 6388 } else { 6389 ensureNoConnection(); 6390 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 6391 } 6392 } 6393 6394 public void ensureConnection() { 6395 if (mAttachInfo != null) { 6396 final boolean registered = 6397 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6398 if (!registered) { 6399 mAttachInfo.mAccessibilityWindowId = 6400 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 6401 new AccessibilityInteractionConnection(ViewRootImpl.this)); 6402 } 6403 } 6404 } 6405 6406 public void ensureNoConnection() { 6407 final boolean registered = 6408 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6409 if (registered) { 6410 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6411 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 6412 } 6413 } 6414 } 6415 6416 /** 6417 * This class is an interface this ViewAncestor provides to the 6418 * AccessibilityManagerService to the latter can interact with 6419 * the view hierarchy in this ViewAncestor. 6420 */ 6421 static final class AccessibilityInteractionConnection 6422 extends IAccessibilityInteractionConnection.Stub { 6423 private final WeakReference<ViewRootImpl> mViewRootImpl; 6424 6425 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 6426 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 6427 } 6428 6429 @Override 6430 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 6431 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6432 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6433 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6434 if (viewRootImpl != null && viewRootImpl.mView != null) { 6435 viewRootImpl.getAccessibilityInteractionController() 6436 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 6437 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6438 spec); 6439 } else { 6440 // We cannot make the call and notify the caller so it does not wait. 6441 try { 6442 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6443 } catch (RemoteException re) { 6444 /* best effort - ignore */ 6445 } 6446 } 6447 } 6448 6449 @Override 6450 public void performAccessibilityAction(long accessibilityNodeId, int action, 6451 Bundle arguments, int interactionId, 6452 IAccessibilityInteractionConnectionCallback callback, int flags, 6453 int interogatingPid, long interrogatingTid) { 6454 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6455 if (viewRootImpl != null && viewRootImpl.mView != null) { 6456 viewRootImpl.getAccessibilityInteractionController() 6457 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 6458 interactionId, callback, flags, interogatingPid, interrogatingTid); 6459 } else { 6460 // We cannot make the call and notify the caller so it does not wait. 6461 try { 6462 callback.setPerformAccessibilityActionResult(false, interactionId); 6463 } catch (RemoteException re) { 6464 /* best effort - ignore */ 6465 } 6466 } 6467 } 6468 6469 @Override 6470 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId, 6471 String viewId, int interactionId, 6472 IAccessibilityInteractionConnectionCallback callback, int flags, 6473 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6474 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6475 if (viewRootImpl != null && viewRootImpl.mView != null) { 6476 viewRootImpl.getAccessibilityInteractionController() 6477 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId, 6478 viewId, interactionId, callback, flags, interrogatingPid, 6479 interrogatingTid, spec); 6480 } else { 6481 // We cannot make the call and notify the caller so it does not wait. 6482 try { 6483 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6484 } catch (RemoteException re) { 6485 /* best effort - ignore */ 6486 } 6487 } 6488 } 6489 6490 @Override 6491 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 6492 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6493 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6494 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6495 if (viewRootImpl != null && viewRootImpl.mView != null) { 6496 viewRootImpl.getAccessibilityInteractionController() 6497 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 6498 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6499 spec); 6500 } else { 6501 // We cannot make the call and notify the caller so it does not wait. 6502 try { 6503 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6504 } catch (RemoteException re) { 6505 /* best effort - ignore */ 6506 } 6507 } 6508 } 6509 6510 @Override 6511 public void findFocus(long accessibilityNodeId, int focusType, int interactionId, 6512 IAccessibilityInteractionConnectionCallback callback, int flags, 6513 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6514 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6515 if (viewRootImpl != null && viewRootImpl.mView != null) { 6516 viewRootImpl.getAccessibilityInteractionController() 6517 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback, 6518 flags, interrogatingPid, interrogatingTid, spec); 6519 } else { 6520 // We cannot make the call and notify the caller so it does not wait. 6521 try { 6522 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6523 } catch (RemoteException re) { 6524 /* best effort - ignore */ 6525 } 6526 } 6527 } 6528 6529 @Override 6530 public void focusSearch(long accessibilityNodeId, int direction, int interactionId, 6531 IAccessibilityInteractionConnectionCallback callback, int flags, 6532 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6533 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6534 if (viewRootImpl != null && viewRootImpl.mView != null) { 6535 viewRootImpl.getAccessibilityInteractionController() 6536 .focusSearchClientThread(accessibilityNodeId, direction, interactionId, 6537 callback, flags, interrogatingPid, interrogatingTid, spec); 6538 } else { 6539 // We cannot make the call and notify the caller so it does not wait. 6540 try { 6541 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6542 } catch (RemoteException re) { 6543 /* best effort - ignore */ 6544 } 6545 } 6546 } 6547 } 6548 6549 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 6550 private int mChangeTypes = 0; 6551 6552 public View mSource; 6553 public long mLastEventTimeMillis; 6554 6555 @Override 6556 public void run() { 6557 // The accessibility may be turned off while we were waiting so check again. 6558 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6559 mLastEventTimeMillis = SystemClock.uptimeMillis(); 6560 AccessibilityEvent event = AccessibilityEvent.obtain(); 6561 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 6562 event.setContentChangeTypes(mChangeTypes); 6563 mSource.sendAccessibilityEventUnchecked(event); 6564 } else { 6565 mLastEventTimeMillis = 0; 6566 } 6567 // In any case reset to initial state. 6568 mSource.resetSubtreeAccessibilityStateChanged(); 6569 mSource = null; 6570 mChangeTypes = 0; 6571 } 6572 6573 public void runOrPost(View source, int changeType) { 6574 if (mSource != null) { 6575 // If there is no common predecessor, then mSource points to 6576 // a removed view, hence in this case always prefer the source. 6577 View predecessor = getCommonPredecessor(mSource, source); 6578 mSource = (predecessor != null) ? predecessor : source; 6579 mChangeTypes |= changeType; 6580 return; 6581 } 6582 mSource = source; 6583 mChangeTypes = changeType; 6584 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 6585 final long minEventIntevalMillis = 6586 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 6587 if (timeSinceLastMillis >= minEventIntevalMillis) { 6588 mSource.removeCallbacks(this); 6589 run(); 6590 } else { 6591 mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 6592 } 6593 } 6594 } 6595} 6596