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