ViewRootImpl.java revision 00dbe81fea7be57ee2ff8a97844faf1bc15a427f
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 = null; 2791 mAttachInfo.mRootView = null; 2792 mAttachInfo.mSurface = null; 2793 2794 mSurface.release(); 2795 2796 if (mInputQueueCallback != null && mInputQueue != null) { 2797 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2798 mInputQueue.dispose(); 2799 mInputQueueCallback = null; 2800 mInputQueue = null; 2801 } 2802 if (mInputEventReceiver != null) { 2803 mInputEventReceiver.dispose(); 2804 mInputEventReceiver = null; 2805 } 2806 try { 2807 mWindowSession.remove(mWindow); 2808 } catch (RemoteException e) { 2809 } 2810 2811 // Dispose the input channel after removing the window so the Window Manager 2812 // doesn't interpret the input channel being closed as an abnormal termination. 2813 if (mInputChannel != null) { 2814 mInputChannel.dispose(); 2815 mInputChannel = null; 2816 } 2817 2818 unscheduleTraversals(); 2819 } 2820 2821 void updateConfiguration(Configuration config, boolean force) { 2822 if (DEBUG_CONFIGURATION) Log.v(TAG, 2823 "Applying new config to window " 2824 + mWindowAttributes.getTitle() 2825 + ": " + config); 2826 2827 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded(); 2828 if (ci != null) { 2829 config = new Configuration(config); 2830 ci.applyToConfiguration(mNoncompatDensity, config); 2831 } 2832 2833 synchronized (sConfigCallbacks) { 2834 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2835 sConfigCallbacks.get(i).onConfigurationChanged(config); 2836 } 2837 } 2838 if (mView != null) { 2839 // At this point the resources have been updated to 2840 // have the most recent config, whatever that is. Use 2841 // the one in them which may be newer. 2842 config = mView.getResources().getConfiguration(); 2843 if (force || mLastConfiguration.diff(config) != 0) { 2844 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection(); 2845 final int currentLayoutDirection = config.getLayoutDirection(); 2846 mLastConfiguration.setTo(config); 2847 if (lastLayoutDirection != currentLayoutDirection && 2848 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 2849 mView.setLayoutDirection(currentLayoutDirection); 2850 } 2851 mView.dispatchConfigurationChanged(config); 2852 } 2853 } 2854 } 2855 2856 /** 2857 * Return true if child is an ancestor of parent, (or equal to the parent). 2858 */ 2859 public static boolean isViewDescendantOf(View child, View parent) { 2860 if (child == parent) { 2861 return true; 2862 } 2863 2864 final ViewParent theParent = child.getParent(); 2865 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2866 } 2867 2868 private static void forceLayout(View view) { 2869 view.forceLayout(); 2870 if (view instanceof ViewGroup) { 2871 ViewGroup group = (ViewGroup) view; 2872 final int count = group.getChildCount(); 2873 for (int i = 0; i < count; i++) { 2874 forceLayout(group.getChildAt(i)); 2875 } 2876 } 2877 } 2878 2879 private final static int MSG_INVALIDATE = 1; 2880 private final static int MSG_INVALIDATE_RECT = 2; 2881 private final static int MSG_DIE = 3; 2882 private final static int MSG_RESIZED = 4; 2883 private final static int MSG_RESIZED_REPORT = 5; 2884 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 2885 private final static int MSG_DISPATCH_KEY = 7; 2886 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 2887 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 2888 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 2889 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 2890 private final static int MSG_CHECK_FOCUS = 13; 2891 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 2892 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 2893 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 2894 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 2895 private final static int MSG_UPDATE_CONFIGURATION = 18; 2896 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 2897 private final static int MSG_DISPATCH_SCREEN_STATE = 20; 2898 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21; 2899 private final static int MSG_DISPATCH_DONE_ANIMATING = 22; 2900 private final static int MSG_INVALIDATE_WORLD = 23; 2901 private final static int MSG_WINDOW_MOVED = 24; 2902 2903 final class ViewRootHandler extends Handler { 2904 @Override 2905 public String getMessageName(Message message) { 2906 switch (message.what) { 2907 case MSG_INVALIDATE: 2908 return "MSG_INVALIDATE"; 2909 case MSG_INVALIDATE_RECT: 2910 return "MSG_INVALIDATE_RECT"; 2911 case MSG_DIE: 2912 return "MSG_DIE"; 2913 case MSG_RESIZED: 2914 return "MSG_RESIZED"; 2915 case MSG_RESIZED_REPORT: 2916 return "MSG_RESIZED_REPORT"; 2917 case MSG_WINDOW_FOCUS_CHANGED: 2918 return "MSG_WINDOW_FOCUS_CHANGED"; 2919 case MSG_DISPATCH_KEY: 2920 return "MSG_DISPATCH_KEY"; 2921 case MSG_DISPATCH_APP_VISIBILITY: 2922 return "MSG_DISPATCH_APP_VISIBILITY"; 2923 case MSG_DISPATCH_GET_NEW_SURFACE: 2924 return "MSG_DISPATCH_GET_NEW_SURFACE"; 2925 case MSG_DISPATCH_KEY_FROM_IME: 2926 return "MSG_DISPATCH_KEY_FROM_IME"; 2927 case MSG_FINISH_INPUT_CONNECTION: 2928 return "MSG_FINISH_INPUT_CONNECTION"; 2929 case MSG_CHECK_FOCUS: 2930 return "MSG_CHECK_FOCUS"; 2931 case MSG_CLOSE_SYSTEM_DIALOGS: 2932 return "MSG_CLOSE_SYSTEM_DIALOGS"; 2933 case MSG_DISPATCH_DRAG_EVENT: 2934 return "MSG_DISPATCH_DRAG_EVENT"; 2935 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 2936 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 2937 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 2938 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 2939 case MSG_UPDATE_CONFIGURATION: 2940 return "MSG_UPDATE_CONFIGURATION"; 2941 case MSG_PROCESS_INPUT_EVENTS: 2942 return "MSG_PROCESS_INPUT_EVENTS"; 2943 case MSG_DISPATCH_SCREEN_STATE: 2944 return "MSG_DISPATCH_SCREEN_STATE"; 2945 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 2946 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 2947 case MSG_DISPATCH_DONE_ANIMATING: 2948 return "MSG_DISPATCH_DONE_ANIMATING"; 2949 case MSG_WINDOW_MOVED: 2950 return "MSG_WINDOW_MOVED"; 2951 } 2952 return super.getMessageName(message); 2953 } 2954 2955 @Override 2956 public void handleMessage(Message msg) { 2957 switch (msg.what) { 2958 case MSG_INVALIDATE: 2959 ((View) msg.obj).invalidate(); 2960 break; 2961 case MSG_INVALIDATE_RECT: 2962 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 2963 info.target.invalidate(info.left, info.top, info.right, info.bottom); 2964 info.recycle(); 2965 break; 2966 case MSG_PROCESS_INPUT_EVENTS: 2967 mProcessInputEventsScheduled = false; 2968 doProcessInputEvents(); 2969 break; 2970 case MSG_DISPATCH_APP_VISIBILITY: 2971 handleAppVisibility(msg.arg1 != 0); 2972 break; 2973 case MSG_DISPATCH_GET_NEW_SURFACE: 2974 handleGetNewSurface(); 2975 break; 2976 case MSG_RESIZED: { 2977 // Recycled in the fall through... 2978 SomeArgs args = (SomeArgs) msg.obj; 2979 if (mWinFrame.equals(args.arg1) 2980 && mPendingOverscanInsets.equals(args.arg5) 2981 && mPendingContentInsets.equals(args.arg2) 2982 && mPendingVisibleInsets.equals(args.arg3) 2983 && args.arg4 == null) { 2984 break; 2985 } 2986 } // fall through... 2987 case MSG_RESIZED_REPORT: 2988 if (mAdded) { 2989 SomeArgs args = (SomeArgs) msg.obj; 2990 2991 Configuration config = (Configuration) args.arg4; 2992 if (config != null) { 2993 updateConfiguration(config, false); 2994 } 2995 2996 mWinFrame.set((Rect) args.arg1); 2997 mPendingOverscanInsets.set((Rect) args.arg5); 2998 mPendingContentInsets.set((Rect) args.arg2); 2999 mPendingVisibleInsets.set((Rect) args.arg3); 3000 3001 args.recycle(); 3002 3003 if (msg.what == MSG_RESIZED_REPORT) { 3004 mReportNextDraw = true; 3005 } 3006 3007 if (mView != null) { 3008 forceLayout(mView); 3009 } 3010 3011 requestLayout(); 3012 } 3013 break; 3014 case MSG_WINDOW_MOVED: 3015 if (mAdded) { 3016 final int w = mWinFrame.width(); 3017 final int h = mWinFrame.height(); 3018 final int l = msg.arg1; 3019 final int t = msg.arg2; 3020 mWinFrame.left = l; 3021 mWinFrame.right = l + w; 3022 mWinFrame.top = t; 3023 mWinFrame.bottom = t + h; 3024 3025 if (mView != null) { 3026 forceLayout(mView); 3027 } 3028 requestLayout(); 3029 } 3030 break; 3031 case MSG_WINDOW_FOCUS_CHANGED: { 3032 if (mAdded) { 3033 boolean hasWindowFocus = msg.arg1 != 0; 3034 mAttachInfo.mHasWindowFocus = hasWindowFocus; 3035 3036 profileRendering(hasWindowFocus); 3037 3038 if (hasWindowFocus) { 3039 boolean inTouchMode = msg.arg2 != 0; 3040 ensureTouchModeLocally(inTouchMode); 3041 3042 if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){ 3043 mFullRedrawNeeded = true; 3044 try { 3045 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 3046 mWidth, mHeight, mHolder.getSurface()); 3047 } catch (Surface.OutOfResourcesException e) { 3048 Log.e(TAG, "OutOfResourcesException locking surface", e); 3049 try { 3050 if (!mWindowSession.outOfMemory(mWindow)) { 3051 Slog.w(TAG, "No processes killed for memory; killing self"); 3052 Process.killProcess(Process.myPid()); 3053 } 3054 } catch (RemoteException ex) { 3055 } 3056 // Retry in a bit. 3057 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 3058 return; 3059 } 3060 } 3061 } 3062 3063 mLastWasImTarget = WindowManager.LayoutParams 3064 .mayUseInputMethod(mWindowAttributes.flags); 3065 3066 InputMethodManager imm = InputMethodManager.peekInstance(); 3067 if (mView != null) { 3068 if (hasWindowFocus && imm != null && mLastWasImTarget) { 3069 imm.startGettingWindowFocus(mView); 3070 } 3071 mAttachInfo.mKeyDispatchState.reset(); 3072 mView.dispatchWindowFocusChanged(hasWindowFocus); 3073 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus); 3074 } 3075 3076 // Note: must be done after the focus change callbacks, 3077 // so all of the view state is set up correctly. 3078 if (hasWindowFocus) { 3079 if (imm != null && mLastWasImTarget) { 3080 imm.onWindowFocus(mView, mView.findFocus(), 3081 mWindowAttributes.softInputMode, 3082 !mHasHadWindowFocus, mWindowAttributes.flags); 3083 } 3084 // Clear the forward bit. We can just do this directly, since 3085 // the window manager doesn't care about it. 3086 mWindowAttributes.softInputMode &= 3087 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3088 ((WindowManager.LayoutParams)mView.getLayoutParams()) 3089 .softInputMode &= 3090 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3091 mHasHadWindowFocus = true; 3092 } 3093 3094 setAccessibilityFocus(null, null); 3095 3096 if (mView != null && mAccessibilityManager.isEnabled()) { 3097 if (hasWindowFocus) { 3098 mView.sendAccessibilityEvent( 3099 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 3100 } 3101 } 3102 } 3103 } break; 3104 case MSG_DIE: 3105 doDie(); 3106 break; 3107 case MSG_DISPATCH_KEY: { 3108 KeyEvent event = (KeyEvent)msg.obj; 3109 enqueueInputEvent(event, null, 0, true); 3110 } break; 3111 case MSG_DISPATCH_KEY_FROM_IME: { 3112 if (LOCAL_LOGV) Log.v( 3113 TAG, "Dispatching key " 3114 + msg.obj + " from IME to " + mView); 3115 KeyEvent event = (KeyEvent)msg.obj; 3116 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 3117 // The IME is trying to say this event is from the 3118 // system! Bad bad bad! 3119 //noinspection UnusedAssignment 3120 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 3121 } 3122 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 3123 } break; 3124 case MSG_FINISH_INPUT_CONNECTION: { 3125 InputMethodManager imm = InputMethodManager.peekInstance(); 3126 if (imm != null) { 3127 imm.reportFinishInputConnection((InputConnection)msg.obj); 3128 } 3129 } break; 3130 case MSG_CHECK_FOCUS: { 3131 InputMethodManager imm = InputMethodManager.peekInstance(); 3132 if (imm != null) { 3133 imm.checkFocus(); 3134 } 3135 } break; 3136 case MSG_CLOSE_SYSTEM_DIALOGS: { 3137 if (mView != null) { 3138 mView.onCloseSystemDialogs((String)msg.obj); 3139 } 3140 } break; 3141 case MSG_DISPATCH_DRAG_EVENT: 3142 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 3143 DragEvent event = (DragEvent)msg.obj; 3144 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 3145 handleDragEvent(event); 3146 } break; 3147 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 3148 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); 3149 } break; 3150 case MSG_UPDATE_CONFIGURATION: { 3151 Configuration config = (Configuration)msg.obj; 3152 if (config.isOtherSeqNewer(mLastConfiguration)) { 3153 config = mLastConfiguration; 3154 } 3155 updateConfiguration(config, false); 3156 } break; 3157 case MSG_DISPATCH_SCREEN_STATE: { 3158 if (mView != null) { 3159 handleScreenStateChange(msg.arg1 == 1); 3160 } 3161 } break; 3162 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3163 setAccessibilityFocus(null, null); 3164 } break; 3165 case MSG_DISPATCH_DONE_ANIMATING: { 3166 handleDispatchDoneAnimating(); 3167 } break; 3168 case MSG_INVALIDATE_WORLD: { 3169 if (mView != null) { 3170 invalidateWorld(mView); 3171 } 3172 } break; 3173 } 3174 } 3175 } 3176 3177 final ViewRootHandler mHandler = new ViewRootHandler(); 3178 3179 /** 3180 * Something in the current window tells us we need to change the touch mode. For 3181 * example, we are not in touch mode, and the user touches the screen. 3182 * 3183 * If the touch mode has changed, tell the window manager, and handle it locally. 3184 * 3185 * @param inTouchMode Whether we want to be in touch mode. 3186 * @return True if the touch mode changed and focus changed was changed as a result 3187 */ 3188 boolean ensureTouchMode(boolean inTouchMode) { 3189 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3190 + "touch mode is " + mAttachInfo.mInTouchMode); 3191 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3192 3193 // tell the window manager 3194 try { 3195 mWindowSession.setInTouchMode(inTouchMode); 3196 } catch (RemoteException e) { 3197 throw new RuntimeException(e); 3198 } 3199 3200 // handle the change 3201 return ensureTouchModeLocally(inTouchMode); 3202 } 3203 3204 /** 3205 * Ensure that the touch mode for this window is set, and if it is changing, 3206 * take the appropriate action. 3207 * @param inTouchMode Whether we want to be in touch mode. 3208 * @return True if the touch mode changed and focus changed was changed as a result 3209 */ 3210 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3211 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3212 + "touch mode is " + mAttachInfo.mInTouchMode); 3213 3214 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3215 3216 mAttachInfo.mInTouchMode = inTouchMode; 3217 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3218 3219 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3220 } 3221 3222 private boolean enterTouchMode() { 3223 if (mView != null) { 3224 if (mView.hasFocus()) { 3225 // note: not relying on mFocusedView here because this could 3226 // be when the window is first being added, and mFocused isn't 3227 // set yet. 3228 final View focused = mView.findFocus(); 3229 if (focused != null && !focused.isFocusableInTouchMode()) { 3230 final ViewGroup ancestorToTakeFocus = 3231 findAncestorToTakeFocusInTouchMode(focused); 3232 if (ancestorToTakeFocus != null) { 3233 // there is an ancestor that wants focus after its descendants that 3234 // is focusable in touch mode.. give it focus 3235 return ancestorToTakeFocus.requestFocus(); 3236 } else { 3237 // nothing appropriate to have focus in touch mode, clear it out 3238 focused.unFocus(); 3239 return true; 3240 } 3241 } 3242 } 3243 } 3244 return false; 3245 } 3246 3247 /** 3248 * Find an ancestor of focused that wants focus after its descendants and is 3249 * focusable in touch mode. 3250 * @param focused The currently focused view. 3251 * @return An appropriate view, or null if no such view exists. 3252 */ 3253 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3254 ViewParent parent = focused.getParent(); 3255 while (parent instanceof ViewGroup) { 3256 final ViewGroup vgParent = (ViewGroup) parent; 3257 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3258 && vgParent.isFocusableInTouchMode()) { 3259 return vgParent; 3260 } 3261 if (vgParent.isRootNamespace()) { 3262 return null; 3263 } else { 3264 parent = vgParent.getParent(); 3265 } 3266 } 3267 return null; 3268 } 3269 3270 private boolean leaveTouchMode() { 3271 if (mView != null) { 3272 if (mView.hasFocus()) { 3273 View focusedView = mView.findFocus(); 3274 if (!(focusedView instanceof ViewGroup)) { 3275 // some view has focus, let it keep it 3276 return false; 3277 } else if (((ViewGroup) focusedView).getDescendantFocusability() != 3278 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3279 // some view group has focus, and doesn't prefer its children 3280 // over itself for focus, so let them keep it. 3281 return false; 3282 } 3283 } 3284 3285 // find the best view to give focus to in this brave new non-touch-mode 3286 // world 3287 final View focused = focusSearch(null, View.FOCUS_DOWN); 3288 if (focused != null) { 3289 return focused.requestFocus(View.FOCUS_DOWN); 3290 } 3291 } 3292 return false; 3293 } 3294 3295 /** 3296 * Base class for implementing a stage in the chain of responsibility 3297 * for processing input events. 3298 * <p> 3299 * Events are delivered to the stage by the {@link #deliver} method. The stage 3300 * then has the choice of finishing the event or forwarding it to the next stage. 3301 * </p> 3302 */ 3303 abstract class InputStage { 3304 private final InputStage mNext; 3305 3306 protected static final int FORWARD = 0; 3307 protected static final int FINISH_HANDLED = 1; 3308 protected static final int FINISH_NOT_HANDLED = 2; 3309 3310 /** 3311 * Creates an input stage. 3312 * @param next The next stage to which events should be forwarded. 3313 */ 3314 public InputStage(InputStage next) { 3315 mNext = next; 3316 } 3317 3318 /** 3319 * Delivers an event to be processed. 3320 */ 3321 public final void deliver(QueuedInputEvent q) { 3322 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) { 3323 forward(q); 3324 } else if (mView == null || !mAdded) { 3325 Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent); 3326 finish(q, false); 3327 } else if (!mAttachInfo.mHasWindowFocus && 3328 !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER) && 3329 !isTerminalInputEvent(q.mEvent)) { 3330 // If this is a focused event and the window doesn't currently have input focus, 3331 // then drop this event. This could be an event that came back from the previous 3332 // stage but the window has lost focus in the meantime. 3333 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent); 3334 finish(q, false); 3335 } else { 3336 apply(q, onProcess(q)); 3337 } 3338 } 3339 3340 /** 3341 * Marks the the input event as finished then forwards it to the next stage. 3342 */ 3343 protected void finish(QueuedInputEvent q, boolean handled) { 3344 q.mFlags |= QueuedInputEvent.FLAG_FINISHED; 3345 if (handled) { 3346 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED; 3347 } 3348 forward(q); 3349 } 3350 3351 /** 3352 * Forwards the event to the next stage. 3353 */ 3354 protected void forward(QueuedInputEvent q) { 3355 onDeliverToNext(q); 3356 } 3357 3358 /** 3359 * Applies a result code from {@link #onProcess} to the specified event. 3360 */ 3361 protected void apply(QueuedInputEvent q, int result) { 3362 if (result == FORWARD) { 3363 forward(q); 3364 } else if (result == FINISH_HANDLED) { 3365 finish(q, true); 3366 } else if (result == FINISH_NOT_HANDLED) { 3367 finish(q, false); 3368 } else { 3369 throw new IllegalArgumentException("Invalid result: " + result); 3370 } 3371 } 3372 3373 /** 3374 * Called when an event is ready to be processed. 3375 * @return A result code indicating how the event was handled. 3376 */ 3377 protected int onProcess(QueuedInputEvent q) { 3378 return FORWARD; 3379 } 3380 3381 /** 3382 * Called when an event is being delivered to the next stage. 3383 */ 3384 protected void onDeliverToNext(QueuedInputEvent q) { 3385 if (mNext != null) { 3386 mNext.deliver(q); 3387 } else { 3388 finishInputEvent(q); 3389 } 3390 } 3391 } 3392 3393 /** 3394 * Base class for implementing an input pipeline stage that supports 3395 * asynchronous and out-of-order processing of input events. 3396 * <p> 3397 * In addition to what a normal input stage can do, an asynchronous 3398 * input stage may also defer an input event that has been delivered to it 3399 * and finish or forward it later. 3400 * </p> 3401 */ 3402 abstract class AsyncInputStage extends InputStage { 3403 private final String mTraceCounter; 3404 3405 private QueuedInputEvent mQueueHead; 3406 private QueuedInputEvent mQueueTail; 3407 private int mQueueLength; 3408 3409 protected static final int DEFER = 3; 3410 3411 /** 3412 * Creates an asynchronous input stage. 3413 * @param next The next stage to which events should be forwarded. 3414 * @param traceCounter The name of a counter to record the size of 3415 * the queue of pending events. 3416 */ 3417 public AsyncInputStage(InputStage next, String traceCounter) { 3418 super(next); 3419 mTraceCounter = traceCounter; 3420 } 3421 3422 /** 3423 * Marks the event as deferred, which is to say that it will be handled 3424 * asynchronously. The caller is responsible for calling {@link #forward} 3425 * or {@link #finish} later when it is done handling the event. 3426 */ 3427 protected void defer(QueuedInputEvent q) { 3428 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED; 3429 enqueue(q); 3430 } 3431 3432 @Override 3433 protected void forward(QueuedInputEvent q) { 3434 // Clear the deferred flag. 3435 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED; 3436 3437 // Fast path if the queue is empty. 3438 QueuedInputEvent curr = mQueueHead; 3439 if (curr == null) { 3440 super.forward(q); 3441 return; 3442 } 3443 3444 // Determine whether the event must be serialized behind any others 3445 // before it can be delivered to the next stage. This is done because 3446 // deferred events might be handled out of order by the stage. 3447 final int deviceId = q.mEvent.getDeviceId(); 3448 QueuedInputEvent prev = null; 3449 boolean blocked = false; 3450 while (curr != null && curr != q) { 3451 if (!blocked && deviceId == curr.mEvent.getDeviceId()) { 3452 blocked = true; 3453 } 3454 prev = curr; 3455 curr = curr.mNext; 3456 } 3457 3458 // If the event is blocked, then leave it in the queue to be delivered later. 3459 // Note that the event might not yet be in the queue if it was not previously 3460 // deferred so we will enqueue it if needed. 3461 if (blocked) { 3462 if (curr == null) { 3463 enqueue(q); 3464 } 3465 return; 3466 } 3467 3468 // The event is not blocked. Deliver it immediately. 3469 if (curr != null) { 3470 curr = curr.mNext; 3471 dequeue(q, prev); 3472 } 3473 super.forward(q); 3474 3475 // Dequeuing this event may have unblocked successors. Deliver them. 3476 while (curr != null) { 3477 if (deviceId == curr.mEvent.getDeviceId()) { 3478 if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) { 3479 break; 3480 } 3481 QueuedInputEvent next = curr.mNext; 3482 dequeue(curr, prev); 3483 super.forward(curr); 3484 curr = next; 3485 } else { 3486 prev = curr; 3487 curr = curr.mNext; 3488 } 3489 } 3490 } 3491 3492 @Override 3493 protected void apply(QueuedInputEvent q, int result) { 3494 if (result == DEFER) { 3495 defer(q); 3496 } else { 3497 super.apply(q, result); 3498 } 3499 } 3500 3501 private void enqueue(QueuedInputEvent q) { 3502 if (mQueueTail == null) { 3503 mQueueHead = q; 3504 mQueueTail = q; 3505 } else { 3506 mQueueTail.mNext = q; 3507 mQueueTail = q; 3508 } 3509 3510 mQueueLength += 1; 3511 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3512 } 3513 3514 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) { 3515 if (prev == null) { 3516 mQueueHead = q.mNext; 3517 } else { 3518 prev.mNext = q.mNext; 3519 } 3520 if (mQueueTail == q) { 3521 mQueueTail = prev; 3522 } 3523 q.mNext = null; 3524 3525 mQueueLength -= 1; 3526 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3527 } 3528 } 3529 3530 /** 3531 * Delivers pre-ime input events to a native activity. 3532 * Does not support pointer events. 3533 */ 3534 final class NativePreImeInputStage extends AsyncInputStage 3535 implements InputQueue.FinishedInputEventCallback { 3536 public NativePreImeInputStage(InputStage next, String traceCounter) { 3537 super(next, traceCounter); 3538 } 3539 3540 @Override 3541 protected int onProcess(QueuedInputEvent q) { 3542 if (mInputQueue != null && q.mEvent instanceof KeyEvent) { 3543 mInputQueue.sendInputEvent(q.mEvent, q, true, this); 3544 return DEFER; 3545 } 3546 return FORWARD; 3547 } 3548 3549 @Override 3550 public void onFinishedInputEvent(Object token, boolean handled) { 3551 QueuedInputEvent q = (QueuedInputEvent)token; 3552 if (handled) { 3553 finish(q, true); 3554 return; 3555 } 3556 forward(q); 3557 } 3558 } 3559 3560 /** 3561 * Delivers pre-ime input events to the view hierarchy. 3562 * Does not support pointer events. 3563 */ 3564 final class ViewPreImeInputStage extends InputStage { 3565 public ViewPreImeInputStage(InputStage next) { 3566 super(next); 3567 } 3568 3569 @Override 3570 protected int onProcess(QueuedInputEvent q) { 3571 if (q.mEvent instanceof KeyEvent) { 3572 return processKeyEvent(q); 3573 } 3574 return FORWARD; 3575 } 3576 3577 private int processKeyEvent(QueuedInputEvent q) { 3578 final KeyEvent event = (KeyEvent)q.mEvent; 3579 if (mView.dispatchKeyEventPreIme(event)) { 3580 return FINISH_HANDLED; 3581 } 3582 return FORWARD; 3583 } 3584 } 3585 3586 /** 3587 * Delivers input events to the ime. 3588 * Does not support pointer events. 3589 */ 3590 final class ImeInputStage extends AsyncInputStage 3591 implements InputMethodManager.FinishedInputEventCallback { 3592 public ImeInputStage(InputStage next, String traceCounter) { 3593 super(next, traceCounter); 3594 } 3595 3596 @Override 3597 protected int onProcess(QueuedInputEvent q) { 3598 if (mLastWasImTarget) { 3599 InputMethodManager imm = InputMethodManager.peekInstance(); 3600 if (imm != null) { 3601 final InputEvent event = q.mEvent; 3602 if (DEBUG_IMF) Log.v(TAG, "Sending input event to IME: " + event); 3603 int result = imm.dispatchInputEvent(event, q, this, mHandler); 3604 if (result == InputMethodManager.DISPATCH_HANDLED) { 3605 return FINISH_HANDLED; 3606 } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) { 3607 return FINISH_NOT_HANDLED; 3608 } else { 3609 return DEFER; // callback will be invoked later 3610 } 3611 } 3612 } 3613 return FORWARD; 3614 } 3615 3616 @Override 3617 public void onFinishedInputEvent(Object token, boolean handled) { 3618 QueuedInputEvent q = (QueuedInputEvent)token; 3619 if (handled) { 3620 finish(q, true); 3621 return; 3622 } 3623 forward(q); 3624 } 3625 } 3626 3627 /** 3628 * Performs early processing of post-ime input events. 3629 */ 3630 final class EarlyPostImeInputStage extends InputStage { 3631 public EarlyPostImeInputStage(InputStage next) { 3632 super(next); 3633 } 3634 3635 @Override 3636 protected int onProcess(QueuedInputEvent q) { 3637 if (q.mEvent instanceof KeyEvent) { 3638 return processKeyEvent(q); 3639 } else { 3640 final int source = q.mEvent.getSource(); 3641 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3642 return processPointerEvent(q); 3643 } 3644 } 3645 return FORWARD; 3646 } 3647 3648 private int processKeyEvent(QueuedInputEvent q) { 3649 final KeyEvent event = (KeyEvent)q.mEvent; 3650 3651 // If the key's purpose is to exit touch mode then we consume it 3652 // and consider it handled. 3653 if (checkForLeavingTouchModeAndConsume(event)) { 3654 return FINISH_HANDLED; 3655 } 3656 3657 // Make sure the fallback event policy sees all keys that will be 3658 // delivered to the view hierarchy. 3659 mFallbackEventHandler.preDispatchKeyEvent(event); 3660 return FORWARD; 3661 } 3662 3663 private int processPointerEvent(QueuedInputEvent q) { 3664 final MotionEvent event = (MotionEvent)q.mEvent; 3665 3666 // Translate the pointer event for compatibility, if needed. 3667 if (mTranslator != null) { 3668 mTranslator.translateEventInScreenToAppWindow(event); 3669 } 3670 3671 // Enter touch mode on down or scroll. 3672 final int action = event.getAction(); 3673 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3674 ensureTouchMode(true); 3675 } 3676 3677 // Offset the scroll position. 3678 if (mCurScrollY != 0) { 3679 event.offsetLocation(0, mCurScrollY); 3680 } 3681 3682 // Remember the touch position for possible drag-initiation. 3683 if (event.isTouchEvent()) { 3684 mLastTouchPoint.x = event.getRawX(); 3685 mLastTouchPoint.y = event.getRawY(); 3686 } 3687 return FORWARD; 3688 } 3689 } 3690 3691 /** 3692 * Delivers post-ime input events to a native activity. 3693 */ 3694 final class NativePostImeInputStage extends AsyncInputStage 3695 implements InputQueue.FinishedInputEventCallback { 3696 public NativePostImeInputStage(InputStage next, String traceCounter) { 3697 super(next, traceCounter); 3698 } 3699 3700 @Override 3701 protected int onProcess(QueuedInputEvent q) { 3702 if (mInputQueue != null) { 3703 mInputQueue.sendInputEvent(q.mEvent, q, false, this); 3704 return DEFER; 3705 } 3706 return FORWARD; 3707 } 3708 3709 @Override 3710 public void onFinishedInputEvent(Object token, boolean handled) { 3711 QueuedInputEvent q = (QueuedInputEvent)token; 3712 if (handled) { 3713 finish(q, true); 3714 return; 3715 } 3716 forward(q); 3717 } 3718 } 3719 3720 /** 3721 * Delivers post-ime input events to the view hierarchy. 3722 */ 3723 final class ViewPostImeInputStage extends InputStage { 3724 public ViewPostImeInputStage(InputStage next) { 3725 super(next); 3726 } 3727 3728 @Override 3729 protected int onProcess(QueuedInputEvent q) { 3730 if (q.mEvent instanceof KeyEvent) { 3731 return processKeyEvent(q); 3732 } else { 3733 final int source = q.mEvent.getSource(); 3734 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3735 return processPointerEvent(q); 3736 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3737 return processTrackballEvent(q); 3738 } else { 3739 return processGenericMotionEvent(q); 3740 } 3741 } 3742 } 3743 3744 private int processKeyEvent(QueuedInputEvent q) { 3745 final KeyEvent event = (KeyEvent)q.mEvent; 3746 3747 // Deliver the key to the view hierarchy. 3748 if (mView.dispatchKeyEvent(event)) { 3749 return FINISH_HANDLED; 3750 } 3751 3752 // If the Control modifier is held, try to interpret the key as a shortcut. 3753 if (event.getAction() == KeyEvent.ACTION_DOWN 3754 && event.isCtrlPressed() 3755 && event.getRepeatCount() == 0 3756 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3757 if (mView.dispatchKeyShortcutEvent(event)) { 3758 return FINISH_HANDLED; 3759 } 3760 } 3761 3762 // Apply the fallback event policy. 3763 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3764 return FINISH_HANDLED; 3765 } 3766 3767 // Handle automatic focus changes. 3768 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3769 int direction = 0; 3770 switch (event.getKeyCode()) { 3771 case KeyEvent.KEYCODE_DPAD_LEFT: 3772 if (event.hasNoModifiers()) { 3773 direction = View.FOCUS_LEFT; 3774 } 3775 break; 3776 case KeyEvent.KEYCODE_DPAD_RIGHT: 3777 if (event.hasNoModifiers()) { 3778 direction = View.FOCUS_RIGHT; 3779 } 3780 break; 3781 case KeyEvent.KEYCODE_DPAD_UP: 3782 if (event.hasNoModifiers()) { 3783 direction = View.FOCUS_UP; 3784 } 3785 break; 3786 case KeyEvent.KEYCODE_DPAD_DOWN: 3787 if (event.hasNoModifiers()) { 3788 direction = View.FOCUS_DOWN; 3789 } 3790 break; 3791 case KeyEvent.KEYCODE_TAB: 3792 if (event.hasNoModifiers()) { 3793 direction = View.FOCUS_FORWARD; 3794 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3795 direction = View.FOCUS_BACKWARD; 3796 } 3797 break; 3798 } 3799 if (direction != 0) { 3800 View focused = mView.findFocus(); 3801 if (focused != null) { 3802 View v = focused.focusSearch(direction); 3803 if (v != null && v != focused) { 3804 // do the math the get the interesting rect 3805 // of previous focused into the coord system of 3806 // newly focused view 3807 focused.getFocusedRect(mTempRect); 3808 if (mView instanceof ViewGroup) { 3809 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3810 focused, mTempRect); 3811 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3812 v, mTempRect); 3813 } 3814 if (v.requestFocus(direction, mTempRect)) { 3815 playSoundEffect(SoundEffectConstants 3816 .getContantForFocusDirection(direction)); 3817 return FINISH_HANDLED; 3818 } 3819 } 3820 3821 // Give the focused view a last chance to handle the dpad key. 3822 if (mView.dispatchUnhandledMove(focused, direction)) { 3823 return FINISH_HANDLED; 3824 } 3825 } else { 3826 // find the best view to give focus to in this non-touch-mode with no-focus 3827 View v = focusSearch(null, direction); 3828 if (v != null && v.requestFocus(direction)) { 3829 return FINISH_HANDLED; 3830 } 3831 } 3832 } 3833 } 3834 return FORWARD; 3835 } 3836 3837 private int processPointerEvent(QueuedInputEvent q) { 3838 final MotionEvent event = (MotionEvent)q.mEvent; 3839 3840 if (mView.dispatchPointerEvent(event)) { 3841 return FINISH_HANDLED; 3842 } 3843 return FORWARD; 3844 } 3845 3846 private int processTrackballEvent(QueuedInputEvent q) { 3847 final MotionEvent event = (MotionEvent)q.mEvent; 3848 3849 if (mView.dispatchTrackballEvent(event)) { 3850 return FINISH_HANDLED; 3851 } 3852 return FORWARD; 3853 } 3854 3855 private int processGenericMotionEvent(QueuedInputEvent q) { 3856 final MotionEvent event = (MotionEvent)q.mEvent; 3857 3858 // Deliver the event to the view. 3859 if (mView.dispatchGenericMotionEvent(event)) { 3860 return FINISH_HANDLED; 3861 } 3862 return FORWARD; 3863 } 3864 } 3865 3866 /** 3867 * Performs synthesis of new input events from unhandled input events. 3868 */ 3869 final class SyntheticInputStage extends InputStage { 3870 private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler(); 3871 private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler(); 3872 private final SyntheticTouchNavigationHandler mTouchNavigation = 3873 new SyntheticTouchNavigationHandler(); 3874 3875 public SyntheticInputStage() { 3876 super(null); 3877 } 3878 3879 @Override 3880 protected int onProcess(QueuedInputEvent q) { 3881 q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED; 3882 if (q.mEvent instanceof MotionEvent) { 3883 final MotionEvent event = (MotionEvent)q.mEvent; 3884 final int source = event.getSource(); 3885 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3886 mTrackball.process(event); 3887 return FINISH_HANDLED; 3888 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 3889 mJoystick.process(event); 3890 return FINISH_HANDLED; 3891 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 3892 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 3893 mTouchNavigation.process(event); 3894 return FINISH_HANDLED; 3895 } 3896 } 3897 return FORWARD; 3898 } 3899 3900 @Override 3901 protected void onDeliverToNext(QueuedInputEvent q) { 3902 if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) { 3903 // Cancel related synthetic events if any prior stage has handled the event. 3904 if (q.mEvent instanceof MotionEvent) { 3905 final MotionEvent event = (MotionEvent)q.mEvent; 3906 final int source = event.getSource(); 3907 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3908 mTrackball.cancel(event); 3909 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 3910 mJoystick.cancel(event); 3911 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 3912 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 3913 mTouchNavigation.cancel(event); 3914 } 3915 } 3916 } 3917 super.onDeliverToNext(q); 3918 } 3919 } 3920 3921 /** 3922 * Creates dpad events from unhandled trackball movements. 3923 */ 3924 final class SyntheticTrackballHandler { 3925 private final TrackballAxis mX = new TrackballAxis(); 3926 private final TrackballAxis mY = new TrackballAxis(); 3927 private long mLastTime; 3928 3929 public void process(MotionEvent event) { 3930 // Translate the trackball event into DPAD keys and try to deliver those. 3931 long curTime = SystemClock.uptimeMillis(); 3932 if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) { 3933 // It has been too long since the last movement, 3934 // so restart at the beginning. 3935 mX.reset(0); 3936 mY.reset(0); 3937 mLastTime = curTime; 3938 } 3939 3940 final int action = event.getAction(); 3941 final int metaState = event.getMetaState(); 3942 switch (action) { 3943 case MotionEvent.ACTION_DOWN: 3944 mX.reset(2); 3945 mY.reset(2); 3946 enqueueInputEvent(new KeyEvent(curTime, curTime, 3947 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3948 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3949 InputDevice.SOURCE_KEYBOARD)); 3950 break; 3951 case MotionEvent.ACTION_UP: 3952 mX.reset(2); 3953 mY.reset(2); 3954 enqueueInputEvent(new KeyEvent(curTime, curTime, 3955 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3956 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3957 InputDevice.SOURCE_KEYBOARD)); 3958 break; 3959 } 3960 3961 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step=" 3962 + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration 3963 + " move=" + event.getX() 3964 + " / Y=" + mY.position + " step=" 3965 + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration 3966 + " move=" + event.getY()); 3967 final float xOff = mX.collect(event.getX(), event.getEventTime(), "X"); 3968 final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y"); 3969 3970 // Generate DPAD events based on the trackball movement. 3971 // We pick the axis that has moved the most as the direction of 3972 // the DPAD. When we generate DPAD events for one axis, then the 3973 // other axis is reset -- we don't want to perform DPAD jumps due 3974 // to slight movements in the trackball when making major movements 3975 // along the other axis. 3976 int keycode = 0; 3977 int movement = 0; 3978 float accel = 1; 3979 if (xOff > yOff) { 3980 movement = mX.generate(); 3981 if (movement != 0) { 3982 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3983 : KeyEvent.KEYCODE_DPAD_LEFT; 3984 accel = mX.acceleration; 3985 mY.reset(2); 3986 } 3987 } else if (yOff > 0) { 3988 movement = mY.generate(); 3989 if (movement != 0) { 3990 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3991 : KeyEvent.KEYCODE_DPAD_UP; 3992 accel = mY.acceleration; 3993 mX.reset(2); 3994 } 3995 } 3996 3997 if (keycode != 0) { 3998 if (movement < 0) movement = -movement; 3999 int accelMovement = (int)(movement * accel); 4000 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 4001 + " accelMovement=" + accelMovement 4002 + " accel=" + accel); 4003 if (accelMovement > movement) { 4004 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4005 + keycode); 4006 movement--; 4007 int repeatCount = accelMovement - movement; 4008 enqueueInputEvent(new KeyEvent(curTime, curTime, 4009 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 4010 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4011 InputDevice.SOURCE_KEYBOARD)); 4012 } 4013 while (movement > 0) { 4014 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4015 + keycode); 4016 movement--; 4017 curTime = SystemClock.uptimeMillis(); 4018 enqueueInputEvent(new KeyEvent(curTime, curTime, 4019 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 4020 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4021 InputDevice.SOURCE_KEYBOARD)); 4022 enqueueInputEvent(new KeyEvent(curTime, curTime, 4023 KeyEvent.ACTION_UP, keycode, 0, metaState, 4024 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4025 InputDevice.SOURCE_KEYBOARD)); 4026 } 4027 mLastTime = curTime; 4028 } 4029 } 4030 4031 public void cancel(MotionEvent event) { 4032 mLastTime = Integer.MIN_VALUE; 4033 4034 // If we reach this, we consumed a trackball event. 4035 // Because we will not translate the trackball event into a key event, 4036 // touch mode will not exit, so we exit touch mode here. 4037 if (mView != null && mAdded) { 4038 ensureTouchMode(false); 4039 } 4040 } 4041 } 4042 4043 /** 4044 * Maintains state information for a single trackball axis, generating 4045 * discrete (DPAD) movements based on raw trackball motion. 4046 */ 4047 static final class TrackballAxis { 4048 /** 4049 * The maximum amount of acceleration we will apply. 4050 */ 4051 static final float MAX_ACCELERATION = 20; 4052 4053 /** 4054 * The maximum amount of time (in milliseconds) between events in order 4055 * for us to consider the user to be doing fast trackball movements, 4056 * and thus apply an acceleration. 4057 */ 4058 static final long FAST_MOVE_TIME = 150; 4059 4060 /** 4061 * Scaling factor to the time (in milliseconds) between events to how 4062 * much to multiple/divide the current acceleration. When movement 4063 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4064 * FAST_MOVE_TIME it divides it. 4065 */ 4066 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4067 4068 static final float FIRST_MOVEMENT_THRESHOLD = 0.5f; 4069 static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f; 4070 static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f; 4071 4072 float position; 4073 float acceleration = 1; 4074 long lastMoveTime = 0; 4075 int step; 4076 int dir; 4077 int nonAccelMovement; 4078 4079 void reset(int _step) { 4080 position = 0; 4081 acceleration = 1; 4082 lastMoveTime = 0; 4083 step = _step; 4084 dir = 0; 4085 } 4086 4087 /** 4088 * Add trackball movement into the state. If the direction of movement 4089 * has been reversed, the state is reset before adding the 4090 * movement (so that you don't have to compensate for any previously 4091 * collected movement before see the result of the movement in the 4092 * new direction). 4093 * 4094 * @return Returns the absolute value of the amount of movement 4095 * collected so far. 4096 */ 4097 float collect(float off, long time, String axis) { 4098 long normTime; 4099 if (off > 0) { 4100 normTime = (long)(off * FAST_MOVE_TIME); 4101 if (dir < 0) { 4102 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4103 position = 0; 4104 step = 0; 4105 acceleration = 1; 4106 lastMoveTime = 0; 4107 } 4108 dir = 1; 4109 } else if (off < 0) { 4110 normTime = (long)((-off) * FAST_MOVE_TIME); 4111 if (dir > 0) { 4112 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4113 position = 0; 4114 step = 0; 4115 acceleration = 1; 4116 lastMoveTime = 0; 4117 } 4118 dir = -1; 4119 } else { 4120 normTime = 0; 4121 } 4122 4123 // The number of milliseconds between each movement that is 4124 // considered "normal" and will not result in any acceleration 4125 // or deceleration, scaled by the offset we have here. 4126 if (normTime > 0) { 4127 long delta = time - lastMoveTime; 4128 lastMoveTime = time; 4129 float acc = acceleration; 4130 if (delta < normTime) { 4131 // The user is scrolling rapidly, so increase acceleration. 4132 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4133 if (scale > 1) acc *= scale; 4134 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4135 + off + " normTime=" + normTime + " delta=" + delta 4136 + " scale=" + scale + " acc=" + acc); 4137 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4138 } else { 4139 // The user is scrolling slowly, so decrease acceleration. 4140 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4141 if (scale > 1) acc /= scale; 4142 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4143 + off + " normTime=" + normTime + " delta=" + delta 4144 + " scale=" + scale + " acc=" + acc); 4145 acceleration = acc > 1 ? acc : 1; 4146 } 4147 } 4148 position += off; 4149 return Math.abs(position); 4150 } 4151 4152 /** 4153 * Generate the number of discrete movement events appropriate for 4154 * the currently collected trackball movement. 4155 * 4156 * @return Returns the number of discrete movements, either positive 4157 * or negative, or 0 if there is not enough trackball movement yet 4158 * for a discrete movement. 4159 */ 4160 int generate() { 4161 int movement = 0; 4162 nonAccelMovement = 0; 4163 do { 4164 final int dir = position >= 0 ? 1 : -1; 4165 switch (step) { 4166 // If we are going to execute the first step, then we want 4167 // to do this as soon as possible instead of waiting for 4168 // a full movement, in order to make things look responsive. 4169 case 0: 4170 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) { 4171 return movement; 4172 } 4173 movement += dir; 4174 nonAccelMovement += dir; 4175 step = 1; 4176 break; 4177 // If we have generated the first movement, then we need 4178 // to wait for the second complete trackball motion before 4179 // generating the second discrete movement. 4180 case 1: 4181 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) { 4182 return movement; 4183 } 4184 movement += dir; 4185 nonAccelMovement += dir; 4186 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir; 4187 step = 2; 4188 break; 4189 // After the first two, we generate discrete movements 4190 // consistently with the trackball, applying an acceleration 4191 // if the trackball is moving quickly. This is a simple 4192 // acceleration on top of what we already compute based 4193 // on how quickly the wheel is being turned, to apply 4194 // a longer increasing acceleration to continuous movement 4195 // in one direction. 4196 default: 4197 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) { 4198 return movement; 4199 } 4200 movement += dir; 4201 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD; 4202 float acc = acceleration; 4203 acc *= 1.1f; 4204 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4205 break; 4206 } 4207 } while (true); 4208 } 4209 } 4210 4211 /** 4212 * Creates dpad events from unhandled joystick movements. 4213 */ 4214 final class SyntheticJoystickHandler extends Handler { 4215 private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1; 4216 private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2; 4217 4218 private int mLastXDirection; 4219 private int mLastYDirection; 4220 private int mLastXKeyCode; 4221 private int mLastYKeyCode; 4222 4223 public SyntheticJoystickHandler() { 4224 super(true); 4225 } 4226 4227 @Override 4228 public void handleMessage(Message msg) { 4229 switch (msg.what) { 4230 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT: 4231 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: { 4232 KeyEvent oldEvent = (KeyEvent)msg.obj; 4233 KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent, 4234 SystemClock.uptimeMillis(), 4235 oldEvent.getRepeatCount() + 1); 4236 if (mAttachInfo.mHasWindowFocus) { 4237 enqueueInputEvent(e); 4238 Message m = obtainMessage(msg.what, e); 4239 m.setAsynchronous(true); 4240 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay()); 4241 } 4242 } break; 4243 } 4244 } 4245 4246 public void process(MotionEvent event) { 4247 update(event, true); 4248 } 4249 4250 public void cancel(MotionEvent event) { 4251 update(event, false); 4252 } 4253 4254 private void update(MotionEvent event, boolean synthesizeNewKeys) { 4255 final long time = event.getEventTime(); 4256 final int metaState = event.getMetaState(); 4257 final int deviceId = event.getDeviceId(); 4258 final int source = event.getSource(); 4259 4260 int xDirection = joystickAxisValueToDirection( 4261 event.getAxisValue(MotionEvent.AXIS_HAT_X)); 4262 if (xDirection == 0) { 4263 xDirection = joystickAxisValueToDirection(event.getX()); 4264 } 4265 4266 int yDirection = joystickAxisValueToDirection( 4267 event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 4268 if (yDirection == 0) { 4269 yDirection = joystickAxisValueToDirection(event.getY()); 4270 } 4271 4272 if (xDirection != mLastXDirection) { 4273 if (mLastXKeyCode != 0) { 4274 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4275 enqueueInputEvent(new KeyEvent(time, time, 4276 KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState, 4277 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4278 mLastXKeyCode = 0; 4279 } 4280 4281 mLastXDirection = xDirection; 4282 4283 if (xDirection != 0 && synthesizeNewKeys) { 4284 mLastXKeyCode = xDirection > 0 4285 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 4286 final KeyEvent e = new KeyEvent(time, time, 4287 KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState, 4288 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4289 enqueueInputEvent(e); 4290 Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e); 4291 m.setAsynchronous(true); 4292 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4293 } 4294 } 4295 4296 if (yDirection != mLastYDirection) { 4297 if (mLastYKeyCode != 0) { 4298 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4299 enqueueInputEvent(new KeyEvent(time, time, 4300 KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState, 4301 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4302 mLastYKeyCode = 0; 4303 } 4304 4305 mLastYDirection = yDirection; 4306 4307 if (yDirection != 0 && synthesizeNewKeys) { 4308 mLastYKeyCode = yDirection > 0 4309 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 4310 final KeyEvent e = new KeyEvent(time, time, 4311 KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState, 4312 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4313 enqueueInputEvent(e); 4314 Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e); 4315 m.setAsynchronous(true); 4316 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4317 } 4318 } 4319 } 4320 4321 private int joystickAxisValueToDirection(float value) { 4322 if (value >= 0.5f) { 4323 return 1; 4324 } else if (value <= -0.5f) { 4325 return -1; 4326 } else { 4327 return 0; 4328 } 4329 } 4330 } 4331 4332 /** 4333 * Creates dpad events from unhandled touch navigation movements. 4334 */ 4335 final class SyntheticTouchNavigationHandler extends Handler { 4336 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler"; 4337 private static final boolean LOCAL_DEBUG = false; 4338 4339 // Assumed nominal width and height in millimeters of a touch navigation pad, 4340 // if no resolution information is available from the input system. 4341 private static final float DEFAULT_WIDTH_MILLIMETERS = 48; 4342 private static final float DEFAULT_HEIGHT_MILLIMETERS = 48; 4343 4344 /* TODO: These constants should eventually be moved to ViewConfiguration. */ 4345 4346 // Tap timeout in milliseconds. 4347 private static final int TAP_TIMEOUT = 250; 4348 4349 // The maximum distance traveled for a gesture to be considered a tap in millimeters. 4350 private static final int TAP_SLOP_MILLIMETERS = 5; 4351 4352 // The nominal distance traveled to move by one unit. 4353 private static final int TICK_DISTANCE_MILLIMETERS = 12; 4354 4355 // Minimum and maximum fling velocity in ticks per second. 4356 // The minimum velocity should be set such that we perform enough ticks per 4357 // second that the fling appears to be fluid. For example, if we set the minimum 4358 // to 2 ticks per second, then there may be up to half a second delay between the next 4359 // to last and last ticks which is noticeably discrete and jerky. This value should 4360 // probably not be set to anything less than about 4. 4361 // If fling accuracy is a problem then consider tuning the tick distance instead. 4362 private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f; 4363 private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f; 4364 4365 // Fling velocity decay factor applied after each new key is emitted. 4366 // This parameter controls the deceleration and overall duration of the fling. 4367 // The fling stops automatically when its velocity drops below the minimum 4368 // fling velocity defined above. 4369 private static final float FLING_TICK_DECAY = 0.8f; 4370 4371 /* The input device that we are tracking. */ 4372 4373 private int mCurrentDeviceId = -1; 4374 private int mCurrentSource; 4375 private boolean mCurrentDeviceSupported; 4376 4377 /* Configuration for the current input device. */ 4378 4379 // The tap timeout and scaled slop. 4380 private int mConfigTapTimeout; 4381 private float mConfigTapSlop; 4382 4383 // The scaled tick distance. A movement of this amount should generally translate 4384 // into a single dpad event in a given direction. 4385 private float mConfigTickDistance; 4386 4387 // The minimum and maximum scaled fling velocity. 4388 private float mConfigMinFlingVelocity; 4389 private float mConfigMaxFlingVelocity; 4390 4391 /* Tracking state. */ 4392 4393 // The velocity tracker for detecting flings. 4394 private VelocityTracker mVelocityTracker; 4395 4396 // The active pointer id, or -1 if none. 4397 private int mActivePointerId = -1; 4398 4399 // Time and location where tracking started. 4400 private long mStartTime; 4401 private float mStartX; 4402 private float mStartY; 4403 4404 // Most recently observed position. 4405 private float mLastX; 4406 private float mLastY; 4407 4408 // Accumulated movement delta since the last direction key was sent. 4409 private float mAccumulatedX; 4410 private float mAccumulatedY; 4411 4412 // Set to true if any movement was delivered to the app. 4413 // Implies that tap slop was exceeded. 4414 private boolean mConsumedMovement; 4415 4416 // The most recently sent key down event. 4417 // The keycode remains set until the direction changes or a fling ends 4418 // so that repeated key events may be generated as required. 4419 private long mPendingKeyDownTime; 4420 private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4421 private int mPendingKeyRepeatCount; 4422 private int mPendingKeyMetaState; 4423 4424 // The current fling velocity while a fling is in progress. 4425 private boolean mFlinging; 4426 private float mFlingVelocity; 4427 4428 public SyntheticTouchNavigationHandler() { 4429 super(true); 4430 } 4431 4432 public void process(MotionEvent event) { 4433 // Update the current device information. 4434 final long time = event.getEventTime(); 4435 final int deviceId = event.getDeviceId(); 4436 final int source = event.getSource(); 4437 if (mCurrentDeviceId != deviceId || mCurrentSource != source) { 4438 finishKeys(time); 4439 finishTracking(time); 4440 mCurrentDeviceId = deviceId; 4441 mCurrentSource = source; 4442 mCurrentDeviceSupported = false; 4443 InputDevice device = event.getDevice(); 4444 if (device != null) { 4445 // In order to support an input device, we must know certain 4446 // characteristics about it, such as its size and resolution. 4447 InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X); 4448 InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y); 4449 if (xRange != null && yRange != null) { 4450 mCurrentDeviceSupported = true; 4451 4452 // Infer the resolution if it not actually known. 4453 float xRes = xRange.getResolution(); 4454 if (xRes <= 0) { 4455 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS; 4456 } 4457 float yRes = yRange.getResolution(); 4458 if (yRes <= 0) { 4459 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS; 4460 } 4461 float nominalRes = (xRes + yRes) * 0.5f; 4462 4463 // Precompute all of the configuration thresholds we will need. 4464 mConfigTapTimeout = TAP_TIMEOUT; 4465 mConfigTapSlop = TAP_SLOP_MILLIMETERS * nominalRes; 4466 mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes; 4467 mConfigMinFlingVelocity = 4468 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4469 mConfigMaxFlingVelocity = 4470 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4471 4472 if (LOCAL_DEBUG) { 4473 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId 4474 + " (" + Integer.toHexString(mCurrentSource) + "): " 4475 + "mConfigTapTimeout=" + mConfigTapTimeout 4476 + ", mConfigTapSlop=" + mConfigTapSlop 4477 + ", mConfigTickDistance=" + mConfigTickDistance 4478 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity 4479 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity); 4480 } 4481 } 4482 } 4483 } 4484 if (!mCurrentDeviceSupported) { 4485 return; 4486 } 4487 4488 // Handle the event. 4489 final int action = event.getActionMasked(); 4490 switch (action) { 4491 case MotionEvent.ACTION_DOWN: { 4492 boolean caughtFling = mFlinging; 4493 finishKeys(time); 4494 finishTracking(time); 4495 mActivePointerId = event.getPointerId(0); 4496 mVelocityTracker = VelocityTracker.obtain(); 4497 mVelocityTracker.addMovement(event); 4498 mStartTime = time; 4499 mStartX = event.getX(); 4500 mStartY = event.getY(); 4501 mLastX = mStartX; 4502 mLastY = mStartY; 4503 mAccumulatedX = 0; 4504 mAccumulatedY = 0; 4505 4506 // If we caught a fling, then pretend that the tap slop has already 4507 // been exceeded to suppress taps whose only purpose is to stop the fling. 4508 mConsumedMovement = caughtFling; 4509 break; 4510 } 4511 4512 case MotionEvent.ACTION_MOVE: 4513 case MotionEvent.ACTION_UP: { 4514 if (mActivePointerId < 0) { 4515 break; 4516 } 4517 final int index = event.findPointerIndex(mActivePointerId); 4518 if (index < 0) { 4519 finishKeys(time); 4520 finishTracking(time); 4521 break; 4522 } 4523 4524 mVelocityTracker.addMovement(event); 4525 final float x = event.getX(index); 4526 final float y = event.getY(index); 4527 mAccumulatedX += x - mLastX; 4528 mAccumulatedY += y - mLastY; 4529 mLastX = x; 4530 mLastY = y; 4531 4532 // Consume any accumulated movement so far. 4533 final int metaState = event.getMetaState(); 4534 consumeAccumulatedMovement(time, metaState); 4535 4536 // Detect taps and flings. 4537 if (action == MotionEvent.ACTION_UP) { 4538 if (!mConsumedMovement 4539 && Math.hypot(mLastX - mStartX, mLastY - mStartY) < mConfigTapSlop 4540 && time <= mStartTime + mConfigTapTimeout) { 4541 // It's a tap! 4542 finishKeys(time); 4543 sendKeyDownOrRepeat(time, KeyEvent.KEYCODE_DPAD_CENTER, metaState); 4544 sendKeyUp(time); 4545 } else if (mConsumedMovement 4546 && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4547 // It might be a fling. 4548 mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity); 4549 final float vx = mVelocityTracker.getXVelocity(mActivePointerId); 4550 final float vy = mVelocityTracker.getYVelocity(mActivePointerId); 4551 if (!startFling(time, vx, vy)) { 4552 finishKeys(time); 4553 } 4554 } 4555 finishTracking(time); 4556 } 4557 break; 4558 } 4559 4560 case MotionEvent.ACTION_CANCEL: { 4561 finishKeys(time); 4562 finishTracking(time); 4563 break; 4564 } 4565 } 4566 } 4567 4568 public void cancel(MotionEvent event) { 4569 if (mCurrentDeviceId == event.getDeviceId() 4570 && mCurrentSource == event.getSource()) { 4571 final long time = event.getEventTime(); 4572 finishKeys(time); 4573 finishTracking(time); 4574 } 4575 } 4576 4577 private void finishKeys(long time) { 4578 cancelFling(); 4579 sendKeyUp(time); 4580 } 4581 4582 private void finishTracking(long time) { 4583 if (mActivePointerId >= 0) { 4584 mActivePointerId = -1; 4585 mVelocityTracker.recycle(); 4586 mVelocityTracker = null; 4587 } 4588 } 4589 4590 private void consumeAccumulatedMovement(long time, int metaState) { 4591 final float absX = Math.abs(mAccumulatedX); 4592 final float absY = Math.abs(mAccumulatedY); 4593 if (absX >= absY) { 4594 if (absX >= mConfigTickDistance) { 4595 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX, 4596 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT); 4597 mAccumulatedY = 0; 4598 mConsumedMovement = true; 4599 } 4600 } else { 4601 if (absY >= mConfigTickDistance) { 4602 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY, 4603 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN); 4604 mAccumulatedX = 0; 4605 mConsumedMovement = true; 4606 } 4607 } 4608 } 4609 4610 private float consumeAccumulatedMovement(long time, int metaState, 4611 float accumulator, int negativeKeyCode, int positiveKeyCode) { 4612 while (accumulator <= -mConfigTickDistance) { 4613 sendKeyDownOrRepeat(time, negativeKeyCode, metaState); 4614 accumulator += mConfigTickDistance; 4615 } 4616 while (accumulator >= mConfigTickDistance) { 4617 sendKeyDownOrRepeat(time, positiveKeyCode, metaState); 4618 accumulator -= mConfigTickDistance; 4619 } 4620 return accumulator; 4621 } 4622 4623 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) { 4624 if (mPendingKeyCode != keyCode) { 4625 sendKeyUp(time); 4626 mPendingKeyDownTime = time; 4627 mPendingKeyCode = keyCode; 4628 mPendingKeyRepeatCount = 0; 4629 } else { 4630 mPendingKeyRepeatCount += 1; 4631 } 4632 mPendingKeyMetaState = metaState; 4633 4634 // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1 4635 // but it doesn't quite make sense when simulating the events in this way. 4636 if (LOCAL_DEBUG) { 4637 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode 4638 + ", repeatCount=" + mPendingKeyRepeatCount 4639 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4640 } 4641 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4642 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount, 4643 mPendingKeyMetaState, mCurrentDeviceId, 4644 KeyEvent.FLAG_FALLBACK, mCurrentSource)); 4645 } 4646 4647 private void sendKeyUp(long time) { 4648 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4649 if (LOCAL_DEBUG) { 4650 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode 4651 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4652 } 4653 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4654 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState, 4655 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK, 4656 mCurrentSource)); 4657 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4658 } 4659 } 4660 4661 private boolean startFling(long time, float vx, float vy) { 4662 if (LOCAL_DEBUG) { 4663 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy 4664 + ", min=" + mConfigMinFlingVelocity); 4665 } 4666 4667 // Flings must be oriented in the same direction as the preceding movements. 4668 switch (mPendingKeyCode) { 4669 case KeyEvent.KEYCODE_DPAD_LEFT: 4670 if (-vx >= mConfigMinFlingVelocity 4671 && Math.abs(vy) < mConfigMinFlingVelocity) { 4672 mFlingVelocity = -vx; 4673 break; 4674 } 4675 return false; 4676 4677 case KeyEvent.KEYCODE_DPAD_RIGHT: 4678 if (vx >= mConfigMinFlingVelocity 4679 && Math.abs(vy) < mConfigMinFlingVelocity) { 4680 mFlingVelocity = vx; 4681 break; 4682 } 4683 return false; 4684 4685 case KeyEvent.KEYCODE_DPAD_UP: 4686 if (-vy >= mConfigMinFlingVelocity 4687 && Math.abs(vx) < mConfigMinFlingVelocity) { 4688 mFlingVelocity = -vy; 4689 break; 4690 } 4691 return false; 4692 4693 case KeyEvent.KEYCODE_DPAD_DOWN: 4694 if (vy >= mConfigMinFlingVelocity 4695 && Math.abs(vx) < mConfigMinFlingVelocity) { 4696 mFlingVelocity = vy; 4697 break; 4698 } 4699 return false; 4700 } 4701 4702 // Post the first fling event. 4703 mFlinging = postFling(time); 4704 return mFlinging; 4705 } 4706 4707 private boolean postFling(long time) { 4708 // The idea here is to estimate the time when the pointer would have 4709 // traveled one tick distance unit given the current fling velocity. 4710 // This effect creates continuity of motion. 4711 if (mFlingVelocity >= mConfigMinFlingVelocity) { 4712 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000); 4713 postAtTime(mFlingRunnable, time + delay); 4714 if (LOCAL_DEBUG) { 4715 Log.d(LOCAL_TAG, "Posted fling: velocity=" 4716 + mFlingVelocity + ", delay=" + delay 4717 + ", keyCode=" + mPendingKeyCode); 4718 } 4719 return true; 4720 } 4721 return false; 4722 } 4723 4724 private void cancelFling() { 4725 if (mFlinging) { 4726 removeCallbacks(mFlingRunnable); 4727 mFlinging = false; 4728 } 4729 } 4730 4731 private final Runnable mFlingRunnable = new Runnable() { 4732 @Override 4733 public void run() { 4734 final long time = SystemClock.uptimeMillis(); 4735 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState); 4736 mFlingVelocity *= FLING_TICK_DECAY; 4737 if (!postFling(time)) { 4738 mFlinging = false; 4739 finishKeys(time); 4740 } 4741 } 4742 }; 4743 } 4744 4745 /** 4746 * Returns true if the key is used for keyboard navigation. 4747 * @param keyEvent The key event. 4748 * @return True if the key is used for keyboard navigation. 4749 */ 4750 private static boolean isNavigationKey(KeyEvent keyEvent) { 4751 switch (keyEvent.getKeyCode()) { 4752 case KeyEvent.KEYCODE_DPAD_LEFT: 4753 case KeyEvent.KEYCODE_DPAD_RIGHT: 4754 case KeyEvent.KEYCODE_DPAD_UP: 4755 case KeyEvent.KEYCODE_DPAD_DOWN: 4756 case KeyEvent.KEYCODE_DPAD_CENTER: 4757 case KeyEvent.KEYCODE_PAGE_UP: 4758 case KeyEvent.KEYCODE_PAGE_DOWN: 4759 case KeyEvent.KEYCODE_MOVE_HOME: 4760 case KeyEvent.KEYCODE_MOVE_END: 4761 case KeyEvent.KEYCODE_TAB: 4762 case KeyEvent.KEYCODE_SPACE: 4763 case KeyEvent.KEYCODE_ENTER: 4764 return true; 4765 } 4766 return false; 4767 } 4768 4769 /** 4770 * Returns true if the key is used for typing. 4771 * @param keyEvent The key event. 4772 * @return True if the key is used for typing. 4773 */ 4774 private static boolean isTypingKey(KeyEvent keyEvent) { 4775 return keyEvent.getUnicodeChar() > 0; 4776 } 4777 4778 /** 4779 * See if the key event means we should leave touch mode (and leave touch mode if so). 4780 * @param event The key event. 4781 * @return Whether this key event should be consumed (meaning the act of 4782 * leaving touch mode alone is considered the event). 4783 */ 4784 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 4785 // Only relevant in touch mode. 4786 if (!mAttachInfo.mInTouchMode) { 4787 return false; 4788 } 4789 4790 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 4791 final int action = event.getAction(); 4792 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 4793 return false; 4794 } 4795 4796 // Don't leave touch mode if the IME told us not to. 4797 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 4798 return false; 4799 } 4800 4801 // If the key can be used for keyboard navigation then leave touch mode 4802 // and select a focused view if needed (in ensureTouchMode). 4803 // When a new focused view is selected, we consume the navigation key because 4804 // navigation doesn't make much sense unless a view already has focus so 4805 // the key's purpose is to set focus. 4806 if (isNavigationKey(event)) { 4807 return ensureTouchMode(false); 4808 } 4809 4810 // If the key can be used for typing then leave touch mode 4811 // and select a focused view if needed (in ensureTouchMode). 4812 // Always allow the view to process the typing key. 4813 if (isTypingKey(event)) { 4814 ensureTouchMode(false); 4815 return false; 4816 } 4817 4818 return false; 4819 } 4820 4821 /* drag/drop */ 4822 void setLocalDragState(Object obj) { 4823 mLocalDragState = obj; 4824 } 4825 4826 private void handleDragEvent(DragEvent event) { 4827 // From the root, only drag start/end/location are dispatched. entered/exited 4828 // are determined and dispatched by the viewgroup hierarchy, who then report 4829 // that back here for ultimate reporting back to the framework. 4830 if (mView != null && mAdded) { 4831 final int what = event.mAction; 4832 4833 if (what == DragEvent.ACTION_DRAG_EXITED) { 4834 // A direct EXITED event means that the window manager knows we've just crossed 4835 // a window boundary, so the current drag target within this one must have 4836 // just been exited. Send it the usual notifications and then we're done 4837 // for now. 4838 mView.dispatchDragEvent(event); 4839 } else { 4840 // Cache the drag description when the operation starts, then fill it in 4841 // on subsequent calls as a convenience 4842 if (what == DragEvent.ACTION_DRAG_STARTED) { 4843 mCurrentDragView = null; // Start the current-recipient tracking 4844 mDragDescription = event.mClipDescription; 4845 } else { 4846 event.mClipDescription = mDragDescription; 4847 } 4848 4849 // For events with a [screen] location, translate into window coordinates 4850 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 4851 mDragPoint.set(event.mX, event.mY); 4852 if (mTranslator != null) { 4853 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 4854 } 4855 4856 if (mCurScrollY != 0) { 4857 mDragPoint.offset(0, mCurScrollY); 4858 } 4859 4860 event.mX = mDragPoint.x; 4861 event.mY = mDragPoint.y; 4862 } 4863 4864 // Remember who the current drag target is pre-dispatch 4865 final View prevDragView = mCurrentDragView; 4866 4867 // Now dispatch the drag/drop event 4868 boolean result = mView.dispatchDragEvent(event); 4869 4870 // If we changed apparent drag target, tell the OS about it 4871 if (prevDragView != mCurrentDragView) { 4872 try { 4873 if (prevDragView != null) { 4874 mWindowSession.dragRecipientExited(mWindow); 4875 } 4876 if (mCurrentDragView != null) { 4877 mWindowSession.dragRecipientEntered(mWindow); 4878 } 4879 } catch (RemoteException e) { 4880 Slog.e(TAG, "Unable to note drag target change"); 4881 } 4882 } 4883 4884 // Report the drop result when we're done 4885 if (what == DragEvent.ACTION_DROP) { 4886 mDragDescription = null; 4887 try { 4888 Log.i(TAG, "Reporting drop result: " + result); 4889 mWindowSession.reportDropResult(mWindow, result); 4890 } catch (RemoteException e) { 4891 Log.e(TAG, "Unable to report drop result"); 4892 } 4893 } 4894 4895 // When the drag operation ends, release any local state object 4896 // that may have been in use 4897 if (what == DragEvent.ACTION_DRAG_ENDED) { 4898 setLocalDragState(null); 4899 } 4900 } 4901 } 4902 event.recycle(); 4903 } 4904 4905 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 4906 if (mSeq != args.seq) { 4907 // The sequence has changed, so we need to update our value and make 4908 // sure to do a traversal afterward so the window manager is given our 4909 // most recent data. 4910 mSeq = args.seq; 4911 mAttachInfo.mForceReportNewAttributes = true; 4912 scheduleTraversals(); 4913 } 4914 if (mView == null) return; 4915 if (args.localChanges != 0) { 4916 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 4917 } 4918 if (mAttachInfo != null) { 4919 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 4920 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 4921 mAttachInfo.mGlobalSystemUiVisibility = visibility; 4922 mView.dispatchSystemUiVisibilityChanged(visibility); 4923 } 4924 } 4925 } 4926 4927 public void handleDispatchDoneAnimating() { 4928 if (mWindowsAnimating) { 4929 mWindowsAnimating = false; 4930 if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded) { 4931 scheduleTraversals(); 4932 } 4933 } 4934 } 4935 4936 public void getLastTouchPoint(Point outLocation) { 4937 outLocation.x = (int) mLastTouchPoint.x; 4938 outLocation.y = (int) mLastTouchPoint.y; 4939 } 4940 4941 public void setDragFocus(View newDragTarget) { 4942 if (mCurrentDragView != newDragTarget) { 4943 mCurrentDragView = newDragTarget; 4944 } 4945 } 4946 4947 private AudioManager getAudioManager() { 4948 if (mView == null) { 4949 throw new IllegalStateException("getAudioManager called when there is no mView"); 4950 } 4951 if (mAudioManager == null) { 4952 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 4953 } 4954 return mAudioManager; 4955 } 4956 4957 public AccessibilityInteractionController getAccessibilityInteractionController() { 4958 if (mView == null) { 4959 throw new IllegalStateException("getAccessibilityInteractionController" 4960 + " called when there is no mView"); 4961 } 4962 if (mAccessibilityInteractionController == null) { 4963 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 4964 } 4965 return mAccessibilityInteractionController; 4966 } 4967 4968 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 4969 boolean insetsPending) throws RemoteException { 4970 4971 float appScale = mAttachInfo.mApplicationScale; 4972 boolean restore = false; 4973 if (params != null && mTranslator != null) { 4974 restore = true; 4975 params.backup(); 4976 mTranslator.translateWindowLayout(params); 4977 } 4978 if (params != null) { 4979 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 4980 } 4981 mPendingConfiguration.seq = 0; 4982 //Log.d(TAG, ">>>>>> CALLING relayout"); 4983 if (params != null && mOrigWindowType != params.type) { 4984 // For compatibility with old apps, don't crash here. 4985 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 4986 Slog.w(TAG, "Window type can not be changed after " 4987 + "the window is added; ignoring change of " + mView); 4988 params.type = mOrigWindowType; 4989 } 4990 } 4991 int relayoutResult = mWindowSession.relayout( 4992 mWindow, mSeq, params, 4993 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 4994 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 4995 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 4996 mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets, 4997 mPendingConfiguration, mSurface); 4998 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 4999 if (restore) { 5000 params.restore(); 5001 } 5002 5003 if (mTranslator != null) { 5004 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 5005 mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets); 5006 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 5007 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 5008 } 5009 return relayoutResult; 5010 } 5011 5012 /** 5013 * {@inheritDoc} 5014 */ 5015 public void playSoundEffect(int effectId) { 5016 checkThread(); 5017 5018 if (mMediaDisabled) { 5019 return; 5020 } 5021 5022 try { 5023 final AudioManager audioManager = getAudioManager(); 5024 5025 switch (effectId) { 5026 case SoundEffectConstants.CLICK: 5027 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 5028 return; 5029 case SoundEffectConstants.NAVIGATION_DOWN: 5030 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 5031 return; 5032 case SoundEffectConstants.NAVIGATION_LEFT: 5033 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 5034 return; 5035 case SoundEffectConstants.NAVIGATION_RIGHT: 5036 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 5037 return; 5038 case SoundEffectConstants.NAVIGATION_UP: 5039 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 5040 return; 5041 default: 5042 throw new IllegalArgumentException("unknown effect id " + effectId + 5043 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 5044 } 5045 } catch (IllegalStateException e) { 5046 // Exception thrown by getAudioManager() when mView is null 5047 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 5048 e.printStackTrace(); 5049 } 5050 } 5051 5052 /** 5053 * {@inheritDoc} 5054 */ 5055 public boolean performHapticFeedback(int effectId, boolean always) { 5056 try { 5057 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 5058 } catch (RemoteException e) { 5059 return false; 5060 } 5061 } 5062 5063 /** 5064 * {@inheritDoc} 5065 */ 5066 public View focusSearch(View focused, int direction) { 5067 checkThread(); 5068 if (!(mView instanceof ViewGroup)) { 5069 return null; 5070 } 5071 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 5072 } 5073 5074 public void debug() { 5075 mView.debug(); 5076 } 5077 5078 public void dumpGfxInfo(int[] info) { 5079 info[0] = info[1] = 0; 5080 if (mView != null) { 5081 getGfxInfo(mView, info); 5082 } 5083 } 5084 5085 private static void getGfxInfo(View view, int[] info) { 5086 DisplayList displayList = view.mDisplayList; 5087 info[0]++; 5088 if (displayList != null) { 5089 info[1] += displayList.getSize(); 5090 } 5091 5092 if (view instanceof ViewGroup) { 5093 ViewGroup group = (ViewGroup) view; 5094 5095 int count = group.getChildCount(); 5096 for (int i = 0; i < count; i++) { 5097 getGfxInfo(group.getChildAt(i), info); 5098 } 5099 } 5100 } 5101 5102 public void die(boolean immediate) { 5103 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 5104 // done by dispatchDetachedFromWindow will cause havoc on return. 5105 if (immediate && !mIsInTraversal) { 5106 doDie(); 5107 } else { 5108 if (!mIsDrawing) { 5109 destroyHardwareRenderer(); 5110 } else { 5111 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 5112 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 5113 } 5114 mHandler.sendEmptyMessage(MSG_DIE); 5115 } 5116 } 5117 5118 void doDie() { 5119 checkThread(); 5120 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 5121 synchronized (this) { 5122 if (mAdded) { 5123 dispatchDetachedFromWindow(); 5124 } 5125 5126 if (mAdded && !mFirst) { 5127 invalidateDisplayLists(); 5128 destroyHardwareRenderer(); 5129 5130 if (mView != null) { 5131 int viewVisibility = mView.getVisibility(); 5132 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 5133 if (mWindowAttributesChanged || viewVisibilityChanged) { 5134 // If layout params have been changed, first give them 5135 // to the window manager to make sure it has the correct 5136 // animation info. 5137 try { 5138 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 5139 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 5140 mWindowSession.finishDrawing(mWindow); 5141 } 5142 } catch (RemoteException e) { 5143 } 5144 } 5145 5146 mSurface.release(); 5147 } 5148 } 5149 5150 mAdded = false; 5151 } 5152 WindowManagerGlobal.getInstance().doRemoveView(this); 5153 } 5154 5155 public void requestUpdateConfiguration(Configuration config) { 5156 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 5157 mHandler.sendMessage(msg); 5158 } 5159 5160 public void loadSystemProperties() { 5161 mHandler.post(new Runnable() { 5162 @Override 5163 public void run() { 5164 // Profiling 5165 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false); 5166 profileRendering(mAttachInfo.mHasWindowFocus); 5167 5168 // Media (used by sound effects) 5169 mMediaDisabled = SystemProperties.getBoolean(PROPERTY_MEDIA_DISABLED, false); 5170 5171 // Hardware rendering 5172 if (mAttachInfo.mHardwareRenderer != null) { 5173 if (mAttachInfo.mHardwareRenderer.loadSystemProperties(mHolder.getSurface())) { 5174 invalidate(); 5175 } 5176 } 5177 5178 // Layout debugging 5179 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false); 5180 if (layout != mAttachInfo.mDebugLayout) { 5181 mAttachInfo.mDebugLayout = layout; 5182 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 5183 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 5184 } 5185 } 5186 } 5187 }); 5188 } 5189 5190 private void destroyHardwareRenderer() { 5191 AttachInfo attachInfo = mAttachInfo; 5192 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 5193 5194 if (hardwareRenderer != null) { 5195 if (mView != null) { 5196 hardwareRenderer.destroyHardwareResources(mView); 5197 } 5198 hardwareRenderer.destroy(true); 5199 hardwareRenderer.setRequested(false); 5200 5201 attachInfo.mHardwareRenderer = null; 5202 attachInfo.mHardwareAccelerated = false; 5203 } 5204 } 5205 5206 public void dispatchFinishInputConnection(InputConnection connection) { 5207 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 5208 mHandler.sendMessage(msg); 5209 } 5210 5211 public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets, 5212 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 5213 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 5214 + " contentInsets=" + contentInsets.toShortString() 5215 + " visibleInsets=" + visibleInsets.toShortString() 5216 + " reportDraw=" + reportDraw); 5217 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 5218 if (mTranslator != null) { 5219 mTranslator.translateRectInScreenToAppWindow(frame); 5220 mTranslator.translateRectInScreenToAppWindow(overscanInsets); 5221 mTranslator.translateRectInScreenToAppWindow(contentInsets); 5222 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 5223 } 5224 SomeArgs args = SomeArgs.obtain(); 5225 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 5226 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 5227 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 5228 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 5229 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 5230 args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets; 5231 msg.obj = args; 5232 mHandler.sendMessage(msg); 5233 } 5234 5235 public void dispatchMoved(int newX, int newY) { 5236 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 5237 if (mTranslator != null) { 5238 PointF point = new PointF(newX, newY); 5239 mTranslator.translatePointInScreenToAppWindow(point); 5240 newX = (int) (point.x + 0.5); 5241 newY = (int) (point.y + 0.5); 5242 } 5243 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 5244 mHandler.sendMessage(msg); 5245 } 5246 5247 /** 5248 * Represents a pending input event that is waiting in a queue. 5249 * 5250 * Input events are processed in serial order by the timestamp specified by 5251 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 5252 * one input event to the application at a time and waits for the application 5253 * to finish handling it before delivering the next one. 5254 * 5255 * However, because the application or IME can synthesize and inject multiple 5256 * key events at a time without going through the input dispatcher, we end up 5257 * needing a queue on the application's side. 5258 */ 5259 private static final class QueuedInputEvent { 5260 public static final int FLAG_DELIVER_POST_IME = 1 << 0; 5261 public static final int FLAG_DEFERRED = 1 << 1; 5262 public static final int FLAG_FINISHED = 1 << 2; 5263 public static final int FLAG_FINISHED_HANDLED = 1 << 3; 5264 public static final int FLAG_RESYNTHESIZED = 1 << 4; 5265 5266 public QueuedInputEvent mNext; 5267 5268 public InputEvent mEvent; 5269 public InputEventReceiver mReceiver; 5270 public int mFlags; 5271 5272 public boolean shouldSkipIme() { 5273 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) { 5274 return true; 5275 } 5276 return mEvent instanceof MotionEvent 5277 && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER); 5278 } 5279 } 5280 5281 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 5282 InputEventReceiver receiver, int flags) { 5283 QueuedInputEvent q = mQueuedInputEventPool; 5284 if (q != null) { 5285 mQueuedInputEventPoolSize -= 1; 5286 mQueuedInputEventPool = q.mNext; 5287 q.mNext = null; 5288 } else { 5289 q = new QueuedInputEvent(); 5290 } 5291 5292 q.mEvent = event; 5293 q.mReceiver = receiver; 5294 q.mFlags = flags; 5295 return q; 5296 } 5297 5298 private void recycleQueuedInputEvent(QueuedInputEvent q) { 5299 q.mEvent = null; 5300 q.mReceiver = null; 5301 5302 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 5303 mQueuedInputEventPoolSize += 1; 5304 q.mNext = mQueuedInputEventPool; 5305 mQueuedInputEventPool = q; 5306 } 5307 } 5308 5309 void enqueueInputEvent(InputEvent event) { 5310 enqueueInputEvent(event, null, 0, false); 5311 } 5312 5313 void enqueueInputEvent(InputEvent event, 5314 InputEventReceiver receiver, int flags, boolean processImmediately) { 5315 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 5316 5317 // Always enqueue the input event in order, regardless of its time stamp. 5318 // We do this because the application or the IME may inject key events 5319 // in response to touch events and we want to ensure that the injected keys 5320 // are processed in the order they were received and we cannot trust that 5321 // the time stamp of injected events are monotonic. 5322 QueuedInputEvent last = mPendingInputEventTail; 5323 if (last == null) { 5324 mPendingInputEventHead = q; 5325 mPendingInputEventTail = q; 5326 } else { 5327 last.mNext = q; 5328 mPendingInputEventTail = q; 5329 } 5330 mPendingInputEventCount += 1; 5331 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5332 mPendingInputEventCount); 5333 5334 if (processImmediately) { 5335 doProcessInputEvents(); 5336 } else { 5337 scheduleProcessInputEvents(); 5338 } 5339 } 5340 5341 private void scheduleProcessInputEvents() { 5342 if (!mProcessInputEventsScheduled) { 5343 mProcessInputEventsScheduled = true; 5344 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 5345 msg.setAsynchronous(true); 5346 mHandler.sendMessage(msg); 5347 } 5348 } 5349 5350 void doProcessInputEvents() { 5351 // Deliver all pending input events in the queue. 5352 while (mPendingInputEventHead != null) { 5353 QueuedInputEvent q = mPendingInputEventHead; 5354 mPendingInputEventHead = q.mNext; 5355 if (mPendingInputEventHead == null) { 5356 mPendingInputEventTail = null; 5357 } 5358 q.mNext = null; 5359 5360 mPendingInputEventCount -= 1; 5361 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5362 mPendingInputEventCount); 5363 5364 deliverInputEvent(q); 5365 } 5366 5367 // We are done processing all input events that we can process right now 5368 // so we can clear the pending flag immediately. 5369 if (mProcessInputEventsScheduled) { 5370 mProcessInputEventsScheduled = false; 5371 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 5372 } 5373 } 5374 5375 private void deliverInputEvent(QueuedInputEvent q) { 5376 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent"); 5377 try { 5378 if (mInputEventConsistencyVerifier != null) { 5379 mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0); 5380 } 5381 5382 InputStage stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage; 5383 if (stage != null) { 5384 stage.deliver(q); 5385 } else { 5386 finishInputEvent(q); 5387 } 5388 } finally { 5389 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 5390 } 5391 } 5392 5393 private void finishInputEvent(QueuedInputEvent q) { 5394 if (q.mReceiver != null) { 5395 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0; 5396 q.mReceiver.finishInputEvent(q.mEvent, handled); 5397 } else { 5398 q.mEvent.recycleIfNeededAfterDispatch(); 5399 } 5400 5401 recycleQueuedInputEvent(q); 5402 } 5403 5404 static boolean isTerminalInputEvent(InputEvent event) { 5405 if (event instanceof KeyEvent) { 5406 final KeyEvent keyEvent = (KeyEvent)event; 5407 return keyEvent.getAction() == KeyEvent.ACTION_UP; 5408 } else { 5409 final MotionEvent motionEvent = (MotionEvent)event; 5410 final int action = motionEvent.getAction(); 5411 return action == MotionEvent.ACTION_UP 5412 || action == MotionEvent.ACTION_CANCEL 5413 || action == MotionEvent.ACTION_HOVER_EXIT; 5414 } 5415 } 5416 5417 void scheduleConsumeBatchedInput() { 5418 if (!mConsumeBatchedInputScheduled) { 5419 mConsumeBatchedInputScheduled = true; 5420 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 5421 mConsumedBatchedInputRunnable, null); 5422 } 5423 } 5424 5425 void unscheduleConsumeBatchedInput() { 5426 if (mConsumeBatchedInputScheduled) { 5427 mConsumeBatchedInputScheduled = false; 5428 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 5429 mConsumedBatchedInputRunnable, null); 5430 } 5431 } 5432 5433 void doConsumeBatchedInput(long frameTimeNanos) { 5434 if (mConsumeBatchedInputScheduled) { 5435 mConsumeBatchedInputScheduled = false; 5436 if (mInputEventReceiver != null) { 5437 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos); 5438 } 5439 doProcessInputEvents(); 5440 } 5441 } 5442 5443 final class TraversalRunnable implements Runnable { 5444 @Override 5445 public void run() { 5446 doTraversal(); 5447 } 5448 } 5449 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 5450 5451 final class WindowInputEventReceiver extends InputEventReceiver { 5452 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 5453 super(inputChannel, looper); 5454 } 5455 5456 @Override 5457 public void onInputEvent(InputEvent event) { 5458 enqueueInputEvent(event, this, 0, true); 5459 } 5460 5461 @Override 5462 public void onBatchedInputEventPending() { 5463 scheduleConsumeBatchedInput(); 5464 } 5465 5466 @Override 5467 public void dispose() { 5468 unscheduleConsumeBatchedInput(); 5469 super.dispose(); 5470 } 5471 } 5472 WindowInputEventReceiver mInputEventReceiver; 5473 5474 final class ConsumeBatchedInputRunnable implements Runnable { 5475 @Override 5476 public void run() { 5477 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 5478 } 5479 } 5480 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 5481 new ConsumeBatchedInputRunnable(); 5482 boolean mConsumeBatchedInputScheduled; 5483 5484 final class InvalidateOnAnimationRunnable implements Runnable { 5485 private boolean mPosted; 5486 private ArrayList<View> mViews = new ArrayList<View>(); 5487 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 5488 new ArrayList<AttachInfo.InvalidateInfo>(); 5489 private View[] mTempViews; 5490 private AttachInfo.InvalidateInfo[] mTempViewRects; 5491 5492 public void addView(View view) { 5493 synchronized (this) { 5494 mViews.add(view); 5495 postIfNeededLocked(); 5496 } 5497 } 5498 5499 public void addViewRect(AttachInfo.InvalidateInfo info) { 5500 synchronized (this) { 5501 mViewRects.add(info); 5502 postIfNeededLocked(); 5503 } 5504 } 5505 5506 public void removeView(View view) { 5507 synchronized (this) { 5508 mViews.remove(view); 5509 5510 for (int i = mViewRects.size(); i-- > 0; ) { 5511 AttachInfo.InvalidateInfo info = mViewRects.get(i); 5512 if (info.target == view) { 5513 mViewRects.remove(i); 5514 info.recycle(); 5515 } 5516 } 5517 5518 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 5519 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 5520 mPosted = false; 5521 } 5522 } 5523 } 5524 5525 @Override 5526 public void run() { 5527 final int viewCount; 5528 final int viewRectCount; 5529 synchronized (this) { 5530 mPosted = false; 5531 5532 viewCount = mViews.size(); 5533 if (viewCount != 0) { 5534 mTempViews = mViews.toArray(mTempViews != null 5535 ? mTempViews : new View[viewCount]); 5536 mViews.clear(); 5537 } 5538 5539 viewRectCount = mViewRects.size(); 5540 if (viewRectCount != 0) { 5541 mTempViewRects = mViewRects.toArray(mTempViewRects != null 5542 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 5543 mViewRects.clear(); 5544 } 5545 } 5546 5547 for (int i = 0; i < viewCount; i++) { 5548 mTempViews[i].invalidate(); 5549 mTempViews[i] = null; 5550 } 5551 5552 for (int i = 0; i < viewRectCount; i++) { 5553 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 5554 info.target.invalidate(info.left, info.top, info.right, info.bottom); 5555 info.recycle(); 5556 } 5557 } 5558 5559 private void postIfNeededLocked() { 5560 if (!mPosted) { 5561 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 5562 mPosted = true; 5563 } 5564 } 5565 } 5566 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 5567 new InvalidateOnAnimationRunnable(); 5568 5569 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 5570 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 5571 mHandler.sendMessageDelayed(msg, delayMilliseconds); 5572 } 5573 5574 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 5575 long delayMilliseconds) { 5576 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 5577 mHandler.sendMessageDelayed(msg, delayMilliseconds); 5578 } 5579 5580 public void dispatchInvalidateOnAnimation(View view) { 5581 mInvalidateOnAnimationRunnable.addView(view); 5582 } 5583 5584 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 5585 mInvalidateOnAnimationRunnable.addViewRect(info); 5586 } 5587 5588 public void enqueueDisplayList(DisplayList displayList) { 5589 mDisplayLists.add(displayList); 5590 } 5591 5592 public void cancelInvalidate(View view) { 5593 mHandler.removeMessages(MSG_INVALIDATE, view); 5594 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 5595 // them to the pool 5596 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 5597 mInvalidateOnAnimationRunnable.removeView(view); 5598 } 5599 5600 public void dispatchKey(KeyEvent event) { 5601 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 5602 msg.setAsynchronous(true); 5603 mHandler.sendMessage(msg); 5604 } 5605 5606 public void dispatchKeyFromIme(KeyEvent event) { 5607 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 5608 msg.setAsynchronous(true); 5609 mHandler.sendMessage(msg); 5610 } 5611 5612 public void dispatchUnhandledKey(KeyEvent event) { 5613 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 5614 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 5615 final int keyCode = event.getKeyCode(); 5616 final int metaState = event.getMetaState(); 5617 5618 // Check for fallback actions specified by the key character map. 5619 KeyCharacterMap.FallbackAction fallbackAction = 5620 kcm.getFallbackAction(keyCode, metaState); 5621 if (fallbackAction != null) { 5622 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 5623 KeyEvent fallbackEvent = KeyEvent.obtain( 5624 event.getDownTime(), event.getEventTime(), 5625 event.getAction(), fallbackAction.keyCode, 5626 event.getRepeatCount(), fallbackAction.metaState, 5627 event.getDeviceId(), event.getScanCode(), 5628 flags, event.getSource(), null); 5629 fallbackAction.recycle(); 5630 5631 dispatchKey(fallbackEvent); 5632 } 5633 } 5634 } 5635 5636 public void dispatchAppVisibility(boolean visible) { 5637 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 5638 msg.arg1 = visible ? 1 : 0; 5639 mHandler.sendMessage(msg); 5640 } 5641 5642 public void dispatchScreenStateChange(boolean on) { 5643 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 5644 msg.arg1 = on ? 1 : 0; 5645 mHandler.sendMessage(msg); 5646 } 5647 5648 public void dispatchGetNewSurface() { 5649 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 5650 mHandler.sendMessage(msg); 5651 } 5652 5653 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 5654 Message msg = Message.obtain(); 5655 msg.what = MSG_WINDOW_FOCUS_CHANGED; 5656 msg.arg1 = hasFocus ? 1 : 0; 5657 msg.arg2 = inTouchMode ? 1 : 0; 5658 mHandler.sendMessage(msg); 5659 } 5660 5661 public void dispatchCloseSystemDialogs(String reason) { 5662 Message msg = Message.obtain(); 5663 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 5664 msg.obj = reason; 5665 mHandler.sendMessage(msg); 5666 } 5667 5668 public void dispatchDragEvent(DragEvent event) { 5669 final int what; 5670 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 5671 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 5672 mHandler.removeMessages(what); 5673 } else { 5674 what = MSG_DISPATCH_DRAG_EVENT; 5675 } 5676 Message msg = mHandler.obtainMessage(what, event); 5677 mHandler.sendMessage(msg); 5678 } 5679 5680 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 5681 int localValue, int localChanges) { 5682 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 5683 args.seq = seq; 5684 args.globalVisibility = globalVisibility; 5685 args.localValue = localValue; 5686 args.localChanges = localChanges; 5687 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 5688 } 5689 5690 public void dispatchDoneAnimating() { 5691 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 5692 } 5693 5694 public void dispatchCheckFocus() { 5695 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 5696 // This will result in a call to checkFocus() below. 5697 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 5698 } 5699 } 5700 5701 /** 5702 * Post a callback to send a 5703 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 5704 * This event is send at most once every 5705 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 5706 */ 5707 private void postSendWindowContentChangedCallback(View source) { 5708 if (mSendWindowContentChangedAccessibilityEvent == null) { 5709 mSendWindowContentChangedAccessibilityEvent = 5710 new SendWindowContentChangedAccessibilityEvent(); 5711 } 5712 mSendWindowContentChangedAccessibilityEvent.runOrPost(source); 5713 } 5714 5715 /** 5716 * Remove a posted callback to send a 5717 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 5718 */ 5719 private void removeSendWindowContentChangedCallback() { 5720 if (mSendWindowContentChangedAccessibilityEvent != null) { 5721 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 5722 } 5723 } 5724 5725 public boolean showContextMenuForChild(View originalView) { 5726 return false; 5727 } 5728 5729 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 5730 return null; 5731 } 5732 5733 public void createContextMenu(ContextMenu menu) { 5734 } 5735 5736 public void childDrawableStateChanged(View child) { 5737 } 5738 5739 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 5740 if (mView == null) { 5741 return false; 5742 } 5743 // Intercept accessibility focus events fired by virtual nodes to keep 5744 // track of accessibility focus position in such nodes. 5745 final int eventType = event.getEventType(); 5746 switch (eventType) { 5747 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 5748 final long sourceNodeId = event.getSourceNodeId(); 5749 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5750 sourceNodeId); 5751 View source = mView.findViewByAccessibilityId(accessibilityViewId); 5752 if (source != null) { 5753 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 5754 if (provider != null) { 5755 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo( 5756 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId)); 5757 setAccessibilityFocus(source, node); 5758 } 5759 } 5760 } break; 5761 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 5762 final long sourceNodeId = event.getSourceNodeId(); 5763 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5764 sourceNodeId); 5765 View source = mView.findViewByAccessibilityId(accessibilityViewId); 5766 if (source != null) { 5767 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 5768 if (provider != null) { 5769 setAccessibilityFocus(null, null); 5770 } 5771 } 5772 } break; 5773 } 5774 mAccessibilityManager.sendAccessibilityEvent(event); 5775 return true; 5776 } 5777 5778 @Override 5779 public void childAccessibilityStateChanged(View child) { 5780 postSendWindowContentChangedCallback(child); 5781 } 5782 5783 @Override 5784 public boolean canResolveLayoutDirection() { 5785 return true; 5786 } 5787 5788 @Override 5789 public boolean isLayoutDirectionResolved() { 5790 return true; 5791 } 5792 5793 @Override 5794 public int getLayoutDirection() { 5795 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT; 5796 } 5797 5798 @Override 5799 public boolean canResolveTextDirection() { 5800 return true; 5801 } 5802 5803 @Override 5804 public boolean isTextDirectionResolved() { 5805 return true; 5806 } 5807 5808 @Override 5809 public int getTextDirection() { 5810 return View.TEXT_DIRECTION_RESOLVED_DEFAULT; 5811 } 5812 5813 @Override 5814 public boolean canResolveTextAlignment() { 5815 return true; 5816 } 5817 5818 @Override 5819 public boolean isTextAlignmentResolved() { 5820 return true; 5821 } 5822 5823 @Override 5824 public int getTextAlignment() { 5825 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT; 5826 } 5827 5828 private View getCommonPredecessor(View first, View second) { 5829 if (mAttachInfo != null) { 5830 if (mTempHashSet == null) { 5831 mTempHashSet = new HashSet<View>(); 5832 } 5833 HashSet<View> seen = mTempHashSet; 5834 seen.clear(); 5835 View firstCurrent = first; 5836 while (firstCurrent != null) { 5837 seen.add(firstCurrent); 5838 ViewParent firstCurrentParent = firstCurrent.mParent; 5839 if (firstCurrentParent instanceof View) { 5840 firstCurrent = (View) firstCurrentParent; 5841 } else { 5842 firstCurrent = null; 5843 } 5844 } 5845 View secondCurrent = second; 5846 while (secondCurrent != null) { 5847 if (seen.contains(secondCurrent)) { 5848 seen.clear(); 5849 return secondCurrent; 5850 } 5851 ViewParent secondCurrentParent = secondCurrent.mParent; 5852 if (secondCurrentParent instanceof View) { 5853 secondCurrent = (View) secondCurrentParent; 5854 } else { 5855 secondCurrent = null; 5856 } 5857 } 5858 seen.clear(); 5859 } 5860 return null; 5861 } 5862 5863 void checkThread() { 5864 if (mThread != Thread.currentThread()) { 5865 throw new CalledFromWrongThreadException( 5866 "Only the original thread that created a view hierarchy can touch its views."); 5867 } 5868 } 5869 5870 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 5871 // ViewAncestor never intercepts touch event, so this can be a no-op 5872 } 5873 5874 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 5875 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 5876 if (rectangle != null) { 5877 mTempRect.set(rectangle); 5878 mTempRect.offset(0, -mCurScrollY); 5879 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5880 try { 5881 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate); 5882 } catch (RemoteException re) { 5883 /* ignore */ 5884 } 5885 } 5886 return scrolled; 5887 } 5888 5889 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 5890 // Do nothing. 5891 } 5892 5893 class TakenSurfaceHolder extends BaseSurfaceHolder { 5894 @Override 5895 public boolean onAllowLockCanvas() { 5896 return mDrawingAllowed; 5897 } 5898 5899 @Override 5900 public void onRelayoutContainer() { 5901 // Not currently interesting -- from changing between fixed and layout size. 5902 } 5903 5904 public void setFormat(int format) { 5905 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 5906 } 5907 5908 public void setType(int type) { 5909 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 5910 } 5911 5912 @Override 5913 public void onUpdateSurface() { 5914 // We take care of format and type changes on our own. 5915 throw new IllegalStateException("Shouldn't be here"); 5916 } 5917 5918 public boolean isCreating() { 5919 return mIsCreating; 5920 } 5921 5922 @Override 5923 public void setFixedSize(int width, int height) { 5924 throw new UnsupportedOperationException( 5925 "Currently only support sizing from layout"); 5926 } 5927 5928 public void setKeepScreenOn(boolean screenOn) { 5929 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 5930 } 5931 } 5932 5933 static class W extends IWindow.Stub { 5934 private final WeakReference<ViewRootImpl> mViewAncestor; 5935 private final IWindowSession mWindowSession; 5936 5937 W(ViewRootImpl viewAncestor) { 5938 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 5939 mWindowSession = viewAncestor.mWindowSession; 5940 } 5941 5942 public void resized(Rect frame, Rect overscanInsets, Rect contentInsets, 5943 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 5944 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5945 if (viewAncestor != null) { 5946 viewAncestor.dispatchResized(frame, overscanInsets, contentInsets, 5947 visibleInsets, reportDraw, newConfig); 5948 } 5949 } 5950 5951 @Override 5952 public void moved(int newX, int newY) { 5953 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5954 if (viewAncestor != null) { 5955 viewAncestor.dispatchMoved(newX, newY); 5956 } 5957 } 5958 5959 public void dispatchAppVisibility(boolean visible) { 5960 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5961 if (viewAncestor != null) { 5962 viewAncestor.dispatchAppVisibility(visible); 5963 } 5964 } 5965 5966 public void dispatchScreenState(boolean on) { 5967 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5968 if (viewAncestor != null) { 5969 viewAncestor.dispatchScreenStateChange(on); 5970 } 5971 } 5972 5973 public void dispatchGetNewSurface() { 5974 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5975 if (viewAncestor != null) { 5976 viewAncestor.dispatchGetNewSurface(); 5977 } 5978 } 5979 5980 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 5981 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5982 if (viewAncestor != null) { 5983 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 5984 } 5985 } 5986 5987 private static int checkCallingPermission(String permission) { 5988 try { 5989 return ActivityManagerNative.getDefault().checkPermission( 5990 permission, Binder.getCallingPid(), Binder.getCallingUid()); 5991 } catch (RemoteException e) { 5992 return PackageManager.PERMISSION_DENIED; 5993 } 5994 } 5995 5996 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 5997 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5998 if (viewAncestor != null) { 5999 final View view = viewAncestor.mView; 6000 if (view != null) { 6001 if (checkCallingPermission(Manifest.permission.DUMP) != 6002 PackageManager.PERMISSION_GRANTED) { 6003 throw new SecurityException("Insufficient permissions to invoke" 6004 + " executeCommand() from pid=" + Binder.getCallingPid() 6005 + ", uid=" + Binder.getCallingUid()); 6006 } 6007 6008 OutputStream clientStream = null; 6009 try { 6010 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 6011 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 6012 } catch (IOException e) { 6013 e.printStackTrace(); 6014 } finally { 6015 if (clientStream != null) { 6016 try { 6017 clientStream.close(); 6018 } catch (IOException e) { 6019 e.printStackTrace(); 6020 } 6021 } 6022 } 6023 } 6024 } 6025 } 6026 6027 public void closeSystemDialogs(String reason) { 6028 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6029 if (viewAncestor != null) { 6030 viewAncestor.dispatchCloseSystemDialogs(reason); 6031 } 6032 } 6033 6034 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 6035 boolean sync) { 6036 if (sync) { 6037 try { 6038 mWindowSession.wallpaperOffsetsComplete(asBinder()); 6039 } catch (RemoteException e) { 6040 } 6041 } 6042 } 6043 6044 public void dispatchWallpaperCommand(String action, int x, int y, 6045 int z, Bundle extras, boolean sync) { 6046 if (sync) { 6047 try { 6048 mWindowSession.wallpaperCommandComplete(asBinder(), null); 6049 } catch (RemoteException e) { 6050 } 6051 } 6052 } 6053 6054 /* Drag/drop */ 6055 public void dispatchDragEvent(DragEvent event) { 6056 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6057 if (viewAncestor != null) { 6058 viewAncestor.dispatchDragEvent(event); 6059 } 6060 } 6061 6062 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 6063 int localValue, int localChanges) { 6064 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6065 if (viewAncestor != null) { 6066 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 6067 localValue, localChanges); 6068 } 6069 } 6070 6071 public void doneAnimating() { 6072 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6073 if (viewAncestor != null) { 6074 viewAncestor.dispatchDoneAnimating(); 6075 } 6076 } 6077 } 6078 6079 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 6080 public CalledFromWrongThreadException(String msg) { 6081 super(msg); 6082 } 6083 } 6084 6085 private SurfaceHolder mHolder = new SurfaceHolder() { 6086 // we only need a SurfaceHolder for opengl. it would be nice 6087 // to implement everything else though, especially the callback 6088 // support (opengl doesn't make use of it right now, but eventually 6089 // will). 6090 public Surface getSurface() { 6091 return mSurface; 6092 } 6093 6094 public boolean isCreating() { 6095 return false; 6096 } 6097 6098 public void addCallback(Callback callback) { 6099 } 6100 6101 public void removeCallback(Callback callback) { 6102 } 6103 6104 public void setFixedSize(int width, int height) { 6105 } 6106 6107 public void setSizeFromLayout() { 6108 } 6109 6110 public void setFormat(int format) { 6111 } 6112 6113 public void setType(int type) { 6114 } 6115 6116 public void setKeepScreenOn(boolean screenOn) { 6117 } 6118 6119 public Canvas lockCanvas() { 6120 return null; 6121 } 6122 6123 public Canvas lockCanvas(Rect dirty) { 6124 return null; 6125 } 6126 6127 public void unlockCanvasAndPost(Canvas canvas) { 6128 } 6129 public Rect getSurfaceFrame() { 6130 return null; 6131 } 6132 }; 6133 6134 static RunQueue getRunQueue() { 6135 RunQueue rq = sRunQueues.get(); 6136 if (rq != null) { 6137 return rq; 6138 } 6139 rq = new RunQueue(); 6140 sRunQueues.set(rq); 6141 return rq; 6142 } 6143 6144 /** 6145 * The run queue is used to enqueue pending work from Views when no Handler is 6146 * attached. The work is executed during the next call to performTraversals on 6147 * the thread. 6148 * @hide 6149 */ 6150 static final class RunQueue { 6151 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 6152 6153 void post(Runnable action) { 6154 postDelayed(action, 0); 6155 } 6156 6157 void postDelayed(Runnable action, long delayMillis) { 6158 HandlerAction handlerAction = new HandlerAction(); 6159 handlerAction.action = action; 6160 handlerAction.delay = delayMillis; 6161 6162 synchronized (mActions) { 6163 mActions.add(handlerAction); 6164 } 6165 } 6166 6167 void removeCallbacks(Runnable action) { 6168 final HandlerAction handlerAction = new HandlerAction(); 6169 handlerAction.action = action; 6170 6171 synchronized (mActions) { 6172 final ArrayList<HandlerAction> actions = mActions; 6173 6174 while (actions.remove(handlerAction)) { 6175 // Keep going 6176 } 6177 } 6178 } 6179 6180 void executeActions(Handler handler) { 6181 synchronized (mActions) { 6182 final ArrayList<HandlerAction> actions = mActions; 6183 final int count = actions.size(); 6184 6185 for (int i = 0; i < count; i++) { 6186 final HandlerAction handlerAction = actions.get(i); 6187 handler.postDelayed(handlerAction.action, handlerAction.delay); 6188 } 6189 6190 actions.clear(); 6191 } 6192 } 6193 6194 private static class HandlerAction { 6195 Runnable action; 6196 long delay; 6197 6198 @Override 6199 public boolean equals(Object o) { 6200 if (this == o) return true; 6201 if (o == null || getClass() != o.getClass()) return false; 6202 6203 HandlerAction that = (HandlerAction) o; 6204 return !(action != null ? !action.equals(that.action) : that.action != null); 6205 6206 } 6207 6208 @Override 6209 public int hashCode() { 6210 int result = action != null ? action.hashCode() : 0; 6211 result = 31 * result + (int) (delay ^ (delay >>> 32)); 6212 return result; 6213 } 6214 } 6215 } 6216 6217 /** 6218 * Class for managing the accessibility interaction connection 6219 * based on the global accessibility state. 6220 */ 6221 final class AccessibilityInteractionConnectionManager 6222 implements AccessibilityStateChangeListener { 6223 public void onAccessibilityStateChanged(boolean enabled) { 6224 if (enabled) { 6225 ensureConnection(); 6226 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 6227 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 6228 View focusedView = mView.findFocus(); 6229 if (focusedView != null && focusedView != mView) { 6230 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6231 } 6232 } 6233 } else { 6234 ensureNoConnection(); 6235 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 6236 } 6237 } 6238 6239 public void ensureConnection() { 6240 if (mAttachInfo != null) { 6241 final boolean registered = 6242 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 6243 if (!registered) { 6244 mAttachInfo.mAccessibilityWindowId = 6245 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 6246 new AccessibilityInteractionConnection(ViewRootImpl.this)); 6247 } 6248 } 6249 } 6250 6251 public void ensureNoConnection() { 6252 final boolean registered = 6253 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 6254 if (registered) { 6255 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 6256 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 6257 } 6258 } 6259 } 6260 6261 /** 6262 * This class is an interface this ViewAncestor provides to the 6263 * AccessibilityManagerService to the latter can interact with 6264 * the view hierarchy in this ViewAncestor. 6265 */ 6266 static final class AccessibilityInteractionConnection 6267 extends IAccessibilityInteractionConnection.Stub { 6268 private final WeakReference<ViewRootImpl> mViewRootImpl; 6269 6270 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 6271 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 6272 } 6273 6274 @Override 6275 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 6276 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6277 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6278 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6279 if (viewRootImpl != null && viewRootImpl.mView != null) { 6280 viewRootImpl.getAccessibilityInteractionController() 6281 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 6282 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6283 spec); 6284 } else { 6285 // We cannot make the call and notify the caller so it does not wait. 6286 try { 6287 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6288 } catch (RemoteException re) { 6289 /* best effort - ignore */ 6290 } 6291 } 6292 } 6293 6294 @Override 6295 public void performAccessibilityAction(long accessibilityNodeId, int action, 6296 Bundle arguments, int interactionId, 6297 IAccessibilityInteractionConnectionCallback callback, int flags, 6298 int interogatingPid, long interrogatingTid) { 6299 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6300 if (viewRootImpl != null && viewRootImpl.mView != null) { 6301 viewRootImpl.getAccessibilityInteractionController() 6302 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 6303 interactionId, callback, flags, interogatingPid, interrogatingTid); 6304 } else { 6305 // We cannot make the call and notify the caller so it does not wait. 6306 try { 6307 callback.setPerformAccessibilityActionResult(false, interactionId); 6308 } catch (RemoteException re) { 6309 /* best effort - ignore */ 6310 } 6311 } 6312 } 6313 6314 @Override 6315 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId, 6316 String viewId, int interactionId, 6317 IAccessibilityInteractionConnectionCallback callback, int flags, 6318 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6319 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6320 if (viewRootImpl != null && viewRootImpl.mView != null) { 6321 viewRootImpl.getAccessibilityInteractionController() 6322 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId, 6323 viewId, interactionId, callback, flags, interrogatingPid, 6324 interrogatingTid, spec); 6325 } else { 6326 // We cannot make the call and notify the caller so it does not wait. 6327 try { 6328 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6329 } catch (RemoteException re) { 6330 /* best effort - ignore */ 6331 } 6332 } 6333 } 6334 6335 @Override 6336 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 6337 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6338 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6339 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6340 if (viewRootImpl != null && viewRootImpl.mView != null) { 6341 viewRootImpl.getAccessibilityInteractionController() 6342 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 6343 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6344 spec); 6345 } else { 6346 // We cannot make the call and notify the caller so it does not wait. 6347 try { 6348 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6349 } catch (RemoteException re) { 6350 /* best effort - ignore */ 6351 } 6352 } 6353 } 6354 6355 @Override 6356 public void findFocus(long accessibilityNodeId, int focusType, int interactionId, 6357 IAccessibilityInteractionConnectionCallback callback, int flags, 6358 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6359 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6360 if (viewRootImpl != null && viewRootImpl.mView != null) { 6361 viewRootImpl.getAccessibilityInteractionController() 6362 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback, 6363 flags, interrogatingPid, interrogatingTid, spec); 6364 } else { 6365 // We cannot make the call and notify the caller so it does not wait. 6366 try { 6367 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6368 } catch (RemoteException re) { 6369 /* best effort - ignore */ 6370 } 6371 } 6372 } 6373 6374 @Override 6375 public void focusSearch(long accessibilityNodeId, int direction, int interactionId, 6376 IAccessibilityInteractionConnectionCallback callback, int flags, 6377 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6378 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6379 if (viewRootImpl != null && viewRootImpl.mView != null) { 6380 viewRootImpl.getAccessibilityInteractionController() 6381 .focusSearchClientThread(accessibilityNodeId, direction, interactionId, 6382 callback, flags, interrogatingPid, interrogatingTid, spec); 6383 } else { 6384 // We cannot make the call and notify the caller so it does not wait. 6385 try { 6386 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6387 } catch (RemoteException re) { 6388 /* best effort - ignore */ 6389 } 6390 } 6391 } 6392 } 6393 6394 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 6395 public View mSource; 6396 public long mLastEventTimeMillis; 6397 6398 public void run() { 6399 mLastEventTimeMillis = SystemClock.uptimeMillis(); 6400 AccessibilityEvent event = AccessibilityEvent.obtain(); 6401 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 6402 event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 6403 mSource.sendAccessibilityEventUnchecked(event); 6404 mSource.resetSubtreeAccessibilityStateChanged(); 6405 mSource = null; 6406 } 6407 6408 public void runOrPost(View source) { 6409 if (mSource != null) { 6410 mSource = getCommonPredecessor(mSource, source); 6411 return; 6412 } 6413 mSource = source; 6414 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 6415 final long minEventIntevalMillis = 6416 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 6417 if (timeSinceLastMillis >= minEventIntevalMillis) { 6418 mSource.removeCallbacks(this); 6419 run(); 6420 } else { 6421 mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 6422 } 6423 } 6424 } 6425} 6426