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