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