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