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