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