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