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