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