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