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