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