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