ViewRootImpl.java revision 54e3d38490b60cd776ad3b988d923241498816e2
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 positioned 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 mFullRedrawNeeded = true; 1749 // reconfigure window manager 1750 try { 1751 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion); 1752 } catch (RemoteException e) { 1753 } 1754 } 1755 } 1756 1757 if (DBG) { 1758 System.out.println("======================================"); 1759 System.out.println("performTraversals -- after setFrame"); 1760 host.debug(); 1761 } 1762 } 1763 1764 if (triggerGlobalLayoutListener) { 1765 attachInfo.mRecomputeGlobalAttributes = false; 1766 attachInfo.mTreeObserver.dispatchOnGlobalLayout(); 1767 1768 if (AccessibilityManager.getInstance(host.mContext).isEnabled()) { 1769 postSendWindowContentChangedCallback(mView); 1770 } 1771 } 1772 1773 if (computesInternalInsets) { 1774 // Clear the original insets. 1775 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets; 1776 insets.reset(); 1777 1778 // Compute new insets in place. 1779 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets); 1780 1781 // Tell the window manager. 1782 if (insetsPending || !mLastGivenInsets.equals(insets)) { 1783 mLastGivenInsets.set(insets); 1784 1785 // Translate insets to screen coordinates if needed. 1786 final Rect contentInsets; 1787 final Rect visibleInsets; 1788 final Region touchableRegion; 1789 if (mTranslator != null) { 1790 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets); 1791 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets); 1792 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion); 1793 } else { 1794 contentInsets = insets.contentInsets; 1795 visibleInsets = insets.visibleInsets; 1796 touchableRegion = insets.touchableRegion; 1797 } 1798 1799 try { 1800 mWindowSession.setInsets(mWindow, insets.mTouchableInsets, 1801 contentInsets, visibleInsets, touchableRegion); 1802 } catch (RemoteException e) { 1803 } 1804 } 1805 } 1806 1807 boolean skipDraw = false; 1808 1809 if (mFirst) { 1810 // handle first focus request 1811 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()=" 1812 + mView.hasFocus()); 1813 if (mView != null) { 1814 if (!mView.hasFocus()) { 1815 mView.requestFocus(View.FOCUS_FORWARD); 1816 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view=" 1817 + mView.findFocus()); 1818 } else { 1819 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view=" 1820 + mView.findFocus()); 1821 } 1822 } 1823 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) { 1824 // The first time we relayout the window, if the system is 1825 // doing window animations, we want to hold of on any future 1826 // draws until the animation is done. 1827 mWindowsAnimating = true; 1828 } 1829 } else if (mWindowsAnimating) { 1830 skipDraw = true; 1831 } 1832 1833 mFirst = false; 1834 mWillDrawSoon = false; 1835 mNewSurfaceNeeded = false; 1836 mViewVisibility = viewVisibility; 1837 1838 if (mAttachInfo.mHasWindowFocus) { 1839 final boolean imTarget = WindowManager.LayoutParams 1840 .mayUseInputMethod(mWindowAttributes.flags); 1841 if (imTarget != mLastWasImTarget) { 1842 mLastWasImTarget = imTarget; 1843 InputMethodManager imm = InputMethodManager.peekInstance(); 1844 if (imm != null && imTarget) { 1845 imm.startGettingWindowFocus(mView); 1846 imm.onWindowFocus(mView, mView.findFocus(), 1847 mWindowAttributes.softInputMode, 1848 !mHasHadWindowFocus, mWindowAttributes.flags); 1849 } 1850 } 1851 } 1852 1853 // Remember if we must report the next draw. 1854 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 1855 mReportNextDraw = true; 1856 } 1857 1858 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() || 1859 viewVisibility != View.VISIBLE; 1860 1861 if (!cancelDraw && !newSurface) { 1862 if (!skipDraw || mReportNextDraw) { 1863 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1864 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1865 mPendingTransitions.get(i).startChangingAnimations(); 1866 } 1867 mPendingTransitions.clear(); 1868 } 1869 1870 performDraw(); 1871 } 1872 } else { 1873 if (viewVisibility == View.VISIBLE) { 1874 // Try again 1875 scheduleTraversals(); 1876 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1877 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1878 mPendingTransitions.get(i).endChangingAnimations(); 1879 } 1880 mPendingTransitions.clear(); 1881 } 1882 } 1883 1884 mIsInTraversal = false; 1885 } 1886 1887 private void handleOutOfResourcesException(Surface.OutOfResourcesException e) { 1888 Log.e(TAG, "OutOfResourcesException initializing HW surface", e); 1889 try { 1890 if (!mWindowSession.outOfMemory(mWindow) && 1891 Process.myUid() != Process.SYSTEM_UID) { 1892 Slog.w(TAG, "No processes killed for memory; killing self"); 1893 Process.killProcess(Process.myPid()); 1894 } 1895 } catch (RemoteException ex) { 1896 } 1897 mLayoutRequested = true; // ask wm for a new surface next time. 1898 } 1899 1900 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) { 1901 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure"); 1902 try { 1903 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1904 } finally { 1905 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 1906 } 1907 } 1908 1909 /** 1910 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy 1911 * is currently undergoing a layout pass. 1912 * 1913 * @return whether the view hierarchy is currently undergoing a layout pass 1914 */ 1915 boolean isInLayout() { 1916 return mInLayout; 1917 } 1918 1919 /** 1920 * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently 1921 * undergoing a layout pass. requestLayout() should not generally be called during layout, 1922 * unless the container hierarchy knows what it is doing (i.e., it is fine as long as 1923 * all children in that container hierarchy are measured and laid out at the end of the layout 1924 * pass for that container). If requestLayout() is called anyway, we handle it correctly 1925 * by registering all requesters during a frame as it proceeds. At the end of the frame, 1926 * we check all of those views to see if any still have pending layout requests, which 1927 * indicates that they were not correctly handled by their container hierarchy. If that is 1928 * the case, we clear all such flags in the tree, to remove the buggy flag state that leads 1929 * to blank containers, and force a second request/measure/layout pass in this frame. If 1930 * more requestLayout() calls are received during that second layout pass, we post those 1931 * requests to the next frame to avoid possible infinite loops. 1932 * 1933 * <p>The return value from this method indicates whether the request should proceed 1934 * (if it is a request during the first layout pass) or should be skipped and posted to the 1935 * next frame (if it is a request during the second layout pass).</p> 1936 * 1937 * @param view the view that requested the layout. 1938 * 1939 * @return true if request should proceed, false otherwise. 1940 */ 1941 boolean requestLayoutDuringLayout(final View view) { 1942 if (view.mParent == null || view.mAttachInfo == null) { 1943 // Would not normally trigger another layout, so just let it pass through as usual 1944 return true; 1945 } 1946 if (!mLayoutRequesters.contains(view)) { 1947 mLayoutRequesters.add(view); 1948 } 1949 if (!mHandlingLayoutInLayoutRequest) { 1950 // Let the request proceed normally; it will be processed in a second layout pass 1951 // if necessary 1952 return true; 1953 } else { 1954 // Don't let the request proceed during the second layout pass. 1955 // It will post to the next frame instead. 1956 return false; 1957 } 1958 } 1959 1960 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth, 1961 int desiredWindowHeight) { 1962 mLayoutRequested = false; 1963 mScrollMayChange = true; 1964 mInLayout = true; 1965 1966 final View host = mView; 1967 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) { 1968 Log.v(TAG, "Laying out " + host + " to (" + 1969 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")"); 1970 } 1971 1972 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout"); 1973 try { 1974 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 1975 1976 mInLayout = false; 1977 int numViewsRequestingLayout = mLayoutRequesters.size(); 1978 if (numViewsRequestingLayout > 0) { 1979 // requestLayout() was called during layout. 1980 // If no layout-request flags are set on the requesting views, there is no problem. 1981 // If some requests are still pending, then we need to clear those flags and do 1982 // a full request/measure/layout pass to handle this situation. 1983 ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, 1984 false); 1985 if (validLayoutRequesters != null) { 1986 // Set this flag to indicate that any further requests are happening during 1987 // the second pass, which may result in posting those requests to the next 1988 // frame instead 1989 mHandlingLayoutInLayoutRequest = true; 1990 1991 // Process fresh layout requests, then measure and layout 1992 int numValidRequests = validLayoutRequesters.size(); 1993 for (int i = 0; i < numValidRequests; ++i) { 1994 final View view = validLayoutRequesters.get(i); 1995 Log.w("View", "requestLayout() improperly called by " + view + 1996 " during layout: running second layout pass"); 1997 view.requestLayout(); 1998 } 1999 measureHierarchy(host, lp, mView.getContext().getResources(), 2000 desiredWindowWidth, desiredWindowHeight); 2001 mInLayout = true; 2002 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 2003 2004 mHandlingLayoutInLayoutRequest = false; 2005 2006 // Check the valid requests again, this time without checking/clearing the 2007 // layout flags, since requests happening during the second pass get noop'd 2008 validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true); 2009 if (validLayoutRequesters != null) { 2010 final ArrayList<View> finalRequesters = validLayoutRequesters; 2011 // Post second-pass requests to the next frame 2012 getRunQueue().post(new Runnable() { 2013 @Override 2014 public void run() { 2015 int numValidRequests = finalRequesters.size(); 2016 for (int i = 0; i < numValidRequests; ++i) { 2017 final View view = finalRequesters.get(i); 2018 Log.w("View", "requestLayout() improperly called by " + view + 2019 " during second layout pass: posting in next frame"); 2020 view.requestLayout(); 2021 } 2022 } 2023 }); 2024 } 2025 } 2026 2027 } 2028 } finally { 2029 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2030 } 2031 mInLayout = false; 2032 } 2033 2034 /** 2035 * This method is called during layout when there have been calls to requestLayout() during 2036 * layout. It walks through the list of views that requested layout to determine which ones 2037 * still need it, based on visibility in the hierarchy and whether they have already been 2038 * handled (as is usually the case with ListView children). 2039 * 2040 * @param layoutRequesters The list of views that requested layout during layout 2041 * @param secondLayoutRequests Whether the requests were issued during the second layout pass. 2042 * If so, the FORCE_LAYOUT flag was not set on requesters. 2043 * @return A list of the actual views that still need to be laid out. 2044 */ 2045 private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters, 2046 boolean secondLayoutRequests) { 2047 2048 int numViewsRequestingLayout = layoutRequesters.size(); 2049 ArrayList<View> validLayoutRequesters = null; 2050 for (int i = 0; i < numViewsRequestingLayout; ++i) { 2051 View view = layoutRequesters.get(i); 2052 if (view != null && view.mAttachInfo != null && view.mParent != null && 2053 (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == 2054 View.PFLAG_FORCE_LAYOUT)) { 2055 boolean gone = false; 2056 View parent = view; 2057 // Only trigger new requests for views in a non-GONE hierarchy 2058 while (parent != null) { 2059 if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) { 2060 gone = true; 2061 break; 2062 } 2063 if (parent.mParent instanceof View) { 2064 parent = (View) parent.mParent; 2065 } else { 2066 parent = null; 2067 } 2068 } 2069 if (!gone) { 2070 if (validLayoutRequesters == null) { 2071 validLayoutRequesters = new ArrayList<View>(); 2072 } 2073 validLayoutRequesters.add(view); 2074 } 2075 } 2076 } 2077 if (!secondLayoutRequests) { 2078 // If we're checking the layout flags, then we need to clean them up also 2079 for (int i = 0; i < numViewsRequestingLayout; ++i) { 2080 View view = layoutRequesters.get(i); 2081 while (view != null && 2082 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) { 2083 view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT; 2084 if (view.mParent instanceof View) { 2085 view = (View) view.mParent; 2086 } else { 2087 view = null; 2088 } 2089 } 2090 } 2091 } 2092 layoutRequesters.clear(); 2093 return validLayoutRequesters; 2094 } 2095 2096 public void requestTransparentRegion(View child) { 2097 // the test below should not fail unless someone is messing with us 2098 checkThread(); 2099 if (mView == child) { 2100 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS; 2101 // Need to make sure we re-evaluate the window attributes next 2102 // time around, to ensure the window has the correct format. 2103 mWindowAttributesChanged = true; 2104 mWindowAttributesChangesFlag = 0; 2105 requestLayout(); 2106 } 2107 } 2108 2109 /** 2110 * Figures out the measure spec for the root view in a window based on it's 2111 * layout params. 2112 * 2113 * @param windowSize 2114 * The available width or height of the window 2115 * 2116 * @param rootDimension 2117 * The layout params for one dimension (width or height) of the 2118 * window. 2119 * 2120 * @return The measure spec to use to measure the root view. 2121 */ 2122 private static int getRootMeasureSpec(int windowSize, int rootDimension) { 2123 int measureSpec; 2124 switch (rootDimension) { 2125 2126 case ViewGroup.LayoutParams.MATCH_PARENT: 2127 // Window can't resize. Force root view to be windowSize. 2128 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); 2129 break; 2130 case ViewGroup.LayoutParams.WRAP_CONTENT: 2131 // Window can resize. Set max size for root view. 2132 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST); 2133 break; 2134 default: 2135 // Window wants to be an exact size. Force root view to be that size. 2136 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY); 2137 break; 2138 } 2139 return measureSpec; 2140 } 2141 2142 int mHardwareYOffset; 2143 int mResizeAlpha; 2144 final Paint mResizePaint = new Paint(); 2145 2146 public void onHardwarePreDraw(HardwareCanvas canvas) { 2147 canvas.translate(0, -mHardwareYOffset); 2148 } 2149 2150 public void onHardwarePostDraw(HardwareCanvas canvas) { 2151 if (mResizeBuffer != null) { 2152 mResizePaint.setAlpha(mResizeAlpha); 2153 canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint); 2154 } 2155 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2156 } 2157 2158 /** 2159 * @hide 2160 */ 2161 void outputDisplayList(View view) { 2162 if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) { 2163 DisplayList displayList = view.getDisplayList(); 2164 if (displayList != null) { 2165 mAttachInfo.mHardwareCanvas.outputDisplayList(displayList); 2166 } 2167 } 2168 } 2169 2170 /** 2171 * @see #PROPERTY_PROFILE_RENDERING 2172 */ 2173 private void profileRendering(boolean enabled) { 2174 if (mProfileRendering) { 2175 mRenderProfilingEnabled = enabled; 2176 2177 if (mRenderProfiler != null) { 2178 mChoreographer.removeFrameCallback(mRenderProfiler); 2179 } 2180 if (mRenderProfilingEnabled) { 2181 if (mRenderProfiler == null) { 2182 mRenderProfiler = new Choreographer.FrameCallback() { 2183 @Override 2184 public void doFrame(long frameTimeNanos) { 2185 mDirty.set(0, 0, mWidth, mHeight); 2186 scheduleTraversals(); 2187 if (mRenderProfilingEnabled) { 2188 mChoreographer.postFrameCallback(mRenderProfiler); 2189 } 2190 } 2191 }; 2192 } 2193 mChoreographer.postFrameCallback(mRenderProfiler); 2194 } else { 2195 mRenderProfiler = null; 2196 } 2197 } 2198 } 2199 2200 /** 2201 * Called from draw() when DEBUG_FPS is enabled 2202 */ 2203 private void trackFPS() { 2204 // Tracks frames per second drawn. First value in a series of draws may be bogus 2205 // because it down not account for the intervening idle time 2206 long nowTime = System.currentTimeMillis(); 2207 if (mFpsStartTime < 0) { 2208 mFpsStartTime = mFpsPrevTime = nowTime; 2209 mFpsNumFrames = 0; 2210 } else { 2211 ++mFpsNumFrames; 2212 String thisHash = Integer.toHexString(System.identityHashCode(this)); 2213 long frameTime = nowTime - mFpsPrevTime; 2214 long totalTime = nowTime - mFpsStartTime; 2215 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime); 2216 mFpsPrevTime = nowTime; 2217 if (totalTime > 1000) { 2218 float fps = (float) mFpsNumFrames * 1000 / totalTime; 2219 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps); 2220 mFpsStartTime = nowTime; 2221 mFpsNumFrames = 0; 2222 } 2223 } 2224 } 2225 2226 private void performDraw() { 2227 if (!mAttachInfo.mScreenOn && !mReportNextDraw) { 2228 return; 2229 } 2230 2231 final boolean fullRedrawNeeded = mFullRedrawNeeded; 2232 mFullRedrawNeeded = false; 2233 2234 mIsDrawing = true; 2235 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw"); 2236 try { 2237 draw(fullRedrawNeeded); 2238 } finally { 2239 mIsDrawing = false; 2240 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2241 } 2242 2243 if (mReportNextDraw) { 2244 mReportNextDraw = false; 2245 2246 if (LOCAL_LOGV) { 2247 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle()); 2248 } 2249 if (mSurfaceHolder != null && mSurface.isValid()) { 2250 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder); 2251 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 2252 if (callbacks != null) { 2253 for (SurfaceHolder.Callback c : callbacks) { 2254 if (c instanceof SurfaceHolder.Callback2) { 2255 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 2256 mSurfaceHolder); 2257 } 2258 } 2259 } 2260 } 2261 try { 2262 mWindowSession.finishDrawing(mWindow); 2263 } catch (RemoteException e) { 2264 } 2265 } 2266 } 2267 2268 private void draw(boolean fullRedrawNeeded) { 2269 Surface surface = mSurface; 2270 if (!surface.isValid()) { 2271 return; 2272 } 2273 2274 if (DEBUG_FPS) { 2275 trackFPS(); 2276 } 2277 2278 if (!sFirstDrawComplete) { 2279 synchronized (sFirstDrawHandlers) { 2280 sFirstDrawComplete = true; 2281 final int count = sFirstDrawHandlers.size(); 2282 for (int i = 0; i< count; i++) { 2283 mHandler.post(sFirstDrawHandlers.get(i)); 2284 } 2285 } 2286 } 2287 2288 scrollToRectOrFocus(null, false); 2289 2290 final AttachInfo attachInfo = mAttachInfo; 2291 if (attachInfo.mViewScrollChanged) { 2292 attachInfo.mViewScrollChanged = false; 2293 attachInfo.mTreeObserver.dispatchOnScrollChanged(); 2294 } 2295 2296 int yoff; 2297 boolean animating = mScroller != null && mScroller.computeScrollOffset(); 2298 if (animating) { 2299 yoff = mScroller.getCurrY(); 2300 } else { 2301 yoff = mScrollY; 2302 } 2303 if (mCurScrollY != yoff) { 2304 mCurScrollY = yoff; 2305 fullRedrawNeeded = true; 2306 } 2307 2308 final float appScale = attachInfo.mApplicationScale; 2309 final boolean scalingRequired = attachInfo.mScalingRequired; 2310 2311 int resizeAlpha = 0; 2312 if (mResizeBuffer != null) { 2313 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime; 2314 if (deltaTime < mResizeBufferDuration) { 2315 float amt = deltaTime/(float) mResizeBufferDuration; 2316 amt = mResizeInterpolator.getInterpolation(amt); 2317 animating = true; 2318 resizeAlpha = 255 - (int)(amt*255); 2319 } else { 2320 disposeResizeBuffer(); 2321 } 2322 } 2323 2324 final Rect dirty = mDirty; 2325 if (mSurfaceHolder != null) { 2326 // The app owns the surface, we won't draw. 2327 dirty.setEmpty(); 2328 if (animating) { 2329 if (mScroller != null) { 2330 mScroller.abortAnimation(); 2331 } 2332 disposeResizeBuffer(); 2333 } 2334 return; 2335 } 2336 2337 if (fullRedrawNeeded) { 2338 attachInfo.mIgnoreDirtyState = true; 2339 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 2340 } 2341 2342 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2343 Log.v(TAG, "Draw " + mView + "/" 2344 + mWindowAttributes.getTitle() 2345 + ": dirty={" + dirty.left + "," + dirty.top 2346 + "," + dirty.right + "," + dirty.bottom + "} surface=" 2347 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" + 2348 appScale + ", width=" + mWidth + ", height=" + mHeight); 2349 } 2350 2351 invalidateDisplayLists(); 2352 2353 attachInfo.mTreeObserver.dispatchOnDraw(); 2354 2355 if (!dirty.isEmpty() || mIsAnimating) { 2356 if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) { 2357 // Draw with hardware renderer. 2358 mIsAnimating = false; 2359 mHardwareYOffset = yoff; 2360 mResizeAlpha = resizeAlpha; 2361 2362 mCurrentDirty.set(dirty); 2363 dirty.setEmpty(); 2364 2365 attachInfo.mHardwareRenderer.draw(mView, attachInfo, this, 2366 animating ? null : mCurrentDirty); 2367 } else { 2368 // If we get here with a disabled & requested hardware renderer, something went 2369 // wrong (an invalidate posted right before we destroyed the hardware surface 2370 // for instance) so we should just bail out. Locking the surface with software 2371 // rendering at this point would lock it forever and prevent hardware renderer 2372 // from doing its job when it comes back. 2373 // Before we request a new frame we must however attempt to reinitiliaze the 2374 // hardware renderer if it's in requested state. This would happen after an 2375 // eglTerminate() for instance. 2376 if (attachInfo.mHardwareRenderer != null && 2377 !attachInfo.mHardwareRenderer.isEnabled() && 2378 attachInfo.mHardwareRenderer.isRequested()) { 2379 2380 try { 2381 attachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2382 mHolder.getSurface()); 2383 } catch (Surface.OutOfResourcesException e) { 2384 handleOutOfResourcesException(e); 2385 return; 2386 } 2387 2388 mFullRedrawNeeded = true; 2389 scheduleTraversals(); 2390 return; 2391 } 2392 2393 if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) { 2394 return; 2395 } 2396 } 2397 } 2398 2399 if (animating) { 2400 mFullRedrawNeeded = true; 2401 scheduleTraversals(); 2402 } 2403 } 2404 2405 /** 2406 * @return true if drawing was succesfull, false if an error occurred 2407 */ 2408 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff, 2409 boolean scalingRequired, Rect dirty) { 2410 2411 // Draw with software renderer. 2412 Canvas canvas; 2413 try { 2414 int left = dirty.left; 2415 int top = dirty.top; 2416 int right = dirty.right; 2417 int bottom = dirty.bottom; 2418 2419 canvas = mSurface.lockCanvas(dirty); 2420 2421 // The dirty rectangle can be modified by Surface.lockCanvas() 2422 //noinspection ConstantConditions 2423 if (left != dirty.left || top != dirty.top || right != dirty.right || 2424 bottom != dirty.bottom) { 2425 attachInfo.mIgnoreDirtyState = true; 2426 } 2427 2428 // TODO: Do this in native 2429 canvas.setDensity(mDensity); 2430 } catch (Surface.OutOfResourcesException e) { 2431 handleOutOfResourcesException(e); 2432 return false; 2433 } catch (IllegalArgumentException e) { 2434 Log.e(TAG, "Could not lock surface", e); 2435 // Don't assume this is due to out of memory, it could be 2436 // something else, and if it is something else then we could 2437 // kill stuff (or ourself) for no reason. 2438 mLayoutRequested = true; // ask wm for a new surface next time. 2439 return false; 2440 } 2441 2442 try { 2443 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2444 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2445 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2446 //canvas.drawARGB(255, 255, 0, 0); 2447 } 2448 2449 // If this bitmap's format includes an alpha channel, we 2450 // need to clear it before drawing so that the child will 2451 // properly re-composite its drawing on a transparent 2452 // background. This automatically respects the clip/dirty region 2453 // or 2454 // If we are applying an offset, we need to clear the area 2455 // where the offset doesn't appear to avoid having garbage 2456 // left in the blank areas. 2457 if (!canvas.isOpaque() || yoff != 0) { 2458 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2459 } 2460 2461 dirty.setEmpty(); 2462 mIsAnimating = false; 2463 attachInfo.mDrawingTime = SystemClock.uptimeMillis(); 2464 mView.mPrivateFlags |= View.PFLAG_DRAWN; 2465 2466 if (DEBUG_DRAW) { 2467 Context cxt = mView.getContext(); 2468 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2469 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2470 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2471 } 2472 try { 2473 canvas.translate(0, -yoff); 2474 if (mTranslator != null) { 2475 mTranslator.translateCanvas(canvas); 2476 } 2477 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0); 2478 attachInfo.mSetIgnoreDirtyState = false; 2479 2480 mView.draw(canvas); 2481 2482 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2483 } finally { 2484 if (!attachInfo.mSetIgnoreDirtyState) { 2485 // Only clear the flag if it was not set during the mView.draw() call 2486 attachInfo.mIgnoreDirtyState = false; 2487 } 2488 } 2489 } finally { 2490 try { 2491 surface.unlockCanvasAndPost(canvas); 2492 } catch (IllegalArgumentException e) { 2493 Log.e(TAG, "Could not unlock surface", e); 2494 mLayoutRequested = true; // ask wm for a new surface next time. 2495 //noinspection ReturnInsideFinallyBlock 2496 return false; 2497 } 2498 2499 if (LOCAL_LOGV) { 2500 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2501 } 2502 } 2503 return true; 2504 } 2505 2506 /** 2507 * We want to draw a highlight around the current accessibility focused. 2508 * Since adding a style for all possible view is not a viable option we 2509 * have this specialized drawing method. 2510 * 2511 * Note: We are doing this here to be able to draw the highlight for 2512 * virtual views in addition to real ones. 2513 * 2514 * @param canvas The canvas on which to draw. 2515 */ 2516 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) { 2517 AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext); 2518 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 2519 return; 2520 } 2521 if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) { 2522 return; 2523 } 2524 Drawable drawable = getAccessibilityFocusedDrawable(); 2525 if (drawable == null) { 2526 return; 2527 } 2528 AccessibilityNodeProvider provider = 2529 mAccessibilityFocusedHost.getAccessibilityNodeProvider(); 2530 Rect bounds = mView.mAttachInfo.mTmpInvalRect; 2531 if (provider == null) { 2532 mAccessibilityFocusedHost.getBoundsOnScreen(bounds); 2533 } else { 2534 if (mAccessibilityFocusedVirtualView == null) { 2535 return; 2536 } 2537 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds); 2538 } 2539 bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop); 2540 bounds.intersect(0, 0, mAttachInfo.mViewRootImpl.mWidth, mAttachInfo.mViewRootImpl.mHeight); 2541 drawable.setBounds(bounds); 2542 drawable.draw(canvas); 2543 } 2544 2545 private Drawable getAccessibilityFocusedDrawable() { 2546 if (mAttachInfo != null) { 2547 // Lazily load the accessibility focus drawable. 2548 if (mAttachInfo.mAccessibilityFocusDrawable == null) { 2549 TypedValue value = new TypedValue(); 2550 final boolean resolved = mView.mContext.getTheme().resolveAttribute( 2551 R.attr.accessibilityFocusedDrawable, value, true); 2552 if (resolved) { 2553 mAttachInfo.mAccessibilityFocusDrawable = 2554 mView.mContext.getResources().getDrawable(value.resourceId); 2555 } 2556 } 2557 return mAttachInfo.mAccessibilityFocusDrawable; 2558 } 2559 return null; 2560 } 2561 2562 void invalidateDisplayLists() { 2563 final ArrayList<DisplayList> displayLists = mDisplayLists; 2564 final int count = displayLists.size(); 2565 2566 for (int i = 0; i < count; i++) { 2567 final DisplayList displayList = displayLists.get(i); 2568 if (displayList.isDirty()) { 2569 displayList.clear(); 2570 } 2571 } 2572 2573 displayLists.clear(); 2574 } 2575 2576 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2577 final View.AttachInfo attachInfo = mAttachInfo; 2578 final Rect ci = attachInfo.mContentInsets; 2579 final Rect vi = attachInfo.mVisibleInsets; 2580 int scrollY = 0; 2581 boolean handled = false; 2582 2583 if (vi.left > ci.left || vi.top > ci.top 2584 || vi.right > ci.right || vi.bottom > ci.bottom) { 2585 // We'll assume that we aren't going to change the scroll 2586 // offset, since we want to avoid that unless it is actually 2587 // going to make the focus visible... otherwise we scroll 2588 // all over the place. 2589 scrollY = mScrollY; 2590 // We can be called for two different situations: during a draw, 2591 // to update the scroll position if the focus has changed (in which 2592 // case 'rectangle' is null), or in response to a 2593 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2594 // is non-null and we just want to scroll to whatever that 2595 // rectangle is). 2596 View focus = mView.findFocus(); 2597 if (focus == null) { 2598 return false; 2599 } 2600 View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null; 2601 if (lastScrolledFocus != null && focus != lastScrolledFocus) { 2602 // If the focus has changed, then ignore any requests to scroll 2603 // to a rectangle; first we want to make sure the entire focus 2604 // view is visible. 2605 rectangle = null; 2606 } 2607 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2608 + " rectangle=" + rectangle + " ci=" + ci 2609 + " vi=" + vi); 2610 if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) { 2611 // Optimization: if the focus hasn't changed since last 2612 // time, and no layout has happened, then just leave things 2613 // as they are. 2614 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2615 + mScrollY + " vi=" + vi.toShortString()); 2616 } else if (focus != null) { 2617 // We need to determine if the currently focused view is 2618 // within the visible part of the window and, if not, apply 2619 // a pan so it can be seen. 2620 mLastScrolledFocus = new WeakReference<View>(focus); 2621 mScrollMayChange = false; 2622 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2623 // Try to find the rectangle from the focus view. 2624 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2625 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2626 + mView.getWidth() + " h=" + mView.getHeight() 2627 + " ci=" + ci.toShortString() 2628 + " vi=" + vi.toShortString()); 2629 if (rectangle == null) { 2630 focus.getFocusedRect(mTempRect); 2631 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2632 + ": focusRect=" + mTempRect.toShortString()); 2633 if (mView instanceof ViewGroup) { 2634 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2635 focus, mTempRect); 2636 } 2637 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2638 "Focus in window: focusRect=" 2639 + mTempRect.toShortString() 2640 + " visRect=" + mVisRect.toShortString()); 2641 } else { 2642 mTempRect.set(rectangle); 2643 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2644 "Request scroll to rect: " 2645 + mTempRect.toShortString() 2646 + " visRect=" + mVisRect.toShortString()); 2647 } 2648 if (mTempRect.intersect(mVisRect)) { 2649 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2650 "Focus window visible rect: " 2651 + mTempRect.toShortString()); 2652 if (mTempRect.height() > 2653 (mView.getHeight()-vi.top-vi.bottom)) { 2654 // If the focus simply is not going to fit, then 2655 // best is probably just to leave things as-is. 2656 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2657 "Too tall; leaving scrollY=" + scrollY); 2658 } else if ((mTempRect.top-scrollY) < vi.top) { 2659 scrollY -= vi.top - (mTempRect.top-scrollY); 2660 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2661 "Top covered; scrollY=" + scrollY); 2662 } else if ((mTempRect.bottom-scrollY) 2663 > (mView.getHeight()-vi.bottom)) { 2664 scrollY += (mTempRect.bottom-scrollY) 2665 - (mView.getHeight()-vi.bottom); 2666 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2667 "Bottom covered; scrollY=" + scrollY); 2668 } 2669 handled = true; 2670 } 2671 } 2672 } 2673 } 2674 2675 if (scrollY != mScrollY) { 2676 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2677 + mScrollY + " , new=" + scrollY); 2678 if (!immediate && mResizeBuffer == null) { 2679 if (mScroller == null) { 2680 mScroller = new Scroller(mView.getContext()); 2681 } 2682 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2683 } else if (mScroller != null) { 2684 mScroller.abortAnimation(); 2685 } 2686 mScrollY = scrollY; 2687 } 2688 2689 return handled; 2690 } 2691 2692 /** 2693 * @hide 2694 */ 2695 public View getAccessibilityFocusedHost() { 2696 return mAccessibilityFocusedHost; 2697 } 2698 2699 /** 2700 * @hide 2701 */ 2702 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() { 2703 return mAccessibilityFocusedVirtualView; 2704 } 2705 2706 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) { 2707 // If we have a virtual view with accessibility focus we need 2708 // to clear the focus and invalidate the virtual view bounds. 2709 if (mAccessibilityFocusedVirtualView != null) { 2710 2711 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView; 2712 View focusHost = mAccessibilityFocusedHost; 2713 focusHost.clearAccessibilityFocusNoCallbacks(); 2714 2715 // Wipe the state of the current accessibility focus since 2716 // the call into the provider to clear accessibility focus 2717 // will fire an accessibility event which will end up calling 2718 // this method and we want to have clean state when this 2719 // invocation happens. 2720 mAccessibilityFocusedHost = null; 2721 mAccessibilityFocusedVirtualView = null; 2722 2723 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider(); 2724 if (provider != null) { 2725 // Invalidate the area of the cleared accessibility focus. 2726 focusNode.getBoundsInParent(mTempRect); 2727 focusHost.invalidate(mTempRect); 2728 // Clear accessibility focus in the virtual node. 2729 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 2730 focusNode.getSourceNodeId()); 2731 provider.performAction(virtualNodeId, 2732 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); 2733 } 2734 focusNode.recycle(); 2735 } 2736 if (mAccessibilityFocusedHost != null) { 2737 // Clear accessibility focus in the view. 2738 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(); 2739 } 2740 2741 // Set the new focus host and node. 2742 mAccessibilityFocusedHost = view; 2743 mAccessibilityFocusedVirtualView = node; 2744 } 2745 2746 public void requestChildFocus(View child, View focused) { 2747 if (DEBUG_INPUT_RESIZE) { 2748 Log.v(TAG, "Request child focus: focus now " + focused); 2749 } 2750 checkThread(); 2751 scheduleTraversals(); 2752 } 2753 2754 public void clearChildFocus(View child) { 2755 if (DEBUG_INPUT_RESIZE) { 2756 Log.v(TAG, "Clearing child focus"); 2757 } 2758 checkThread(); 2759 scheduleTraversals(); 2760 } 2761 2762 @Override 2763 public ViewParent getParentForAccessibility() { 2764 return null; 2765 } 2766 2767 public void focusableViewAvailable(View v) { 2768 checkThread(); 2769 if (mView != null) { 2770 if (!mView.hasFocus()) { 2771 v.requestFocus(); 2772 } else { 2773 // the one case where will transfer focus away from the current one 2774 // is if the current view is a view group that prefers to give focus 2775 // to its children first AND the view is a descendant of it. 2776 View focused = mView.findFocus(); 2777 if (focused instanceof ViewGroup) { 2778 ViewGroup group = (ViewGroup) focused; 2779 if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 2780 && isViewDescendantOf(v, focused)) { 2781 v.requestFocus(); 2782 } 2783 } 2784 } 2785 } 2786 } 2787 2788 public void recomputeViewAttributes(View child) { 2789 checkThread(); 2790 if (mView == child) { 2791 mAttachInfo.mRecomputeGlobalAttributes = true; 2792 if (!mWillDrawSoon) { 2793 scheduleTraversals(); 2794 } 2795 } 2796 } 2797 2798 void dispatchDetachedFromWindow() { 2799 if (mView != null && mView.mAttachInfo != null) { 2800 if (mAttachInfo.mHardwareRenderer != null && 2801 mAttachInfo.mHardwareRenderer.isEnabled()) { 2802 mAttachInfo.mHardwareRenderer.validate(); 2803 } 2804 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false); 2805 mView.dispatchDetachedFromWindow(); 2806 } 2807 2808 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2809 mAccessibilityManager.removeAccessibilityStateChangeListener( 2810 mAccessibilityInteractionConnectionManager); 2811 removeSendWindowContentChangedCallback(); 2812 2813 destroyHardwareRenderer(); 2814 2815 setAccessibilityFocus(null, null); 2816 2817 mView = null; 2818 mAttachInfo.mRootView = null; 2819 mAttachInfo.mSurface = null; 2820 2821 mSurface.release(); 2822 2823 if (mInputQueueCallback != null && mInputQueue != null) { 2824 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2825 mInputQueueCallback = null; 2826 mInputQueue = null; 2827 } else if (mInputEventReceiver != null) { 2828 mInputEventReceiver.dispose(); 2829 mInputEventReceiver = null; 2830 } 2831 try { 2832 mWindowSession.remove(mWindow); 2833 } catch (RemoteException e) { 2834 } 2835 2836 // Dispose the input channel after removing the window so the Window Manager 2837 // doesn't interpret the input channel being closed as an abnormal termination. 2838 if (mInputChannel != null) { 2839 mInputChannel.dispose(); 2840 mInputChannel = null; 2841 } 2842 2843 unscheduleTraversals(); 2844 } 2845 2846 void updateConfiguration(Configuration config, boolean force) { 2847 if (DEBUG_CONFIGURATION) Log.v(TAG, 2848 "Applying new config to window " 2849 + mWindowAttributes.getTitle() 2850 + ": " + config); 2851 2852 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded(); 2853 if (ci != null) { 2854 config = new Configuration(config); 2855 ci.applyToConfiguration(mNoncompatDensity, config); 2856 } 2857 2858 synchronized (sConfigCallbacks) { 2859 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2860 sConfigCallbacks.get(i).onConfigurationChanged(config); 2861 } 2862 } 2863 if (mView != null) { 2864 // At this point the resources have been updated to 2865 // have the most recent config, whatever that is. Use 2866 // the one in them which may be newer. 2867 config = mView.getResources().getConfiguration(); 2868 if (force || mLastConfiguration.diff(config) != 0) { 2869 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection(); 2870 final int currentLayoutDirection = config.getLayoutDirection(); 2871 mLastConfiguration.setTo(config); 2872 if (lastLayoutDirection != currentLayoutDirection && 2873 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 2874 mView.setLayoutDirection(currentLayoutDirection); 2875 } 2876 mView.dispatchConfigurationChanged(config); 2877 } 2878 } 2879 } 2880 2881 /** 2882 * Return true if child is an ancestor of parent, (or equal to the parent). 2883 */ 2884 public static boolean isViewDescendantOf(View child, View parent) { 2885 if (child == parent) { 2886 return true; 2887 } 2888 2889 final ViewParent theParent = child.getParent(); 2890 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2891 } 2892 2893 private static void forceLayout(View view) { 2894 view.forceLayout(); 2895 if (view instanceof ViewGroup) { 2896 ViewGroup group = (ViewGroup) view; 2897 final int count = group.getChildCount(); 2898 for (int i = 0; i < count; i++) { 2899 forceLayout(group.getChildAt(i)); 2900 } 2901 } 2902 } 2903 2904 private final static int MSG_INVALIDATE = 1; 2905 private final static int MSG_INVALIDATE_RECT = 2; 2906 private final static int MSG_DIE = 3; 2907 private final static int MSG_RESIZED = 4; 2908 private final static int MSG_RESIZED_REPORT = 5; 2909 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 2910 private final static int MSG_DISPATCH_KEY = 7; 2911 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 2912 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 2913 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 2914 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 2915 private final static int MSG_CHECK_FOCUS = 13; 2916 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 2917 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 2918 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 2919 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 2920 private final static int MSG_UPDATE_CONFIGURATION = 18; 2921 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 2922 private final static int MSG_DISPATCH_SCREEN_STATE = 20; 2923 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21; 2924 private final static int MSG_DISPATCH_DONE_ANIMATING = 22; 2925 private final static int MSG_INVALIDATE_WORLD = 23; 2926 private final static int MSG_WINDOW_MOVED = 24; 2927 2928 final class ViewRootHandler extends Handler { 2929 @Override 2930 public String getMessageName(Message message) { 2931 switch (message.what) { 2932 case MSG_INVALIDATE: 2933 return "MSG_INVALIDATE"; 2934 case MSG_INVALIDATE_RECT: 2935 return "MSG_INVALIDATE_RECT"; 2936 case MSG_DIE: 2937 return "MSG_DIE"; 2938 case MSG_RESIZED: 2939 return "MSG_RESIZED"; 2940 case MSG_RESIZED_REPORT: 2941 return "MSG_RESIZED_REPORT"; 2942 case MSG_WINDOW_FOCUS_CHANGED: 2943 return "MSG_WINDOW_FOCUS_CHANGED"; 2944 case MSG_DISPATCH_KEY: 2945 return "MSG_DISPATCH_KEY"; 2946 case MSG_DISPATCH_APP_VISIBILITY: 2947 return "MSG_DISPATCH_APP_VISIBILITY"; 2948 case MSG_DISPATCH_GET_NEW_SURFACE: 2949 return "MSG_DISPATCH_GET_NEW_SURFACE"; 2950 case MSG_DISPATCH_KEY_FROM_IME: 2951 return "MSG_DISPATCH_KEY_FROM_IME"; 2952 case MSG_FINISH_INPUT_CONNECTION: 2953 return "MSG_FINISH_INPUT_CONNECTION"; 2954 case MSG_CHECK_FOCUS: 2955 return "MSG_CHECK_FOCUS"; 2956 case MSG_CLOSE_SYSTEM_DIALOGS: 2957 return "MSG_CLOSE_SYSTEM_DIALOGS"; 2958 case MSG_DISPATCH_DRAG_EVENT: 2959 return "MSG_DISPATCH_DRAG_EVENT"; 2960 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 2961 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 2962 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 2963 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 2964 case MSG_UPDATE_CONFIGURATION: 2965 return "MSG_UPDATE_CONFIGURATION"; 2966 case MSG_PROCESS_INPUT_EVENTS: 2967 return "MSG_PROCESS_INPUT_EVENTS"; 2968 case MSG_DISPATCH_SCREEN_STATE: 2969 return "MSG_DISPATCH_SCREEN_STATE"; 2970 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 2971 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 2972 case MSG_DISPATCH_DONE_ANIMATING: 2973 return "MSG_DISPATCH_DONE_ANIMATING"; 2974 case MSG_WINDOW_MOVED: 2975 return "MSG_WINDOW_MOVED"; 2976 } 2977 return super.getMessageName(message); 2978 } 2979 2980 @Override 2981 public void handleMessage(Message msg) { 2982 switch (msg.what) { 2983 case MSG_INVALIDATE: 2984 ((View) msg.obj).invalidate(); 2985 break; 2986 case MSG_INVALIDATE_RECT: 2987 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 2988 info.target.invalidate(info.left, info.top, info.right, info.bottom); 2989 info.recycle(); 2990 break; 2991 case MSG_PROCESS_INPUT_EVENTS: 2992 mProcessInputEventsScheduled = false; 2993 doProcessInputEvents(); 2994 break; 2995 case MSG_DISPATCH_APP_VISIBILITY: 2996 handleAppVisibility(msg.arg1 != 0); 2997 break; 2998 case MSG_DISPATCH_GET_NEW_SURFACE: 2999 handleGetNewSurface(); 3000 break; 3001 case MSG_RESIZED: { 3002 // Recycled in the fall through... 3003 SomeArgs args = (SomeArgs) msg.obj; 3004 if (mWinFrame.equals(args.arg1) 3005 && mPendingOverscanInsets.equals(args.arg5) 3006 && mPendingContentInsets.equals(args.arg2) 3007 && mPendingVisibleInsets.equals(args.arg3) 3008 && args.arg4 == null) { 3009 break; 3010 } 3011 } // fall through... 3012 case MSG_RESIZED_REPORT: 3013 if (mAdded) { 3014 SomeArgs args = (SomeArgs) msg.obj; 3015 3016 Configuration config = (Configuration) args.arg4; 3017 if (config != null) { 3018 updateConfiguration(config, false); 3019 } 3020 3021 mWinFrame.set((Rect) args.arg1); 3022 mPendingOverscanInsets.set((Rect) args.arg5); 3023 mPendingContentInsets.set((Rect) args.arg2); 3024 mPendingVisibleInsets.set((Rect) args.arg3); 3025 3026 args.recycle(); 3027 3028 if (msg.what == MSG_RESIZED_REPORT) { 3029 mReportNextDraw = true; 3030 } 3031 3032 if (mView != null) { 3033 forceLayout(mView); 3034 } 3035 3036 requestLayout(); 3037 } 3038 break; 3039 case MSG_WINDOW_MOVED: 3040 if (mAdded) { 3041 final int w = mWinFrame.width(); 3042 final int h = mWinFrame.height(); 3043 final int l = msg.arg1; 3044 final int t = msg.arg2; 3045 mWinFrame.left = l; 3046 mWinFrame.right = l + w; 3047 mWinFrame.top = t; 3048 mWinFrame.bottom = t + h; 3049 3050 if (mView != null) { 3051 forceLayout(mView); 3052 } 3053 requestLayout(); 3054 } 3055 break; 3056 case MSG_WINDOW_FOCUS_CHANGED: { 3057 if (mAdded) { 3058 boolean hasWindowFocus = msg.arg1 != 0; 3059 mAttachInfo.mHasWindowFocus = hasWindowFocus; 3060 3061 profileRendering(hasWindowFocus); 3062 3063 if (hasWindowFocus) { 3064 boolean inTouchMode = msg.arg2 != 0; 3065 ensureTouchModeLocally(inTouchMode); 3066 3067 if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){ 3068 mFullRedrawNeeded = true; 3069 try { 3070 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 3071 mWidth, mHeight, mHolder.getSurface()); 3072 } catch (Surface.OutOfResourcesException e) { 3073 Log.e(TAG, "OutOfResourcesException locking surface", e); 3074 try { 3075 if (!mWindowSession.outOfMemory(mWindow)) { 3076 Slog.w(TAG, "No processes killed for memory; killing self"); 3077 Process.killProcess(Process.myPid()); 3078 } 3079 } catch (RemoteException ex) { 3080 } 3081 // Retry in a bit. 3082 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 3083 return; 3084 } 3085 } 3086 } 3087 3088 mLastWasImTarget = WindowManager.LayoutParams 3089 .mayUseInputMethod(mWindowAttributes.flags); 3090 3091 InputMethodManager imm = InputMethodManager.peekInstance(); 3092 if (mView != null) { 3093 if (hasWindowFocus && imm != null && mLastWasImTarget) { 3094 imm.startGettingWindowFocus(mView); 3095 } 3096 mAttachInfo.mKeyDispatchState.reset(); 3097 mView.dispatchWindowFocusChanged(hasWindowFocus); 3098 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus); 3099 } 3100 3101 // Note: must be done after the focus change callbacks, 3102 // so all of the view state is set up correctly. 3103 if (hasWindowFocus) { 3104 if (imm != null && mLastWasImTarget) { 3105 imm.onWindowFocus(mView, mView.findFocus(), 3106 mWindowAttributes.softInputMode, 3107 !mHasHadWindowFocus, mWindowAttributes.flags); 3108 } 3109 // Clear the forward bit. We can just do this directly, since 3110 // the window manager doesn't care about it. 3111 mWindowAttributes.softInputMode &= 3112 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3113 ((WindowManager.LayoutParams)mView.getLayoutParams()) 3114 .softInputMode &= 3115 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3116 mHasHadWindowFocus = true; 3117 } 3118 3119 setAccessibilityFocus(null, null); 3120 3121 if (mView != null && mAccessibilityManager.isEnabled()) { 3122 if (hasWindowFocus) { 3123 mView.sendAccessibilityEvent( 3124 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 3125 } 3126 } 3127 } 3128 } break; 3129 case MSG_DIE: 3130 doDie(); 3131 break; 3132 case MSG_DISPATCH_KEY: { 3133 KeyEvent event = (KeyEvent)msg.obj; 3134 enqueueInputEvent(event, null, 0, true); 3135 } break; 3136 case MSG_DISPATCH_KEY_FROM_IME: { 3137 if (LOCAL_LOGV) Log.v( 3138 TAG, "Dispatching key " 3139 + msg.obj + " from IME to " + mView); 3140 KeyEvent event = (KeyEvent)msg.obj; 3141 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 3142 // The IME is trying to say this event is from the 3143 // system! Bad bad bad! 3144 //noinspection UnusedAssignment 3145 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 3146 } 3147 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 3148 } break; 3149 case MSG_FINISH_INPUT_CONNECTION: { 3150 InputMethodManager imm = InputMethodManager.peekInstance(); 3151 if (imm != null) { 3152 imm.reportFinishInputConnection((InputConnection)msg.obj); 3153 } 3154 } break; 3155 case MSG_CHECK_FOCUS: { 3156 InputMethodManager imm = InputMethodManager.peekInstance(); 3157 if (imm != null) { 3158 imm.checkFocus(); 3159 } 3160 } break; 3161 case MSG_CLOSE_SYSTEM_DIALOGS: { 3162 if (mView != null) { 3163 mView.onCloseSystemDialogs((String)msg.obj); 3164 } 3165 } break; 3166 case MSG_DISPATCH_DRAG_EVENT: 3167 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 3168 DragEvent event = (DragEvent)msg.obj; 3169 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 3170 handleDragEvent(event); 3171 } break; 3172 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 3173 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); 3174 } break; 3175 case MSG_UPDATE_CONFIGURATION: { 3176 Configuration config = (Configuration)msg.obj; 3177 if (config.isOtherSeqNewer(mLastConfiguration)) { 3178 config = mLastConfiguration; 3179 } 3180 updateConfiguration(config, false); 3181 } break; 3182 case MSG_DISPATCH_SCREEN_STATE: { 3183 if (mView != null) { 3184 handleScreenStateChange(msg.arg1 == 1); 3185 } 3186 } break; 3187 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3188 setAccessibilityFocus(null, null); 3189 } break; 3190 case MSG_DISPATCH_DONE_ANIMATING: { 3191 handleDispatchDoneAnimating(); 3192 } break; 3193 case MSG_INVALIDATE_WORLD: { 3194 if (mView != null) { 3195 invalidateWorld(mView); 3196 } 3197 } break; 3198 } 3199 } 3200 } 3201 3202 final ViewRootHandler mHandler = new ViewRootHandler(); 3203 3204 /** 3205 * Something in the current window tells us we need to change the touch mode. For 3206 * example, we are not in touch mode, and the user touches the screen. 3207 * 3208 * If the touch mode has changed, tell the window manager, and handle it locally. 3209 * 3210 * @param inTouchMode Whether we want to be in touch mode. 3211 * @return True if the touch mode changed and focus changed was changed as a result 3212 */ 3213 boolean ensureTouchMode(boolean inTouchMode) { 3214 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3215 + "touch mode is " + mAttachInfo.mInTouchMode); 3216 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3217 3218 // tell the window manager 3219 try { 3220 mWindowSession.setInTouchMode(inTouchMode); 3221 } catch (RemoteException e) { 3222 throw new RuntimeException(e); 3223 } 3224 3225 // handle the change 3226 return ensureTouchModeLocally(inTouchMode); 3227 } 3228 3229 /** 3230 * Ensure that the touch mode for this window is set, and if it is changing, 3231 * take the appropriate action. 3232 * @param inTouchMode Whether we want to be in touch mode. 3233 * @return True if the touch mode changed and focus changed was changed as a result 3234 */ 3235 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3236 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3237 + "touch mode is " + mAttachInfo.mInTouchMode); 3238 3239 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3240 3241 mAttachInfo.mInTouchMode = inTouchMode; 3242 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3243 3244 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3245 } 3246 3247 private boolean enterTouchMode() { 3248 if (mView != null) { 3249 if (mView.hasFocus()) { 3250 // note: not relying on mFocusedView here because this could 3251 // be when the window is first being added, and mFocused isn't 3252 // set yet. 3253 final View focused = mView.findFocus(); 3254 if (focused != null && !focused.isFocusableInTouchMode()) { 3255 final ViewGroup ancestorToTakeFocus = 3256 findAncestorToTakeFocusInTouchMode(focused); 3257 if (ancestorToTakeFocus != null) { 3258 // there is an ancestor that wants focus after its descendants that 3259 // is focusable in touch mode.. give it focus 3260 return ancestorToTakeFocus.requestFocus(); 3261 } else { 3262 // nothing appropriate to have focus in touch mode, clear it out 3263 focused.unFocus(); 3264 return true; 3265 } 3266 } 3267 } 3268 } 3269 return false; 3270 } 3271 3272 /** 3273 * Find an ancestor of focused that wants focus after its descendants and is 3274 * focusable in touch mode. 3275 * @param focused The currently focused view. 3276 * @return An appropriate view, or null if no such view exists. 3277 */ 3278 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3279 ViewParent parent = focused.getParent(); 3280 while (parent instanceof ViewGroup) { 3281 final ViewGroup vgParent = (ViewGroup) parent; 3282 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3283 && vgParent.isFocusableInTouchMode()) { 3284 return vgParent; 3285 } 3286 if (vgParent.isRootNamespace()) { 3287 return null; 3288 } else { 3289 parent = vgParent.getParent(); 3290 } 3291 } 3292 return null; 3293 } 3294 3295 private boolean leaveTouchMode() { 3296 if (mView != null) { 3297 if (mView.hasFocus()) { 3298 View focusedView = mView.findFocus(); 3299 if (!(focusedView instanceof ViewGroup)) { 3300 // some view has focus, let it keep it 3301 return false; 3302 } else if (((ViewGroup) focusedView).getDescendantFocusability() != 3303 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3304 // some view group has focus, and doesn't prefer its children 3305 // over itself for focus, so let them keep it. 3306 return false; 3307 } 3308 } 3309 3310 // find the best view to give focus to in this brave new non-touch-mode 3311 // world 3312 final View focused = focusSearch(null, View.FOCUS_DOWN); 3313 if (focused != null) { 3314 return focused.requestFocus(View.FOCUS_DOWN); 3315 } 3316 } 3317 return false; 3318 } 3319 3320 /** 3321 * Base class for implementing a stage in the chain of responsibility 3322 * for processing input events. 3323 * <p> 3324 * Events are delivered to the stage by the {@link #deliver} method. The stage 3325 * then has the choice of finishing the event or forwarding it to the next stage. 3326 * </p> 3327 */ 3328 abstract class InputStage { 3329 private final InputStage mNext; 3330 3331 protected static final int FORWARD = 0; 3332 protected static final int FINISH_HANDLED = 1; 3333 protected static final int FINISH_NOT_HANDLED = 2; 3334 3335 /** 3336 * Creates an input stage. 3337 * @param next The next stage to which events should be forwarded. 3338 */ 3339 public InputStage(InputStage next) { 3340 mNext = next; 3341 } 3342 3343 /** 3344 * Delivers an event to be processed. 3345 */ 3346 public final void deliver(QueuedInputEvent q) { 3347 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) { 3348 forward(q); 3349 } else if (mView == null || !mAdded) { 3350 finish(q, false); 3351 } else { 3352 apply(q, onProcess(q)); 3353 } 3354 } 3355 3356 /** 3357 * Marks the the input event as finished then forwards it to the next stage. 3358 */ 3359 protected void finish(QueuedInputEvent q, boolean handled) { 3360 q.mFlags |= QueuedInputEvent.FLAG_FINISHED; 3361 if (handled) { 3362 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED; 3363 } 3364 forward(q); 3365 } 3366 3367 /** 3368 * Forwards the event to the next stage. 3369 */ 3370 protected void forward(QueuedInputEvent q) { 3371 onDeliverToNext(q); 3372 } 3373 3374 /** 3375 * Applies a result code from {@link #onProcess} to the specified event. 3376 */ 3377 protected void apply(QueuedInputEvent q, int result) { 3378 if (result == FORWARD) { 3379 forward(q); 3380 } else if (result == FINISH_HANDLED) { 3381 finish(q, true); 3382 } else if (result == FINISH_NOT_HANDLED) { 3383 finish(q, false); 3384 } else { 3385 throw new IllegalArgumentException("Invalid result: " + result); 3386 } 3387 } 3388 3389 /** 3390 * Called when an event is ready to be processed. 3391 * @return A result code indicating how the event was handled. 3392 */ 3393 protected int onProcess(QueuedInputEvent q) { 3394 return FORWARD; 3395 } 3396 3397 /** 3398 * Called when an event is being delivered to the next stage. 3399 */ 3400 protected void onDeliverToNext(QueuedInputEvent q) { 3401 if (mNext != null) { 3402 mNext.deliver(q); 3403 } else { 3404 finishInputEvent(q); 3405 } 3406 } 3407 } 3408 3409 /** 3410 * Base class for implementing an input pipeline stage that supports 3411 * asynchronous and out-of-order processing of input events. 3412 * <p> 3413 * In addition to what a normal input stage can do, an asynchronous 3414 * input stage may also defer an input event that has been delivered to it 3415 * and finish or forward it later. 3416 * </p> 3417 */ 3418 abstract class AsyncInputStage extends InputStage { 3419 private final String mTraceCounter; 3420 3421 private QueuedInputEvent mQueueHead; 3422 private QueuedInputEvent mQueueTail; 3423 private int mQueueLength; 3424 3425 protected static final int DEFER = 3; 3426 3427 /** 3428 * Creates an asynchronous input stage. 3429 * @param next The next stage to which events should be forwarded. 3430 * @param traceCounter The name of a counter to record the size of 3431 * the queue of pending events. 3432 */ 3433 public AsyncInputStage(InputStage next, String traceCounter) { 3434 super(next); 3435 mTraceCounter = traceCounter; 3436 } 3437 3438 /** 3439 * Marks the event as deferred, which is to say that it will be handled 3440 * asynchronously. The caller is responsible for calling {@link #forward} 3441 * or {@link #finish} later when it is done handling the event. 3442 */ 3443 protected void defer(QueuedInputEvent q) { 3444 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED; 3445 enqueue(q); 3446 } 3447 3448 @Override 3449 protected void forward(QueuedInputEvent q) { 3450 // Clear the deferred flag. 3451 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED; 3452 3453 // Fast path if the queue is empty. 3454 QueuedInputEvent curr = mQueueHead; 3455 if (curr == null) { 3456 super.forward(q); 3457 return; 3458 } 3459 3460 // Determine whether the event must be serialized behind any others 3461 // before it can be delivered to the next stage. This is done because 3462 // deferred events might be handled out of order by the stage. 3463 final int deviceId = q.mEvent.getDeviceId(); 3464 QueuedInputEvent prev = null; 3465 boolean blocked = false; 3466 while (curr != null && curr != q) { 3467 if (!blocked && deviceId == curr.mEvent.getDeviceId()) { 3468 blocked = true; 3469 } 3470 prev = curr; 3471 curr = curr.mNext; 3472 } 3473 3474 // If the event is blocked, then leave it in the queue to be delivered later. 3475 // Note that the event might not yet be in the queue if it was not previously 3476 // deferred so we will enqueue it if needed. 3477 if (blocked) { 3478 if (curr == null) { 3479 enqueue(q); 3480 } 3481 return; 3482 } 3483 3484 // The event is not blocked. Deliver it immediately. 3485 if (curr != null) { 3486 curr = curr.mNext; 3487 dequeue(q, prev); 3488 } 3489 super.forward(q); 3490 3491 // Dequeuing this event may have unblocked successors. Deliver them. 3492 while (curr != null) { 3493 if (deviceId == curr.mEvent.getDeviceId()) { 3494 if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) { 3495 break; 3496 } 3497 QueuedInputEvent next = curr.mNext; 3498 dequeue(curr, prev); 3499 super.forward(curr); 3500 curr = next; 3501 } else { 3502 prev = curr; 3503 curr = curr.mNext; 3504 } 3505 } 3506 } 3507 3508 @Override 3509 protected void apply(QueuedInputEvent q, int result) { 3510 if (result == DEFER) { 3511 defer(q); 3512 } else { 3513 super.apply(q, result); 3514 } 3515 } 3516 3517 private void enqueue(QueuedInputEvent q) { 3518 if (mQueueTail == null) { 3519 mQueueHead = q; 3520 mQueueTail = q; 3521 } else { 3522 mQueueTail.mNext = q; 3523 mQueueTail = q; 3524 } 3525 3526 mQueueLength += 1; 3527 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3528 } 3529 3530 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) { 3531 if (prev == null) { 3532 mQueueHead = q.mNext; 3533 } else { 3534 prev.mNext = q.mNext; 3535 } 3536 if (mQueueTail == q) { 3537 mQueueTail = prev; 3538 } 3539 q.mNext = null; 3540 3541 mQueueLength -= 1; 3542 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength); 3543 } 3544 } 3545 3546 /** 3547 * Delivers pre-ime input events to a native activity. 3548 * Does not support pointer events. 3549 */ 3550 final class NativePreImeInputStage extends AsyncInputStage { 3551 public NativePreImeInputStage(InputStage next, String traceCounter) { 3552 super(next, traceCounter); 3553 } 3554 3555 @Override 3556 protected int onProcess(QueuedInputEvent q) { 3557 return FORWARD; 3558 } 3559 } 3560 3561 /** 3562 * Delivers pre-ime input events to the view hierarchy. 3563 * Does not support pointer events. 3564 */ 3565 final class ViewPreImeInputStage extends InputStage { 3566 public ViewPreImeInputStage(InputStage next) { 3567 super(next); 3568 } 3569 3570 @Override 3571 protected int onProcess(QueuedInputEvent q) { 3572 if (q.mEvent instanceof KeyEvent) { 3573 return processKeyEvent(q); 3574 } 3575 return FORWARD; 3576 } 3577 3578 private int processKeyEvent(QueuedInputEvent q) { 3579 final KeyEvent event = (KeyEvent)q.mEvent; 3580 if (mView.dispatchKeyEventPreIme(event)) { 3581 return FINISH_HANDLED; 3582 } 3583 return FORWARD; 3584 } 3585 } 3586 3587 /** 3588 * Delivers input events to the ime. 3589 * Does not support pointer events. 3590 */ 3591 final class ImeInputStage extends AsyncInputStage 3592 implements InputMethodManager.FinishedInputEventCallback { 3593 public ImeInputStage(InputStage next, String traceCounter) { 3594 super(next, traceCounter); 3595 } 3596 3597 @Override 3598 protected int onProcess(QueuedInputEvent q) { 3599 if (mLastWasImTarget) { 3600 InputMethodManager imm = InputMethodManager.peekInstance(); 3601 if (imm != null) { 3602 final InputEvent event = q.mEvent; 3603 if (DEBUG_IMF) Log.v(TAG, "Sending input event to IME: " + event); 3604 int result = imm.dispatchInputEvent(event, q, this, mHandler); 3605 if (result == InputMethodManager.DISPATCH_HANDLED) { 3606 return FINISH_HANDLED; 3607 } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) { 3608 return FINISH_NOT_HANDLED; 3609 } else { 3610 return DEFER; // callback will be invoked later 3611 } 3612 } 3613 } 3614 return FORWARD; 3615 } 3616 3617 @Override 3618 public void onFinishedInputEvent(Object token, boolean handled) { 3619 QueuedInputEvent q = (QueuedInputEvent)token; 3620 if (handled) { 3621 finish(q, true); 3622 return; 3623 } 3624 3625 // If the window doesn't currently have input focus, then drop 3626 // this event. This could be an event that came back from the 3627 // IME dispatch but the window has lost focus in the meantime. 3628 if (!mAttachInfo.mHasWindowFocus && !isTerminalInputEvent(q.mEvent)) { 3629 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent); 3630 finish(q, false); 3631 return; 3632 } 3633 3634 forward(q); 3635 } 3636 } 3637 3638 /** 3639 * Performs early processing of post-ime input events. 3640 */ 3641 final class EarlyPostImeInputStage extends InputStage { 3642 public EarlyPostImeInputStage(InputStage next) { 3643 super(next); 3644 } 3645 3646 @Override 3647 protected int onProcess(QueuedInputEvent q) { 3648 if (q.mEvent instanceof KeyEvent) { 3649 return processKeyEvent(q); 3650 } else { 3651 final int source = q.mEvent.getSource(); 3652 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3653 return processPointerEvent(q); 3654 } 3655 } 3656 return FORWARD; 3657 } 3658 3659 private int processKeyEvent(QueuedInputEvent q) { 3660 final KeyEvent event = (KeyEvent)q.mEvent; 3661 3662 // If the key's purpose is to exit touch mode then we consume it 3663 // and consider it handled. 3664 if (checkForLeavingTouchModeAndConsume(event)) { 3665 return FINISH_HANDLED; 3666 } 3667 3668 // Make sure the fallback event policy sees all keys that will be 3669 // delivered to the view hierarchy. 3670 mFallbackEventHandler.preDispatchKeyEvent(event); 3671 return FORWARD; 3672 } 3673 3674 private int processPointerEvent(QueuedInputEvent q) { 3675 final MotionEvent event = (MotionEvent)q.mEvent; 3676 3677 // Translate the pointer event for compatibility, if needed. 3678 if (mTranslator != null) { 3679 mTranslator.translateEventInScreenToAppWindow(event); 3680 } 3681 3682 // Enter touch mode on down or scroll. 3683 final int action = event.getAction(); 3684 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3685 ensureTouchMode(true); 3686 } 3687 3688 // Offset the scroll position. 3689 if (mCurScrollY != 0) { 3690 event.offsetLocation(0, mCurScrollY); 3691 } 3692 3693 // Remember the touch position for possible drag-initiation. 3694 if (event.isTouchEvent()) { 3695 mLastTouchPoint.x = event.getRawX(); 3696 mLastTouchPoint.y = event.getRawY(); 3697 } 3698 return FORWARD; 3699 } 3700 } 3701 3702 /** 3703 * Delivers post-ime input events to a native activity. 3704 */ 3705 final class NativePostImeInputStage extends AsyncInputStage { 3706 public NativePostImeInputStage(InputStage next, String traceCounter) { 3707 super(next, traceCounter); 3708 } 3709 3710 @Override 3711 protected int onProcess(QueuedInputEvent q) { 3712 return FORWARD; 3713 } 3714 } 3715 3716 /** 3717 * Delivers post-ime input events to the view hierarchy. 3718 */ 3719 final class ViewPostImeInputStage extends InputStage { 3720 public ViewPostImeInputStage(InputStage next) { 3721 super(next); 3722 } 3723 3724 @Override 3725 protected int onProcess(QueuedInputEvent q) { 3726 if (q.mEvent instanceof KeyEvent) { 3727 return processKeyEvent(q); 3728 } else { 3729 final int source = q.mEvent.getSource(); 3730 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3731 return processPointerEvent(q); 3732 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3733 return processTrackballEvent(q); 3734 } else { 3735 return processGenericMotionEvent(q); 3736 } 3737 } 3738 } 3739 3740 private int processKeyEvent(QueuedInputEvent q) { 3741 final KeyEvent event = (KeyEvent)q.mEvent; 3742 3743 // Deliver the key to the view hierarchy. 3744 if (mView.dispatchKeyEvent(event)) { 3745 return FINISH_HANDLED; 3746 } 3747 3748 // If the Control modifier is held, try to interpret the key as a shortcut. 3749 if (event.getAction() == KeyEvent.ACTION_DOWN 3750 && event.isCtrlPressed() 3751 && event.getRepeatCount() == 0 3752 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3753 if (mView.dispatchKeyShortcutEvent(event)) { 3754 return FINISH_HANDLED; 3755 } 3756 } 3757 3758 // Apply the fallback event policy. 3759 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3760 return FINISH_HANDLED; 3761 } 3762 3763 // Handle automatic focus changes. 3764 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3765 int direction = 0; 3766 switch (event.getKeyCode()) { 3767 case KeyEvent.KEYCODE_DPAD_LEFT: 3768 if (event.hasNoModifiers()) { 3769 direction = View.FOCUS_LEFT; 3770 } 3771 break; 3772 case KeyEvent.KEYCODE_DPAD_RIGHT: 3773 if (event.hasNoModifiers()) { 3774 direction = View.FOCUS_RIGHT; 3775 } 3776 break; 3777 case KeyEvent.KEYCODE_DPAD_UP: 3778 if (event.hasNoModifiers()) { 3779 direction = View.FOCUS_UP; 3780 } 3781 break; 3782 case KeyEvent.KEYCODE_DPAD_DOWN: 3783 if (event.hasNoModifiers()) { 3784 direction = View.FOCUS_DOWN; 3785 } 3786 break; 3787 case KeyEvent.KEYCODE_TAB: 3788 if (event.hasNoModifiers()) { 3789 direction = View.FOCUS_FORWARD; 3790 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3791 direction = View.FOCUS_BACKWARD; 3792 } 3793 break; 3794 } 3795 if (direction != 0) { 3796 View focused = mView.findFocus(); 3797 if (focused != null) { 3798 View v = focused.focusSearch(direction); 3799 if (v != null && v != focused) { 3800 // do the math the get the interesting rect 3801 // of previous focused into the coord system of 3802 // newly focused view 3803 focused.getFocusedRect(mTempRect); 3804 if (mView instanceof ViewGroup) { 3805 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3806 focused, mTempRect); 3807 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3808 v, mTempRect); 3809 } 3810 if (v.requestFocus(direction, mTempRect)) { 3811 playSoundEffect(SoundEffectConstants 3812 .getContantForFocusDirection(direction)); 3813 return FINISH_HANDLED; 3814 } 3815 } 3816 3817 // Give the focused view a last chance to handle the dpad key. 3818 if (mView.dispatchUnhandledMove(focused, direction)) { 3819 return FINISH_HANDLED; 3820 } 3821 } else { 3822 // find the best view to give focus to in this non-touch-mode with no-focus 3823 View v = focusSearch(null, direction); 3824 if (v != null && v.requestFocus(direction)) { 3825 return FINISH_HANDLED; 3826 } 3827 } 3828 } 3829 } 3830 return FORWARD; 3831 } 3832 3833 private int processPointerEvent(QueuedInputEvent q) { 3834 final MotionEvent event = (MotionEvent)q.mEvent; 3835 3836 if (mView.dispatchPointerEvent(event)) { 3837 return FINISH_HANDLED; 3838 } 3839 return FORWARD; 3840 } 3841 3842 private int processTrackballEvent(QueuedInputEvent q) { 3843 final MotionEvent event = (MotionEvent)q.mEvent; 3844 3845 if (mView.dispatchTrackballEvent(event)) { 3846 return FINISH_HANDLED; 3847 } 3848 return FORWARD; 3849 } 3850 3851 private int processGenericMotionEvent(QueuedInputEvent q) { 3852 final MotionEvent event = (MotionEvent)q.mEvent; 3853 3854 // Deliver the event to the view. 3855 if (mView.dispatchGenericMotionEvent(event)) { 3856 return FINISH_HANDLED; 3857 } 3858 return FORWARD; 3859 } 3860 } 3861 3862 /** 3863 * Performs synthesis of new input events from unhandled input events. 3864 */ 3865 final class SyntheticInputStage extends InputStage { 3866 private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler(); 3867 private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler(); 3868 private final SyntheticTouchNavigationHandler mTouchNavigation = 3869 new SyntheticTouchNavigationHandler(); 3870 3871 public SyntheticInputStage() { 3872 super(null); 3873 } 3874 3875 @Override 3876 protected int onProcess(QueuedInputEvent q) { 3877 q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED; 3878 if (q.mEvent instanceof MotionEvent) { 3879 final MotionEvent event = (MotionEvent)q.mEvent; 3880 final int source = event.getSource(); 3881 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3882 mTrackball.process(event); 3883 return FINISH_HANDLED; 3884 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 3885 mJoystick.process(event); 3886 return FINISH_HANDLED; 3887 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 3888 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 3889 mTouchNavigation.process(event); 3890 return FINISH_HANDLED; 3891 } 3892 } 3893 return FORWARD; 3894 } 3895 3896 @Override 3897 protected void onDeliverToNext(QueuedInputEvent q) { 3898 if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) { 3899 // Cancel related synthetic events if any prior stage has handled the event. 3900 if (q.mEvent instanceof MotionEvent) { 3901 final MotionEvent event = (MotionEvent)q.mEvent; 3902 final int source = event.getSource(); 3903 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3904 mTrackball.cancel(event); 3905 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 3906 mJoystick.cancel(event); 3907 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) 3908 == InputDevice.SOURCE_TOUCH_NAVIGATION) { 3909 mTouchNavigation.cancel(event); 3910 } 3911 } 3912 } 3913 super.onDeliverToNext(q); 3914 } 3915 } 3916 3917 /** 3918 * Creates dpad events from unhandled trackball movements. 3919 */ 3920 final class SyntheticTrackballHandler { 3921 private final TrackballAxis mX = new TrackballAxis(); 3922 private final TrackballAxis mY = new TrackballAxis(); 3923 private long mLastTime; 3924 3925 public void process(MotionEvent event) { 3926 // Translate the trackball event into DPAD keys and try to deliver those. 3927 long curTime = SystemClock.uptimeMillis(); 3928 if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) { 3929 // It has been too long since the last movement, 3930 // so restart at the beginning. 3931 mX.reset(0); 3932 mY.reset(0); 3933 mLastTime = curTime; 3934 } 3935 3936 final int action = event.getAction(); 3937 final int metaState = event.getMetaState(); 3938 switch (action) { 3939 case MotionEvent.ACTION_DOWN: 3940 mX.reset(2); 3941 mY.reset(2); 3942 enqueueInputEvent(new KeyEvent(curTime, curTime, 3943 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3944 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3945 InputDevice.SOURCE_KEYBOARD)); 3946 break; 3947 case MotionEvent.ACTION_UP: 3948 mX.reset(2); 3949 mY.reset(2); 3950 enqueueInputEvent(new KeyEvent(curTime, curTime, 3951 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3952 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3953 InputDevice.SOURCE_KEYBOARD)); 3954 break; 3955 } 3956 3957 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + mX.position + " step=" 3958 + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration 3959 + " move=" + event.getX() 3960 + " / Y=" + mY.position + " step=" 3961 + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration 3962 + " move=" + event.getY()); 3963 final float xOff = mX.collect(event.getX(), event.getEventTime(), "X"); 3964 final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y"); 3965 3966 // Generate DPAD events based on the trackball movement. 3967 // We pick the axis that has moved the most as the direction of 3968 // the DPAD. When we generate DPAD events for one axis, then the 3969 // other axis is reset -- we don't want to perform DPAD jumps due 3970 // to slight movements in the trackball when making major movements 3971 // along the other axis. 3972 int keycode = 0; 3973 int movement = 0; 3974 float accel = 1; 3975 if (xOff > yOff) { 3976 movement = mX.generate(); 3977 if (movement != 0) { 3978 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3979 : KeyEvent.KEYCODE_DPAD_LEFT; 3980 accel = mX.acceleration; 3981 mY.reset(2); 3982 } 3983 } else if (yOff > 0) { 3984 movement = mY.generate(); 3985 if (movement != 0) { 3986 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3987 : KeyEvent.KEYCODE_DPAD_UP; 3988 accel = mY.acceleration; 3989 mX.reset(2); 3990 } 3991 } 3992 3993 if (keycode != 0) { 3994 if (movement < 0) movement = -movement; 3995 int accelMovement = (int)(movement * accel); 3996 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 3997 + " accelMovement=" + accelMovement 3998 + " accel=" + accel); 3999 if (accelMovement > movement) { 4000 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4001 + keycode); 4002 movement--; 4003 int repeatCount = accelMovement - movement; 4004 enqueueInputEvent(new KeyEvent(curTime, curTime, 4005 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 4006 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4007 InputDevice.SOURCE_KEYBOARD)); 4008 } 4009 while (movement > 0) { 4010 if (DEBUG_TRACKBALL) Log.v(TAG, "Delivering fake DPAD: " 4011 + keycode); 4012 movement--; 4013 curTime = SystemClock.uptimeMillis(); 4014 enqueueInputEvent(new KeyEvent(curTime, curTime, 4015 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 4016 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4017 InputDevice.SOURCE_KEYBOARD)); 4018 enqueueInputEvent(new KeyEvent(curTime, curTime, 4019 KeyEvent.ACTION_UP, keycode, 0, metaState, 4020 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 4021 InputDevice.SOURCE_KEYBOARD)); 4022 } 4023 mLastTime = curTime; 4024 } 4025 } 4026 4027 public void cancel(MotionEvent event) { 4028 mLastTime = Integer.MIN_VALUE; 4029 4030 // If we reach this, we consumed a trackball event. 4031 // Because we will not translate the trackball event into a key event, 4032 // touch mode will not exit, so we exit touch mode here. 4033 if (mView != null && mAdded) { 4034 ensureTouchMode(false); 4035 } 4036 } 4037 } 4038 4039 /** 4040 * Maintains state information for a single trackball axis, generating 4041 * discrete (DPAD) movements based on raw trackball motion. 4042 */ 4043 static final class TrackballAxis { 4044 /** 4045 * The maximum amount of acceleration we will apply. 4046 */ 4047 static final float MAX_ACCELERATION = 20; 4048 4049 /** 4050 * The maximum amount of time (in milliseconds) between events in order 4051 * for us to consider the user to be doing fast trackball movements, 4052 * and thus apply an acceleration. 4053 */ 4054 static final long FAST_MOVE_TIME = 150; 4055 4056 /** 4057 * Scaling factor to the time (in milliseconds) between events to how 4058 * much to multiple/divide the current acceleration. When movement 4059 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4060 * FAST_MOVE_TIME it divides it. 4061 */ 4062 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4063 4064 static final float FIRST_MOVEMENT_THRESHOLD = 0.5f; 4065 static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f; 4066 static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f; 4067 4068 float position; 4069 float acceleration = 1; 4070 long lastMoveTime = 0; 4071 int step; 4072 int dir; 4073 int nonAccelMovement; 4074 4075 void reset(int _step) { 4076 position = 0; 4077 acceleration = 1; 4078 lastMoveTime = 0; 4079 step = _step; 4080 dir = 0; 4081 } 4082 4083 /** 4084 * Add trackball movement into the state. If the direction of movement 4085 * has been reversed, the state is reset before adding the 4086 * movement (so that you don't have to compensate for any previously 4087 * collected movement before see the result of the movement in the 4088 * new direction). 4089 * 4090 * @return Returns the absolute value of the amount of movement 4091 * collected so far. 4092 */ 4093 float collect(float off, long time, String axis) { 4094 long normTime; 4095 if (off > 0) { 4096 normTime = (long)(off * FAST_MOVE_TIME); 4097 if (dir < 0) { 4098 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4099 position = 0; 4100 step = 0; 4101 acceleration = 1; 4102 lastMoveTime = 0; 4103 } 4104 dir = 1; 4105 } else if (off < 0) { 4106 normTime = (long)((-off) * FAST_MOVE_TIME); 4107 if (dir > 0) { 4108 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4109 position = 0; 4110 step = 0; 4111 acceleration = 1; 4112 lastMoveTime = 0; 4113 } 4114 dir = -1; 4115 } else { 4116 normTime = 0; 4117 } 4118 4119 // The number of milliseconds between each movement that is 4120 // considered "normal" and will not result in any acceleration 4121 // or deceleration, scaled by the offset we have here. 4122 if (normTime > 0) { 4123 long delta = time - lastMoveTime; 4124 lastMoveTime = time; 4125 float acc = acceleration; 4126 if (delta < normTime) { 4127 // The user is scrolling rapidly, so increase acceleration. 4128 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4129 if (scale > 1) acc *= scale; 4130 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4131 + off + " normTime=" + normTime + " delta=" + delta 4132 + " scale=" + scale + " acc=" + acc); 4133 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4134 } else { 4135 // The user is scrolling slowly, so decrease acceleration. 4136 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4137 if (scale > 1) acc /= scale; 4138 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4139 + off + " normTime=" + normTime + " delta=" + delta 4140 + " scale=" + scale + " acc=" + acc); 4141 acceleration = acc > 1 ? acc : 1; 4142 } 4143 } 4144 position += off; 4145 return Math.abs(position); 4146 } 4147 4148 /** 4149 * Generate the number of discrete movement events appropriate for 4150 * the currently collected trackball movement. 4151 * 4152 * @return Returns the number of discrete movements, either positive 4153 * or negative, or 0 if there is not enough trackball movement yet 4154 * for a discrete movement. 4155 */ 4156 int generate() { 4157 int movement = 0; 4158 nonAccelMovement = 0; 4159 do { 4160 final int dir = position >= 0 ? 1 : -1; 4161 switch (step) { 4162 // If we are going to execute the first step, then we want 4163 // to do this as soon as possible instead of waiting for 4164 // a full movement, in order to make things look responsive. 4165 case 0: 4166 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) { 4167 return movement; 4168 } 4169 movement += dir; 4170 nonAccelMovement += dir; 4171 step = 1; 4172 break; 4173 // If we have generated the first movement, then we need 4174 // to wait for the second complete trackball motion before 4175 // generating the second discrete movement. 4176 case 1: 4177 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) { 4178 return movement; 4179 } 4180 movement += dir; 4181 nonAccelMovement += dir; 4182 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir; 4183 step = 2; 4184 break; 4185 // After the first two, we generate discrete movements 4186 // consistently with the trackball, applying an acceleration 4187 // if the trackball is moving quickly. This is a simple 4188 // acceleration on top of what we already compute based 4189 // on how quickly the wheel is being turned, to apply 4190 // a longer increasing acceleration to continuous movement 4191 // in one direction. 4192 default: 4193 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) { 4194 return movement; 4195 } 4196 movement += dir; 4197 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD; 4198 float acc = acceleration; 4199 acc *= 1.1f; 4200 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4201 break; 4202 } 4203 } while (true); 4204 } 4205 } 4206 4207 /** 4208 * Creates dpad events from unhandled joystick movements. 4209 */ 4210 final class SyntheticJoystickHandler extends Handler { 4211 private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1; 4212 private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2; 4213 4214 private int mLastXDirection; 4215 private int mLastYDirection; 4216 private int mLastXKeyCode; 4217 private int mLastYKeyCode; 4218 4219 public SyntheticJoystickHandler() { 4220 super(true); 4221 } 4222 4223 @Override 4224 public void handleMessage(Message msg) { 4225 switch (msg.what) { 4226 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT: 4227 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: { 4228 KeyEvent oldEvent = (KeyEvent)msg.obj; 4229 KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent, 4230 SystemClock.uptimeMillis(), 4231 oldEvent.getRepeatCount() + 1); 4232 if (mAttachInfo.mHasWindowFocus) { 4233 enqueueInputEvent(e); 4234 Message m = obtainMessage(msg.what, e); 4235 m.setAsynchronous(true); 4236 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay()); 4237 } 4238 } break; 4239 } 4240 } 4241 4242 public void process(MotionEvent event) { 4243 update(event, true); 4244 } 4245 4246 public void cancel(MotionEvent event) { 4247 update(event, false); 4248 } 4249 4250 private void update(MotionEvent event, boolean synthesizeNewKeys) { 4251 final long time = event.getEventTime(); 4252 final int metaState = event.getMetaState(); 4253 final int deviceId = event.getDeviceId(); 4254 final int source = event.getSource(); 4255 4256 int xDirection = joystickAxisValueToDirection( 4257 event.getAxisValue(MotionEvent.AXIS_HAT_X)); 4258 if (xDirection == 0) { 4259 xDirection = joystickAxisValueToDirection(event.getX()); 4260 } 4261 4262 int yDirection = joystickAxisValueToDirection( 4263 event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 4264 if (yDirection == 0) { 4265 yDirection = joystickAxisValueToDirection(event.getY()); 4266 } 4267 4268 if (xDirection != mLastXDirection) { 4269 if (mLastXKeyCode != 0) { 4270 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); 4271 enqueueInputEvent(new KeyEvent(time, time, 4272 KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState, 4273 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4274 mLastXKeyCode = 0; 4275 } 4276 4277 mLastXDirection = xDirection; 4278 4279 if (xDirection != 0 && synthesizeNewKeys) { 4280 mLastXKeyCode = xDirection > 0 4281 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 4282 final KeyEvent e = new KeyEvent(time, time, 4283 KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState, 4284 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4285 enqueueInputEvent(e); 4286 Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e); 4287 m.setAsynchronous(true); 4288 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4289 } 4290 } 4291 4292 if (yDirection != mLastYDirection) { 4293 if (mLastYKeyCode != 0) { 4294 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); 4295 enqueueInputEvent(new KeyEvent(time, time, 4296 KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState, 4297 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 4298 mLastYKeyCode = 0; 4299 } 4300 4301 mLastYDirection = yDirection; 4302 4303 if (yDirection != 0 && synthesizeNewKeys) { 4304 mLastYKeyCode = yDirection > 0 4305 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 4306 final KeyEvent e = new KeyEvent(time, time, 4307 KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState, 4308 deviceId, 0, KeyEvent.FLAG_FALLBACK, source); 4309 enqueueInputEvent(e); 4310 Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e); 4311 m.setAsynchronous(true); 4312 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); 4313 } 4314 } 4315 } 4316 4317 private int joystickAxisValueToDirection(float value) { 4318 if (value >= 0.5f) { 4319 return 1; 4320 } else if (value <= -0.5f) { 4321 return -1; 4322 } else { 4323 return 0; 4324 } 4325 } 4326 } 4327 4328 /** 4329 * Creates dpad events from unhandled touch navigation movements. 4330 */ 4331 final class SyntheticTouchNavigationHandler extends Handler { 4332 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler"; 4333 private static final boolean LOCAL_DEBUG = false; 4334 4335 // Assumed nominal width and height in millimeters of a touch navigation pad, 4336 // if no resolution information is available from the input system. 4337 private static final float DEFAULT_WIDTH_MILLIMETERS = 48; 4338 private static final float DEFAULT_HEIGHT_MILLIMETERS = 48; 4339 4340 /* TODO: These constants should eventually be moved to ViewConfiguration. */ 4341 4342 // Tap timeout in milliseconds. 4343 private static final int TAP_TIMEOUT = 250; 4344 4345 // The maximum distance traveled for a gesture to be considered a tap in millimeters. 4346 private static final int TAP_SLOP_MILLIMETERS = 5; 4347 4348 // The nominal distance traveled to move by one unit. 4349 private static final int TICK_DISTANCE_MILLIMETERS = 12; 4350 4351 // Minimum and maximum fling velocity in ticks per second. 4352 // The minimum velocity should be set such that we perform enough ticks per 4353 // second that the fling appears to be fluid. For example, if we set the minimum 4354 // to 2 ticks per second, then there may be up to half a second delay between the next 4355 // to last and last ticks which is noticeably discrete and jerky. This value should 4356 // probably not be set to anything less than about 4. 4357 // If fling accuracy is a problem then consider tuning the tick distance instead. 4358 private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f; 4359 private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f; 4360 4361 // Fling velocity decay factor applied after each new key is emitted. 4362 // This parameter controls the deceleration and overall duration of the fling. 4363 // The fling stops automatically when its velocity drops below the minimum 4364 // fling velocity defined above. 4365 private static final float FLING_TICK_DECAY = 0.8f; 4366 4367 /* The input device that we are tracking. */ 4368 4369 private int mCurrentDeviceId = -1; 4370 private int mCurrentSource; 4371 private boolean mCurrentDeviceSupported; 4372 4373 /* Configuration for the current input device. */ 4374 4375 // The tap timeout and scaled slop. 4376 private int mConfigTapTimeout; 4377 private float mConfigTapSlop; 4378 4379 // The scaled tick distance. A movement of this amount should generally translate 4380 // into a single dpad event in a given direction. 4381 private float mConfigTickDistance; 4382 4383 // The minimum and maximum scaled fling velocity. 4384 private float mConfigMinFlingVelocity; 4385 private float mConfigMaxFlingVelocity; 4386 4387 /* Tracking state. */ 4388 4389 // The velocity tracker for detecting flings. 4390 private VelocityTracker mVelocityTracker; 4391 4392 // The active pointer id, or -1 if none. 4393 private int mActivePointerId = -1; 4394 4395 // Time and location where tracking started. 4396 private long mStartTime; 4397 private float mStartX; 4398 private float mStartY; 4399 4400 // Most recently observed position. 4401 private float mLastX; 4402 private float mLastY; 4403 4404 // Accumulated movement delta since the last direction key was sent. 4405 private float mAccumulatedX; 4406 private float mAccumulatedY; 4407 4408 // Set to true if any movement was delivered to the app. 4409 // Implies that tap slop was exceeded. 4410 private boolean mConsumedMovement; 4411 4412 // The most recently sent key down event. 4413 // The keycode remains set until the direction changes or a fling ends 4414 // so that repeated key events may be generated as required. 4415 private long mPendingKeyDownTime; 4416 private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4417 private int mPendingKeyRepeatCount; 4418 private int mPendingKeyMetaState; 4419 4420 // The current fling velocity while a fling is in progress. 4421 private boolean mFlinging; 4422 private float mFlingVelocity; 4423 4424 public SyntheticTouchNavigationHandler() { 4425 super(true); 4426 } 4427 4428 public void process(MotionEvent event) { 4429 // Update the current device information. 4430 final long time = event.getEventTime(); 4431 final int deviceId = event.getDeviceId(); 4432 final int source = event.getSource(); 4433 if (mCurrentDeviceId != deviceId || mCurrentSource != source) { 4434 finishKeys(time); 4435 finishTracking(time); 4436 mCurrentDeviceId = deviceId; 4437 mCurrentSource = source; 4438 mCurrentDeviceSupported = false; 4439 InputDevice device = event.getDevice(); 4440 if (device != null) { 4441 // In order to support an input device, we must know certain 4442 // characteristics about it, such as its size and resolution. 4443 InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X); 4444 InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y); 4445 if (xRange != null && yRange != null) { 4446 mCurrentDeviceSupported = true; 4447 4448 // Infer the resolution if it not actually known. 4449 float xRes = xRange.getResolution(); 4450 if (xRes <= 0) { 4451 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS; 4452 } 4453 float yRes = yRange.getResolution(); 4454 if (yRes <= 0) { 4455 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS; 4456 } 4457 float nominalRes = (xRes + yRes) * 0.5f; 4458 4459 // Precompute all of the configuration thresholds we will need. 4460 mConfigTapTimeout = TAP_TIMEOUT; 4461 mConfigTapSlop = TAP_SLOP_MILLIMETERS * nominalRes; 4462 mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes; 4463 mConfigMinFlingVelocity = 4464 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4465 mConfigMaxFlingVelocity = 4466 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance; 4467 4468 if (LOCAL_DEBUG) { 4469 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId 4470 + " (" + Integer.toHexString(mCurrentSource) + "): " 4471 + "mConfigTapTimeout=" + mConfigTapTimeout 4472 + ", mConfigTapSlop=" + mConfigTapSlop 4473 + ", mConfigTickDistance=" + mConfigTickDistance 4474 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity 4475 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity); 4476 } 4477 } 4478 } 4479 } 4480 if (!mCurrentDeviceSupported) { 4481 return; 4482 } 4483 4484 // Handle the event. 4485 final int action = event.getActionMasked(); 4486 switch (action) { 4487 case MotionEvent.ACTION_DOWN: { 4488 boolean caughtFling = mFlinging; 4489 finishKeys(time); 4490 finishTracking(time); 4491 mActivePointerId = event.getPointerId(0); 4492 mVelocityTracker = VelocityTracker.obtain(); 4493 mVelocityTracker.addMovement(event); 4494 mStartTime = time; 4495 mStartX = event.getX(); 4496 mStartY = event.getY(); 4497 mLastX = mStartX; 4498 mLastY = mStartY; 4499 mAccumulatedX = 0; 4500 mAccumulatedY = 0; 4501 4502 // If we caught a fling, then pretend that the tap slop has already 4503 // been exceeded to suppress taps whose only purpose is to stop the fling. 4504 mConsumedMovement = caughtFling; 4505 break; 4506 } 4507 4508 case MotionEvent.ACTION_MOVE: 4509 case MotionEvent.ACTION_UP: { 4510 if (mActivePointerId < 0) { 4511 break; 4512 } 4513 final int index = event.findPointerIndex(mActivePointerId); 4514 if (index < 0) { 4515 finishKeys(time); 4516 finishTracking(time); 4517 break; 4518 } 4519 4520 mVelocityTracker.addMovement(event); 4521 final float x = event.getX(index); 4522 final float y = event.getY(index); 4523 mAccumulatedX += x - mLastX; 4524 mAccumulatedY += y - mLastY; 4525 mLastX = x; 4526 mLastY = y; 4527 4528 // Consume any accumulated movement so far. 4529 final int metaState = event.getMetaState(); 4530 consumeAccumulatedMovement(time, metaState); 4531 4532 // Detect taps and flings. 4533 if (action == MotionEvent.ACTION_UP) { 4534 if (!mConsumedMovement 4535 && Math.hypot(mLastX - mStartX, mLastY - mStartY) < mConfigTapSlop 4536 && time <= mStartTime + mConfigTapTimeout) { 4537 // It's a tap! 4538 finishKeys(time); 4539 sendKeyDownOrRepeat(time, KeyEvent.KEYCODE_DPAD_CENTER, metaState); 4540 sendKeyUp(time); 4541 } else if (mConsumedMovement 4542 && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4543 // It might be a fling. 4544 mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity); 4545 final float vx = mVelocityTracker.getXVelocity(mActivePointerId); 4546 final float vy = mVelocityTracker.getYVelocity(mActivePointerId); 4547 if (!startFling(time, vx, vy)) { 4548 finishKeys(time); 4549 } 4550 } 4551 finishTracking(time); 4552 } 4553 break; 4554 } 4555 4556 case MotionEvent.ACTION_CANCEL: { 4557 finishKeys(time); 4558 finishTracking(time); 4559 break; 4560 } 4561 } 4562 } 4563 4564 public void cancel(MotionEvent event) { 4565 if (mCurrentDeviceId == event.getDeviceId() 4566 && mCurrentSource == event.getSource()) { 4567 final long time = event.getEventTime(); 4568 finishKeys(time); 4569 finishTracking(time); 4570 } 4571 } 4572 4573 private void finishKeys(long time) { 4574 cancelFling(); 4575 sendKeyUp(time); 4576 } 4577 4578 private void finishTracking(long time) { 4579 if (mActivePointerId >= 0) { 4580 mActivePointerId = -1; 4581 mVelocityTracker.recycle(); 4582 mVelocityTracker = null; 4583 } 4584 } 4585 4586 private void consumeAccumulatedMovement(long time, int metaState) { 4587 final float absX = Math.abs(mAccumulatedX); 4588 final float absY = Math.abs(mAccumulatedY); 4589 if (absX >= absY) { 4590 if (absX >= mConfigTickDistance) { 4591 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX, 4592 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT); 4593 mAccumulatedY = 0; 4594 mConsumedMovement = true; 4595 } 4596 } else { 4597 if (absY >= mConfigTickDistance) { 4598 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY, 4599 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN); 4600 mAccumulatedX = 0; 4601 mConsumedMovement = true; 4602 } 4603 } 4604 } 4605 4606 private float consumeAccumulatedMovement(long time, int metaState, 4607 float accumulator, int negativeKeyCode, int positiveKeyCode) { 4608 while (accumulator <= -mConfigTickDistance) { 4609 sendKeyDownOrRepeat(time, negativeKeyCode, metaState); 4610 accumulator += mConfigTickDistance; 4611 } 4612 while (accumulator >= mConfigTickDistance) { 4613 sendKeyDownOrRepeat(time, positiveKeyCode, metaState); 4614 accumulator -= mConfigTickDistance; 4615 } 4616 return accumulator; 4617 } 4618 4619 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) { 4620 if (mPendingKeyCode != keyCode) { 4621 sendKeyUp(time); 4622 mPendingKeyDownTime = time; 4623 mPendingKeyCode = keyCode; 4624 mPendingKeyRepeatCount = 0; 4625 } else { 4626 mPendingKeyRepeatCount += 1; 4627 } 4628 mPendingKeyMetaState = metaState; 4629 4630 // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1 4631 // but it doesn't quite make sense when simulating the events in this way. 4632 if (LOCAL_DEBUG) { 4633 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode 4634 + ", repeatCount=" + mPendingKeyRepeatCount 4635 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4636 } 4637 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4638 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount, 4639 mPendingKeyMetaState, mCurrentDeviceId, 4640 KeyEvent.FLAG_FALLBACK, mCurrentSource)); 4641 } 4642 4643 private void sendKeyUp(long time) { 4644 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) { 4645 if (LOCAL_DEBUG) { 4646 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode 4647 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState)); 4648 } 4649 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time, 4650 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState, 4651 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK, 4652 mCurrentSource)); 4653 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN; 4654 } 4655 } 4656 4657 private boolean startFling(long time, float vx, float vy) { 4658 if (LOCAL_DEBUG) { 4659 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy 4660 + ", min=" + mConfigMinFlingVelocity); 4661 } 4662 4663 // Flings must be oriented in the same direction as the preceding movements. 4664 switch (mPendingKeyCode) { 4665 case KeyEvent.KEYCODE_DPAD_LEFT: 4666 if (-vx >= mConfigMinFlingVelocity 4667 && Math.abs(vy) < mConfigMinFlingVelocity) { 4668 mFlingVelocity = -vx; 4669 break; 4670 } 4671 return false; 4672 4673 case KeyEvent.KEYCODE_DPAD_RIGHT: 4674 if (vx >= mConfigMinFlingVelocity 4675 && Math.abs(vy) < mConfigMinFlingVelocity) { 4676 mFlingVelocity = vx; 4677 break; 4678 } 4679 return false; 4680 4681 case KeyEvent.KEYCODE_DPAD_UP: 4682 if (-vy >= mConfigMinFlingVelocity 4683 && Math.abs(vx) < mConfigMinFlingVelocity) { 4684 mFlingVelocity = -vy; 4685 break; 4686 } 4687 return false; 4688 4689 case KeyEvent.KEYCODE_DPAD_DOWN: 4690 if (vy >= mConfigMinFlingVelocity 4691 && Math.abs(vx) < mConfigMinFlingVelocity) { 4692 mFlingVelocity = vy; 4693 break; 4694 } 4695 return false; 4696 } 4697 4698 // Post the first fling event. 4699 mFlinging = postFling(time); 4700 return mFlinging; 4701 } 4702 4703 private boolean postFling(long time) { 4704 // The idea here is to estimate the time when the pointer would have 4705 // traveled one tick distance unit given the current fling velocity. 4706 // This effect creates continuity of motion. 4707 if (mFlingVelocity >= mConfigMinFlingVelocity) { 4708 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000); 4709 postAtTime(mFlingRunnable, time + delay); 4710 if (LOCAL_DEBUG) { 4711 Log.d(LOCAL_TAG, "Posted fling: velocity=" 4712 + mFlingVelocity + ", delay=" + delay 4713 + ", keyCode=" + mPendingKeyCode); 4714 } 4715 return true; 4716 } 4717 return false; 4718 } 4719 4720 private void cancelFling() { 4721 if (mFlinging) { 4722 removeCallbacks(mFlingRunnable); 4723 mFlinging = false; 4724 } 4725 } 4726 4727 private final Runnable mFlingRunnable = new Runnable() { 4728 @Override 4729 public void run() { 4730 final long time = SystemClock.uptimeMillis(); 4731 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState); 4732 mFlingVelocity *= FLING_TICK_DECAY; 4733 if (!postFling(time)) { 4734 mFlinging = false; 4735 finishKeys(time); 4736 } 4737 } 4738 }; 4739 } 4740 4741 /** 4742 * Returns true if the key is used for keyboard navigation. 4743 * @param keyEvent The key event. 4744 * @return True if the key is used for keyboard navigation. 4745 */ 4746 private static boolean isNavigationKey(KeyEvent keyEvent) { 4747 switch (keyEvent.getKeyCode()) { 4748 case KeyEvent.KEYCODE_DPAD_LEFT: 4749 case KeyEvent.KEYCODE_DPAD_RIGHT: 4750 case KeyEvent.KEYCODE_DPAD_UP: 4751 case KeyEvent.KEYCODE_DPAD_DOWN: 4752 case KeyEvent.KEYCODE_DPAD_CENTER: 4753 case KeyEvent.KEYCODE_PAGE_UP: 4754 case KeyEvent.KEYCODE_PAGE_DOWN: 4755 case KeyEvent.KEYCODE_MOVE_HOME: 4756 case KeyEvent.KEYCODE_MOVE_END: 4757 case KeyEvent.KEYCODE_TAB: 4758 case KeyEvent.KEYCODE_SPACE: 4759 case KeyEvent.KEYCODE_ENTER: 4760 return true; 4761 } 4762 return false; 4763 } 4764 4765 /** 4766 * Returns true if the key is used for typing. 4767 * @param keyEvent The key event. 4768 * @return True if the key is used for typing. 4769 */ 4770 private static boolean isTypingKey(KeyEvent keyEvent) { 4771 return keyEvent.getUnicodeChar() > 0; 4772 } 4773 4774 /** 4775 * See if the key event means we should leave touch mode (and leave touch mode if so). 4776 * @param event The key event. 4777 * @return Whether this key event should be consumed (meaning the act of 4778 * leaving touch mode alone is considered the event). 4779 */ 4780 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 4781 // Only relevant in touch mode. 4782 if (!mAttachInfo.mInTouchMode) { 4783 return false; 4784 } 4785 4786 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 4787 final int action = event.getAction(); 4788 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 4789 return false; 4790 } 4791 4792 // Don't leave touch mode if the IME told us not to. 4793 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 4794 return false; 4795 } 4796 4797 // If the key can be used for keyboard navigation then leave touch mode 4798 // and select a focused view if needed (in ensureTouchMode). 4799 // When a new focused view is selected, we consume the navigation key because 4800 // navigation doesn't make much sense unless a view already has focus so 4801 // the key's purpose is to set focus. 4802 if (isNavigationKey(event)) { 4803 return ensureTouchMode(false); 4804 } 4805 4806 // If the key can be used for typing then leave touch mode 4807 // and select a focused view if needed (in ensureTouchMode). 4808 // Always allow the view to process the typing key. 4809 if (isTypingKey(event)) { 4810 ensureTouchMode(false); 4811 return false; 4812 } 4813 4814 return false; 4815 } 4816 4817 /* drag/drop */ 4818 void setLocalDragState(Object obj) { 4819 mLocalDragState = obj; 4820 } 4821 4822 private void handleDragEvent(DragEvent event) { 4823 // From the root, only drag start/end/location are dispatched. entered/exited 4824 // are determined and dispatched by the viewgroup hierarchy, who then report 4825 // that back here for ultimate reporting back to the framework. 4826 if (mView != null && mAdded) { 4827 final int what = event.mAction; 4828 4829 if (what == DragEvent.ACTION_DRAG_EXITED) { 4830 // A direct EXITED event means that the window manager knows we've just crossed 4831 // a window boundary, so the current drag target within this one must have 4832 // just been exited. Send it the usual notifications and then we're done 4833 // for now. 4834 mView.dispatchDragEvent(event); 4835 } else { 4836 // Cache the drag description when the operation starts, then fill it in 4837 // on subsequent calls as a convenience 4838 if (what == DragEvent.ACTION_DRAG_STARTED) { 4839 mCurrentDragView = null; // Start the current-recipient tracking 4840 mDragDescription = event.mClipDescription; 4841 } else { 4842 event.mClipDescription = mDragDescription; 4843 } 4844 4845 // For events with a [screen] location, translate into window coordinates 4846 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 4847 mDragPoint.set(event.mX, event.mY); 4848 if (mTranslator != null) { 4849 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 4850 } 4851 4852 if (mCurScrollY != 0) { 4853 mDragPoint.offset(0, mCurScrollY); 4854 } 4855 4856 event.mX = mDragPoint.x; 4857 event.mY = mDragPoint.y; 4858 } 4859 4860 // Remember who the current drag target is pre-dispatch 4861 final View prevDragView = mCurrentDragView; 4862 4863 // Now dispatch the drag/drop event 4864 boolean result = mView.dispatchDragEvent(event); 4865 4866 // If we changed apparent drag target, tell the OS about it 4867 if (prevDragView != mCurrentDragView) { 4868 try { 4869 if (prevDragView != null) { 4870 mWindowSession.dragRecipientExited(mWindow); 4871 } 4872 if (mCurrentDragView != null) { 4873 mWindowSession.dragRecipientEntered(mWindow); 4874 } 4875 } catch (RemoteException e) { 4876 Slog.e(TAG, "Unable to note drag target change"); 4877 } 4878 } 4879 4880 // Report the drop result when we're done 4881 if (what == DragEvent.ACTION_DROP) { 4882 mDragDescription = null; 4883 try { 4884 Log.i(TAG, "Reporting drop result: " + result); 4885 mWindowSession.reportDropResult(mWindow, result); 4886 } catch (RemoteException e) { 4887 Log.e(TAG, "Unable to report drop result"); 4888 } 4889 } 4890 4891 // When the drag operation ends, release any local state object 4892 // that may have been in use 4893 if (what == DragEvent.ACTION_DRAG_ENDED) { 4894 setLocalDragState(null); 4895 } 4896 } 4897 } 4898 event.recycle(); 4899 } 4900 4901 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 4902 if (mSeq != args.seq) { 4903 // The sequence has changed, so we need to update our value and make 4904 // sure to do a traversal afterward so the window manager is given our 4905 // most recent data. 4906 mSeq = args.seq; 4907 mAttachInfo.mForceReportNewAttributes = true; 4908 scheduleTraversals(); 4909 } 4910 if (mView == null) return; 4911 if (args.localChanges != 0) { 4912 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 4913 } 4914 if (mAttachInfo != null) { 4915 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 4916 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 4917 mAttachInfo.mGlobalSystemUiVisibility = visibility; 4918 mView.dispatchSystemUiVisibilityChanged(visibility); 4919 } 4920 } 4921 } 4922 4923 public void handleDispatchDoneAnimating() { 4924 if (mWindowsAnimating) { 4925 mWindowsAnimating = false; 4926 if (!mDirty.isEmpty() || mIsAnimating || mFullRedrawNeeded) { 4927 scheduleTraversals(); 4928 } 4929 } 4930 } 4931 4932 public void getLastTouchPoint(Point outLocation) { 4933 outLocation.x = (int) mLastTouchPoint.x; 4934 outLocation.y = (int) mLastTouchPoint.y; 4935 } 4936 4937 public void setDragFocus(View newDragTarget) { 4938 if (mCurrentDragView != newDragTarget) { 4939 mCurrentDragView = newDragTarget; 4940 } 4941 } 4942 4943 private AudioManager getAudioManager() { 4944 if (mView == null) { 4945 throw new IllegalStateException("getAudioManager called when there is no mView"); 4946 } 4947 if (mAudioManager == null) { 4948 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 4949 } 4950 return mAudioManager; 4951 } 4952 4953 public AccessibilityInteractionController getAccessibilityInteractionController() { 4954 if (mView == null) { 4955 throw new IllegalStateException("getAccessibilityInteractionController" 4956 + " called when there is no mView"); 4957 } 4958 if (mAccessibilityInteractionController == null) { 4959 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 4960 } 4961 return mAccessibilityInteractionController; 4962 } 4963 4964 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 4965 boolean insetsPending) throws RemoteException { 4966 4967 float appScale = mAttachInfo.mApplicationScale; 4968 boolean restore = false; 4969 if (params != null && mTranslator != null) { 4970 restore = true; 4971 params.backup(); 4972 mTranslator.translateWindowLayout(params); 4973 } 4974 if (params != null) { 4975 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 4976 } 4977 mPendingConfiguration.seq = 0; 4978 //Log.d(TAG, ">>>>>> CALLING relayout"); 4979 if (params != null && mOrigWindowType != params.type) { 4980 // For compatibility with old apps, don't crash here. 4981 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 4982 Slog.w(TAG, "Window type can not be changed after " 4983 + "the window is added; ignoring change of " + mView); 4984 params.type = mOrigWindowType; 4985 } 4986 } 4987 int relayoutResult = mWindowSession.relayout( 4988 mWindow, mSeq, params, 4989 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 4990 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 4991 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 4992 mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets, 4993 mPendingConfiguration, mSurface); 4994 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 4995 if (restore) { 4996 params.restore(); 4997 } 4998 4999 if (mTranslator != null) { 5000 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 5001 mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets); 5002 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 5003 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 5004 } 5005 return relayoutResult; 5006 } 5007 5008 /** 5009 * {@inheritDoc} 5010 */ 5011 public void playSoundEffect(int effectId) { 5012 checkThread(); 5013 5014 try { 5015 final AudioManager audioManager = getAudioManager(); 5016 5017 switch (effectId) { 5018 case SoundEffectConstants.CLICK: 5019 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 5020 return; 5021 case SoundEffectConstants.NAVIGATION_DOWN: 5022 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 5023 return; 5024 case SoundEffectConstants.NAVIGATION_LEFT: 5025 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 5026 return; 5027 case SoundEffectConstants.NAVIGATION_RIGHT: 5028 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 5029 return; 5030 case SoundEffectConstants.NAVIGATION_UP: 5031 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 5032 return; 5033 default: 5034 throw new IllegalArgumentException("unknown effect id " + effectId + 5035 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 5036 } 5037 } catch (IllegalStateException e) { 5038 // Exception thrown by getAudioManager() when mView is null 5039 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 5040 e.printStackTrace(); 5041 } 5042 } 5043 5044 /** 5045 * {@inheritDoc} 5046 */ 5047 public boolean performHapticFeedback(int effectId, boolean always) { 5048 try { 5049 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 5050 } catch (RemoteException e) { 5051 return false; 5052 } 5053 } 5054 5055 /** 5056 * {@inheritDoc} 5057 */ 5058 public View focusSearch(View focused, int direction) { 5059 checkThread(); 5060 if (!(mView instanceof ViewGroup)) { 5061 return null; 5062 } 5063 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 5064 } 5065 5066 public void debug() { 5067 mView.debug(); 5068 } 5069 5070 public void dumpGfxInfo(int[] info) { 5071 info[0] = info[1] = 0; 5072 if (mView != null) { 5073 getGfxInfo(mView, info); 5074 } 5075 } 5076 5077 private static void getGfxInfo(View view, int[] info) { 5078 DisplayList displayList = view.mDisplayList; 5079 info[0]++; 5080 if (displayList != null) { 5081 info[1] += displayList.getSize(); 5082 } 5083 5084 if (view instanceof ViewGroup) { 5085 ViewGroup group = (ViewGroup) view; 5086 5087 int count = group.getChildCount(); 5088 for (int i = 0; i < count; i++) { 5089 getGfxInfo(group.getChildAt(i), info); 5090 } 5091 } 5092 } 5093 5094 public void die(boolean immediate) { 5095 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 5096 // done by dispatchDetachedFromWindow will cause havoc on return. 5097 if (immediate && !mIsInTraversal) { 5098 doDie(); 5099 } else { 5100 if (!mIsDrawing) { 5101 destroyHardwareRenderer(); 5102 } else { 5103 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 5104 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 5105 } 5106 mHandler.sendEmptyMessage(MSG_DIE); 5107 } 5108 } 5109 5110 void doDie() { 5111 checkThread(); 5112 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 5113 synchronized (this) { 5114 if (mAdded) { 5115 dispatchDetachedFromWindow(); 5116 } 5117 5118 if (mAdded && !mFirst) { 5119 invalidateDisplayLists(); 5120 destroyHardwareRenderer(); 5121 5122 if (mView != null) { 5123 int viewVisibility = mView.getVisibility(); 5124 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 5125 if (mWindowAttributesChanged || viewVisibilityChanged) { 5126 // If layout params have been changed, first give them 5127 // to the window manager to make sure it has the correct 5128 // animation info. 5129 try { 5130 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 5131 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 5132 mWindowSession.finishDrawing(mWindow); 5133 } 5134 } catch (RemoteException e) { 5135 } 5136 } 5137 5138 mSurface.release(); 5139 } 5140 } 5141 5142 mAdded = false; 5143 } 5144 } 5145 5146 public void requestUpdateConfiguration(Configuration config) { 5147 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 5148 mHandler.sendMessage(msg); 5149 } 5150 5151 public void loadSystemProperties() { 5152 mHandler.post(new Runnable() { 5153 @Override 5154 public void run() { 5155 // Profiling 5156 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false); 5157 profileRendering(mAttachInfo.mHasWindowFocus); 5158 5159 // Hardware rendering 5160 if (mAttachInfo.mHardwareRenderer != null) { 5161 if (mAttachInfo.mHardwareRenderer.loadSystemProperties(mHolder.getSurface())) { 5162 invalidate(); 5163 } 5164 } 5165 5166 // Layout debugging 5167 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false); 5168 if (layout != mAttachInfo.mDebugLayout) { 5169 mAttachInfo.mDebugLayout = layout; 5170 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 5171 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 5172 } 5173 } 5174 } 5175 }); 5176 } 5177 5178 private void destroyHardwareRenderer() { 5179 AttachInfo attachInfo = mAttachInfo; 5180 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 5181 5182 if (hardwareRenderer != null) { 5183 if (mView != null) { 5184 hardwareRenderer.destroyHardwareResources(mView); 5185 } 5186 hardwareRenderer.destroy(true); 5187 hardwareRenderer.setRequested(false); 5188 5189 attachInfo.mHardwareRenderer = null; 5190 attachInfo.mHardwareAccelerated = false; 5191 } 5192 } 5193 5194 public void dispatchFinishInputConnection(InputConnection connection) { 5195 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 5196 mHandler.sendMessage(msg); 5197 } 5198 5199 public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets, 5200 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 5201 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 5202 + " contentInsets=" + contentInsets.toShortString() 5203 + " visibleInsets=" + visibleInsets.toShortString() 5204 + " reportDraw=" + reportDraw); 5205 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 5206 if (mTranslator != null) { 5207 mTranslator.translateRectInScreenToAppWindow(frame); 5208 mTranslator.translateRectInScreenToAppWindow(overscanInsets); 5209 mTranslator.translateRectInScreenToAppWindow(contentInsets); 5210 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 5211 } 5212 SomeArgs args = SomeArgs.obtain(); 5213 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 5214 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 5215 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 5216 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 5217 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 5218 args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets; 5219 msg.obj = args; 5220 mHandler.sendMessage(msg); 5221 } 5222 5223 public void dispatchMoved(int newX, int newY) { 5224 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 5225 if (mTranslator != null) { 5226 PointF point = new PointF(newX, newY); 5227 mTranslator.translatePointInScreenToAppWindow(point); 5228 newX = (int) (point.x + 0.5); 5229 newY = (int) (point.y + 0.5); 5230 } 5231 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 5232 mHandler.sendMessage(msg); 5233 } 5234 5235 /** 5236 * Represents a pending input event that is waiting in a queue. 5237 * 5238 * Input events are processed in serial order by the timestamp specified by 5239 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 5240 * one input event to the application at a time and waits for the application 5241 * to finish handling it before delivering the next one. 5242 * 5243 * However, because the application or IME can synthesize and inject multiple 5244 * key events at a time without going through the input dispatcher, we end up 5245 * needing a queue on the application's side. 5246 */ 5247 private static final class QueuedInputEvent { 5248 public static final int FLAG_DELIVER_POST_IME = 1 << 0; 5249 public static final int FLAG_DEFERRED = 1 << 1; 5250 public static final int FLAG_FINISHED = 1 << 2; 5251 public static final int FLAG_FINISHED_HANDLED = 1 << 3; 5252 public static final int FLAG_RESYNTHESIZED = 1 << 4; 5253 5254 public QueuedInputEvent mNext; 5255 5256 public InputEvent mEvent; 5257 public InputEventReceiver mReceiver; 5258 public int mFlags; 5259 5260 public boolean shouldSkipIme() { 5261 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) { 5262 return true; 5263 } 5264 return mEvent instanceof MotionEvent 5265 && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER); 5266 } 5267 } 5268 5269 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 5270 InputEventReceiver receiver, int flags) { 5271 QueuedInputEvent q = mQueuedInputEventPool; 5272 if (q != null) { 5273 mQueuedInputEventPoolSize -= 1; 5274 mQueuedInputEventPool = q.mNext; 5275 q.mNext = null; 5276 } else { 5277 q = new QueuedInputEvent(); 5278 } 5279 5280 q.mEvent = event; 5281 q.mReceiver = receiver; 5282 q.mFlags = flags; 5283 return q; 5284 } 5285 5286 private void recycleQueuedInputEvent(QueuedInputEvent q) { 5287 q.mEvent = null; 5288 q.mReceiver = null; 5289 5290 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 5291 mQueuedInputEventPoolSize += 1; 5292 q.mNext = mQueuedInputEventPool; 5293 mQueuedInputEventPool = q; 5294 } 5295 } 5296 5297 void enqueueInputEvent(InputEvent event) { 5298 enqueueInputEvent(event, null, 0, false); 5299 } 5300 5301 void enqueueInputEvent(InputEvent event, 5302 InputEventReceiver receiver, int flags, boolean processImmediately) { 5303 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 5304 5305 // Always enqueue the input event in order, regardless of its time stamp. 5306 // We do this because the application or the IME may inject key events 5307 // in response to touch events and we want to ensure that the injected keys 5308 // are processed in the order they were received and we cannot trust that 5309 // the time stamp of injected events are monotonic. 5310 QueuedInputEvent last = mPendingInputEventTail; 5311 if (last == null) { 5312 mPendingInputEventHead = q; 5313 mPendingInputEventTail = q; 5314 } else { 5315 last.mNext = q; 5316 mPendingInputEventTail = q; 5317 } 5318 mPendingInputEventCount += 1; 5319 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5320 mPendingInputEventCount); 5321 5322 if (processImmediately) { 5323 doProcessInputEvents(); 5324 } else { 5325 scheduleProcessInputEvents(); 5326 } 5327 } 5328 5329 private void scheduleProcessInputEvents() { 5330 if (!mProcessInputEventsScheduled) { 5331 mProcessInputEventsScheduled = true; 5332 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 5333 msg.setAsynchronous(true); 5334 mHandler.sendMessage(msg); 5335 } 5336 } 5337 5338 void doProcessInputEvents() { 5339 // Deliver all pending input events in the queue. 5340 while (mPendingInputEventHead != null) { 5341 QueuedInputEvent q = mPendingInputEventHead; 5342 mPendingInputEventHead = q.mNext; 5343 if (mPendingInputEventHead == null) { 5344 mPendingInputEventTail = null; 5345 } 5346 q.mNext = null; 5347 5348 mPendingInputEventCount -= 1; 5349 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName, 5350 mPendingInputEventCount); 5351 5352 deliverInputEvent(q); 5353 } 5354 5355 // We are done processing all input events that we can process right now 5356 // so we can clear the pending flag immediately. 5357 if (mProcessInputEventsScheduled) { 5358 mProcessInputEventsScheduled = false; 5359 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 5360 } 5361 } 5362 5363 private void deliverInputEvent(QueuedInputEvent q) { 5364 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent"); 5365 try { 5366 if (mInputEventConsistencyVerifier != null) { 5367 mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0); 5368 } 5369 5370 InputStage stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage; 5371 if (stage != null) { 5372 stage.deliver(q); 5373 } else { 5374 finishInputEvent(q); 5375 } 5376 } finally { 5377 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 5378 } 5379 } 5380 5381 private void finishInputEvent(QueuedInputEvent q) { 5382 if (q.mReceiver != null) { 5383 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0; 5384 q.mReceiver.finishInputEvent(q.mEvent, handled); 5385 } else { 5386 q.mEvent.recycleIfNeededAfterDispatch(); 5387 } 5388 5389 recycleQueuedInputEvent(q); 5390 } 5391 5392 static boolean isTerminalInputEvent(InputEvent event) { 5393 if (event instanceof KeyEvent) { 5394 final KeyEvent keyEvent = (KeyEvent)event; 5395 return keyEvent.getAction() == KeyEvent.ACTION_UP; 5396 } else { 5397 final MotionEvent motionEvent = (MotionEvent)event; 5398 final int action = motionEvent.getAction(); 5399 return action == MotionEvent.ACTION_UP 5400 || action == MotionEvent.ACTION_CANCEL 5401 || action == MotionEvent.ACTION_HOVER_EXIT; 5402 } 5403 } 5404 5405 void scheduleConsumeBatchedInput() { 5406 if (!mConsumeBatchedInputScheduled) { 5407 mConsumeBatchedInputScheduled = true; 5408 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 5409 mConsumedBatchedInputRunnable, null); 5410 } 5411 } 5412 5413 void unscheduleConsumeBatchedInput() { 5414 if (mConsumeBatchedInputScheduled) { 5415 mConsumeBatchedInputScheduled = false; 5416 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 5417 mConsumedBatchedInputRunnable, null); 5418 } 5419 } 5420 5421 void doConsumeBatchedInput(long frameTimeNanos) { 5422 if (mConsumeBatchedInputScheduled) { 5423 mConsumeBatchedInputScheduled = false; 5424 if (mInputEventReceiver != null) { 5425 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos); 5426 } 5427 doProcessInputEvents(); 5428 } 5429 } 5430 5431 final class TraversalRunnable implements Runnable { 5432 @Override 5433 public void run() { 5434 doTraversal(); 5435 } 5436 } 5437 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 5438 5439 final class WindowInputEventReceiver extends InputEventReceiver { 5440 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 5441 super(inputChannel, looper); 5442 } 5443 5444 @Override 5445 public void onInputEvent(InputEvent event) { 5446 enqueueInputEvent(event, this, 0, true); 5447 } 5448 5449 @Override 5450 public void onBatchedInputEventPending() { 5451 scheduleConsumeBatchedInput(); 5452 } 5453 5454 @Override 5455 public void dispose() { 5456 unscheduleConsumeBatchedInput(); 5457 super.dispose(); 5458 } 5459 } 5460 WindowInputEventReceiver mInputEventReceiver; 5461 5462 final class ConsumeBatchedInputRunnable implements Runnable { 5463 @Override 5464 public void run() { 5465 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 5466 } 5467 } 5468 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 5469 new ConsumeBatchedInputRunnable(); 5470 boolean mConsumeBatchedInputScheduled; 5471 5472 final class InvalidateOnAnimationRunnable implements Runnable { 5473 private boolean mPosted; 5474 private ArrayList<View> mViews = new ArrayList<View>(); 5475 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 5476 new ArrayList<AttachInfo.InvalidateInfo>(); 5477 private View[] mTempViews; 5478 private AttachInfo.InvalidateInfo[] mTempViewRects; 5479 5480 public void addView(View view) { 5481 synchronized (this) { 5482 mViews.add(view); 5483 postIfNeededLocked(); 5484 } 5485 } 5486 5487 public void addViewRect(AttachInfo.InvalidateInfo info) { 5488 synchronized (this) { 5489 mViewRects.add(info); 5490 postIfNeededLocked(); 5491 } 5492 } 5493 5494 public void removeView(View view) { 5495 synchronized (this) { 5496 mViews.remove(view); 5497 5498 for (int i = mViewRects.size(); i-- > 0; ) { 5499 AttachInfo.InvalidateInfo info = mViewRects.get(i); 5500 if (info.target == view) { 5501 mViewRects.remove(i); 5502 info.recycle(); 5503 } 5504 } 5505 5506 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 5507 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 5508 mPosted = false; 5509 } 5510 } 5511 } 5512 5513 @Override 5514 public void run() { 5515 final int viewCount; 5516 final int viewRectCount; 5517 synchronized (this) { 5518 mPosted = false; 5519 5520 viewCount = mViews.size(); 5521 if (viewCount != 0) { 5522 mTempViews = mViews.toArray(mTempViews != null 5523 ? mTempViews : new View[viewCount]); 5524 mViews.clear(); 5525 } 5526 5527 viewRectCount = mViewRects.size(); 5528 if (viewRectCount != 0) { 5529 mTempViewRects = mViewRects.toArray(mTempViewRects != null 5530 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 5531 mViewRects.clear(); 5532 } 5533 } 5534 5535 for (int i = 0; i < viewCount; i++) { 5536 mTempViews[i].invalidate(); 5537 mTempViews[i] = null; 5538 } 5539 5540 for (int i = 0; i < viewRectCount; i++) { 5541 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 5542 info.target.invalidate(info.left, info.top, info.right, info.bottom); 5543 info.recycle(); 5544 } 5545 } 5546 5547 private void postIfNeededLocked() { 5548 if (!mPosted) { 5549 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 5550 mPosted = true; 5551 } 5552 } 5553 } 5554 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 5555 new InvalidateOnAnimationRunnable(); 5556 5557 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 5558 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 5559 mHandler.sendMessageDelayed(msg, delayMilliseconds); 5560 } 5561 5562 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 5563 long delayMilliseconds) { 5564 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 5565 mHandler.sendMessageDelayed(msg, delayMilliseconds); 5566 } 5567 5568 public void dispatchInvalidateOnAnimation(View view) { 5569 mInvalidateOnAnimationRunnable.addView(view); 5570 } 5571 5572 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 5573 mInvalidateOnAnimationRunnable.addViewRect(info); 5574 } 5575 5576 public void enqueueDisplayList(DisplayList displayList) { 5577 mDisplayLists.add(displayList); 5578 } 5579 5580 public void cancelInvalidate(View view) { 5581 mHandler.removeMessages(MSG_INVALIDATE, view); 5582 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 5583 // them to the pool 5584 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 5585 mInvalidateOnAnimationRunnable.removeView(view); 5586 } 5587 5588 public void dispatchKey(KeyEvent event) { 5589 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 5590 msg.setAsynchronous(true); 5591 mHandler.sendMessage(msg); 5592 } 5593 5594 public void dispatchKeyFromIme(KeyEvent event) { 5595 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 5596 msg.setAsynchronous(true); 5597 mHandler.sendMessage(msg); 5598 } 5599 5600 public void dispatchUnhandledKey(KeyEvent event) { 5601 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 5602 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 5603 final int keyCode = event.getKeyCode(); 5604 final int metaState = event.getMetaState(); 5605 5606 // Check for fallback actions specified by the key character map. 5607 KeyCharacterMap.FallbackAction fallbackAction = 5608 kcm.getFallbackAction(keyCode, metaState); 5609 if (fallbackAction != null) { 5610 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 5611 KeyEvent fallbackEvent = KeyEvent.obtain( 5612 event.getDownTime(), event.getEventTime(), 5613 event.getAction(), fallbackAction.keyCode, 5614 event.getRepeatCount(), fallbackAction.metaState, 5615 event.getDeviceId(), event.getScanCode(), 5616 flags, event.getSource(), null); 5617 fallbackAction.recycle(); 5618 5619 dispatchKey(fallbackEvent); 5620 } 5621 } 5622 } 5623 5624 public void dispatchAppVisibility(boolean visible) { 5625 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 5626 msg.arg1 = visible ? 1 : 0; 5627 mHandler.sendMessage(msg); 5628 } 5629 5630 public void dispatchScreenStateChange(boolean on) { 5631 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 5632 msg.arg1 = on ? 1 : 0; 5633 mHandler.sendMessage(msg); 5634 } 5635 5636 public void dispatchGetNewSurface() { 5637 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 5638 mHandler.sendMessage(msg); 5639 } 5640 5641 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 5642 Message msg = Message.obtain(); 5643 msg.what = MSG_WINDOW_FOCUS_CHANGED; 5644 msg.arg1 = hasFocus ? 1 : 0; 5645 msg.arg2 = inTouchMode ? 1 : 0; 5646 mHandler.sendMessage(msg); 5647 } 5648 5649 public void dispatchCloseSystemDialogs(String reason) { 5650 Message msg = Message.obtain(); 5651 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 5652 msg.obj = reason; 5653 mHandler.sendMessage(msg); 5654 } 5655 5656 public void dispatchDragEvent(DragEvent event) { 5657 final int what; 5658 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 5659 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 5660 mHandler.removeMessages(what); 5661 } else { 5662 what = MSG_DISPATCH_DRAG_EVENT; 5663 } 5664 Message msg = mHandler.obtainMessage(what, event); 5665 mHandler.sendMessage(msg); 5666 } 5667 5668 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 5669 int localValue, int localChanges) { 5670 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 5671 args.seq = seq; 5672 args.globalVisibility = globalVisibility; 5673 args.localValue = localValue; 5674 args.localChanges = localChanges; 5675 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 5676 } 5677 5678 public void dispatchDoneAnimating() { 5679 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 5680 } 5681 5682 public void dispatchCheckFocus() { 5683 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 5684 // This will result in a call to checkFocus() below. 5685 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 5686 } 5687 } 5688 5689 /** 5690 * Post a callback to send a 5691 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 5692 * This event is send at most once every 5693 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 5694 */ 5695 private void postSendWindowContentChangedCallback(View source) { 5696 if (mSendWindowContentChangedAccessibilityEvent == null) { 5697 mSendWindowContentChangedAccessibilityEvent = 5698 new SendWindowContentChangedAccessibilityEvent(); 5699 } 5700 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource; 5701 if (oldSource == null) { 5702 mSendWindowContentChangedAccessibilityEvent.mSource = source; 5703 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 5704 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 5705 } else { 5706 mSendWindowContentChangedAccessibilityEvent.mSource = 5707 getCommonPredecessor(oldSource, source); 5708 } 5709 } 5710 5711 /** 5712 * Remove a posted callback to send a 5713 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 5714 */ 5715 private void removeSendWindowContentChangedCallback() { 5716 if (mSendWindowContentChangedAccessibilityEvent != null) { 5717 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 5718 } 5719 } 5720 5721 public boolean showContextMenuForChild(View originalView) { 5722 return false; 5723 } 5724 5725 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 5726 return null; 5727 } 5728 5729 public void createContextMenu(ContextMenu menu) { 5730 } 5731 5732 public void childDrawableStateChanged(View child) { 5733 } 5734 5735 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 5736 if (mView == null) { 5737 return false; 5738 } 5739 // Intercept accessibility focus events fired by virtual nodes to keep 5740 // track of accessibility focus position in such nodes. 5741 final int eventType = event.getEventType(); 5742 switch (eventType) { 5743 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 5744 final long sourceNodeId = event.getSourceNodeId(); 5745 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5746 sourceNodeId); 5747 View source = mView.findViewByAccessibilityId(accessibilityViewId); 5748 if (source != null) { 5749 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 5750 if (provider != null) { 5751 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo( 5752 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId)); 5753 setAccessibilityFocus(source, node); 5754 } 5755 } 5756 } break; 5757 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 5758 final long sourceNodeId = event.getSourceNodeId(); 5759 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 5760 sourceNodeId); 5761 View source = mView.findViewByAccessibilityId(accessibilityViewId); 5762 if (source != null) { 5763 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 5764 if (provider != null) { 5765 setAccessibilityFocus(null, null); 5766 } 5767 } 5768 } break; 5769 } 5770 mAccessibilityManager.sendAccessibilityEvent(event); 5771 return true; 5772 } 5773 5774 @Override 5775 public void childAccessibilityStateChanged(View child) { 5776 postSendWindowContentChangedCallback(child); 5777 } 5778 5779 @Override 5780 public boolean canResolveLayoutDirection() { 5781 return true; 5782 } 5783 5784 @Override 5785 public boolean isLayoutDirectionResolved() { 5786 return true; 5787 } 5788 5789 @Override 5790 public int getLayoutDirection() { 5791 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT; 5792 } 5793 5794 @Override 5795 public boolean canResolveTextDirection() { 5796 return true; 5797 } 5798 5799 @Override 5800 public boolean isTextDirectionResolved() { 5801 return true; 5802 } 5803 5804 @Override 5805 public int getTextDirection() { 5806 return View.TEXT_DIRECTION_RESOLVED_DEFAULT; 5807 } 5808 5809 @Override 5810 public boolean canResolveTextAlignment() { 5811 return true; 5812 } 5813 5814 @Override 5815 public boolean isTextAlignmentResolved() { 5816 return true; 5817 } 5818 5819 @Override 5820 public int getTextAlignment() { 5821 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT; 5822 } 5823 5824 private View getCommonPredecessor(View first, View second) { 5825 if (mAttachInfo != null) { 5826 if (mTempHashSet == null) { 5827 mTempHashSet = new HashSet<View>(); 5828 } 5829 HashSet<View> seen = mTempHashSet; 5830 seen.clear(); 5831 View firstCurrent = first; 5832 while (firstCurrent != null) { 5833 seen.add(firstCurrent); 5834 ViewParent firstCurrentParent = firstCurrent.mParent; 5835 if (firstCurrentParent instanceof View) { 5836 firstCurrent = (View) firstCurrentParent; 5837 } else { 5838 firstCurrent = null; 5839 } 5840 } 5841 View secondCurrent = second; 5842 while (secondCurrent != null) { 5843 if (seen.contains(secondCurrent)) { 5844 seen.clear(); 5845 return secondCurrent; 5846 } 5847 ViewParent secondCurrentParent = secondCurrent.mParent; 5848 if (secondCurrentParent instanceof View) { 5849 secondCurrent = (View) secondCurrentParent; 5850 } else { 5851 secondCurrent = null; 5852 } 5853 } 5854 seen.clear(); 5855 } 5856 return null; 5857 } 5858 5859 void checkThread() { 5860 if (mThread != Thread.currentThread()) { 5861 throw new CalledFromWrongThreadException( 5862 "Only the original thread that created a view hierarchy can touch its views."); 5863 } 5864 } 5865 5866 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 5867 // ViewAncestor never intercepts touch event, so this can be a no-op 5868 } 5869 5870 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 5871 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 5872 if (rectangle != null) { 5873 mTempRect.set(rectangle); 5874 mTempRect.offset(0, -mCurScrollY); 5875 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5876 try { 5877 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate); 5878 } catch (RemoteException re) { 5879 /* ignore */ 5880 } 5881 } 5882 return scrolled; 5883 } 5884 5885 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 5886 // Do nothing. 5887 } 5888 5889 class TakenSurfaceHolder extends BaseSurfaceHolder { 5890 @Override 5891 public boolean onAllowLockCanvas() { 5892 return mDrawingAllowed; 5893 } 5894 5895 @Override 5896 public void onRelayoutContainer() { 5897 // Not currently interesting -- from changing between fixed and layout size. 5898 } 5899 5900 public void setFormat(int format) { 5901 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 5902 } 5903 5904 public void setType(int type) { 5905 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 5906 } 5907 5908 @Override 5909 public void onUpdateSurface() { 5910 // We take care of format and type changes on our own. 5911 throw new IllegalStateException("Shouldn't be here"); 5912 } 5913 5914 public boolean isCreating() { 5915 return mIsCreating; 5916 } 5917 5918 @Override 5919 public void setFixedSize(int width, int height) { 5920 throw new UnsupportedOperationException( 5921 "Currently only support sizing from layout"); 5922 } 5923 5924 public void setKeepScreenOn(boolean screenOn) { 5925 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 5926 } 5927 } 5928 5929 static class W extends IWindow.Stub { 5930 private final WeakReference<ViewRootImpl> mViewAncestor; 5931 private final IWindowSession mWindowSession; 5932 5933 W(ViewRootImpl viewAncestor) { 5934 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 5935 mWindowSession = viewAncestor.mWindowSession; 5936 } 5937 5938 public void resized(Rect frame, Rect overscanInsets, Rect contentInsets, 5939 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 5940 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5941 if (viewAncestor != null) { 5942 viewAncestor.dispatchResized(frame, overscanInsets, contentInsets, 5943 visibleInsets, reportDraw, newConfig); 5944 } 5945 } 5946 5947 @Override 5948 public void moved(int newX, int newY) { 5949 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5950 if (viewAncestor != null) { 5951 viewAncestor.dispatchMoved(newX, newY); 5952 } 5953 } 5954 5955 public void dispatchAppVisibility(boolean visible) { 5956 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5957 if (viewAncestor != null) { 5958 viewAncestor.dispatchAppVisibility(visible); 5959 } 5960 } 5961 5962 public void dispatchScreenState(boolean on) { 5963 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5964 if (viewAncestor != null) { 5965 viewAncestor.dispatchScreenStateChange(on); 5966 } 5967 } 5968 5969 public void dispatchGetNewSurface() { 5970 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5971 if (viewAncestor != null) { 5972 viewAncestor.dispatchGetNewSurface(); 5973 } 5974 } 5975 5976 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 5977 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5978 if (viewAncestor != null) { 5979 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 5980 } 5981 } 5982 5983 private static int checkCallingPermission(String permission) { 5984 try { 5985 return ActivityManagerNative.getDefault().checkPermission( 5986 permission, Binder.getCallingPid(), Binder.getCallingUid()); 5987 } catch (RemoteException e) { 5988 return PackageManager.PERMISSION_DENIED; 5989 } 5990 } 5991 5992 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 5993 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5994 if (viewAncestor != null) { 5995 final View view = viewAncestor.mView; 5996 if (view != null) { 5997 if (checkCallingPermission(Manifest.permission.DUMP) != 5998 PackageManager.PERMISSION_GRANTED) { 5999 throw new SecurityException("Insufficient permissions to invoke" 6000 + " executeCommand() from pid=" + Binder.getCallingPid() 6001 + ", uid=" + Binder.getCallingUid()); 6002 } 6003 6004 OutputStream clientStream = null; 6005 try { 6006 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 6007 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 6008 } catch (IOException e) { 6009 e.printStackTrace(); 6010 } finally { 6011 if (clientStream != null) { 6012 try { 6013 clientStream.close(); 6014 } catch (IOException e) { 6015 e.printStackTrace(); 6016 } 6017 } 6018 } 6019 } 6020 } 6021 } 6022 6023 public void closeSystemDialogs(String reason) { 6024 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6025 if (viewAncestor != null) { 6026 viewAncestor.dispatchCloseSystemDialogs(reason); 6027 } 6028 } 6029 6030 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 6031 boolean sync) { 6032 if (sync) { 6033 try { 6034 mWindowSession.wallpaperOffsetsComplete(asBinder()); 6035 } catch (RemoteException e) { 6036 } 6037 } 6038 } 6039 6040 public void dispatchWallpaperCommand(String action, int x, int y, 6041 int z, Bundle extras, boolean sync) { 6042 if (sync) { 6043 try { 6044 mWindowSession.wallpaperCommandComplete(asBinder(), null); 6045 } catch (RemoteException e) { 6046 } 6047 } 6048 } 6049 6050 /* Drag/drop */ 6051 public void dispatchDragEvent(DragEvent event) { 6052 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6053 if (viewAncestor != null) { 6054 viewAncestor.dispatchDragEvent(event); 6055 } 6056 } 6057 6058 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 6059 int localValue, int localChanges) { 6060 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6061 if (viewAncestor != null) { 6062 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 6063 localValue, localChanges); 6064 } 6065 } 6066 6067 public void doneAnimating() { 6068 final ViewRootImpl viewAncestor = mViewAncestor.get(); 6069 if (viewAncestor != null) { 6070 viewAncestor.dispatchDoneAnimating(); 6071 } 6072 } 6073 } 6074 6075 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 6076 public CalledFromWrongThreadException(String msg) { 6077 super(msg); 6078 } 6079 } 6080 6081 private SurfaceHolder mHolder = new SurfaceHolder() { 6082 // we only need a SurfaceHolder for opengl. it would be nice 6083 // to implement everything else though, especially the callback 6084 // support (opengl doesn't make use of it right now, but eventually 6085 // will). 6086 public Surface getSurface() { 6087 return mSurface; 6088 } 6089 6090 public boolean isCreating() { 6091 return false; 6092 } 6093 6094 public void addCallback(Callback callback) { 6095 } 6096 6097 public void removeCallback(Callback callback) { 6098 } 6099 6100 public void setFixedSize(int width, int height) { 6101 } 6102 6103 public void setSizeFromLayout() { 6104 } 6105 6106 public void setFormat(int format) { 6107 } 6108 6109 public void setType(int type) { 6110 } 6111 6112 public void setKeepScreenOn(boolean screenOn) { 6113 } 6114 6115 public Canvas lockCanvas() { 6116 return null; 6117 } 6118 6119 public Canvas lockCanvas(Rect dirty) { 6120 return null; 6121 } 6122 6123 public void unlockCanvasAndPost(Canvas canvas) { 6124 } 6125 public Rect getSurfaceFrame() { 6126 return null; 6127 } 6128 }; 6129 6130 static RunQueue getRunQueue() { 6131 RunQueue rq = sRunQueues.get(); 6132 if (rq != null) { 6133 return rq; 6134 } 6135 rq = new RunQueue(); 6136 sRunQueues.set(rq); 6137 return rq; 6138 } 6139 6140 /** 6141 * The run queue is used to enqueue pending work from Views when no Handler is 6142 * attached. The work is executed during the next call to performTraversals on 6143 * the thread. 6144 * @hide 6145 */ 6146 static final class RunQueue { 6147 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 6148 6149 void post(Runnable action) { 6150 postDelayed(action, 0); 6151 } 6152 6153 void postDelayed(Runnable action, long delayMillis) { 6154 HandlerAction handlerAction = new HandlerAction(); 6155 handlerAction.action = action; 6156 handlerAction.delay = delayMillis; 6157 6158 synchronized (mActions) { 6159 mActions.add(handlerAction); 6160 } 6161 } 6162 6163 void removeCallbacks(Runnable action) { 6164 final HandlerAction handlerAction = new HandlerAction(); 6165 handlerAction.action = action; 6166 6167 synchronized (mActions) { 6168 final ArrayList<HandlerAction> actions = mActions; 6169 6170 while (actions.remove(handlerAction)) { 6171 // Keep going 6172 } 6173 } 6174 } 6175 6176 void executeActions(Handler handler) { 6177 synchronized (mActions) { 6178 final ArrayList<HandlerAction> actions = mActions; 6179 final int count = actions.size(); 6180 6181 for (int i = 0; i < count; i++) { 6182 final HandlerAction handlerAction = actions.get(i); 6183 handler.postDelayed(handlerAction.action, handlerAction.delay); 6184 } 6185 6186 actions.clear(); 6187 } 6188 } 6189 6190 private static class HandlerAction { 6191 Runnable action; 6192 long delay; 6193 6194 @Override 6195 public boolean equals(Object o) { 6196 if (this == o) return true; 6197 if (o == null || getClass() != o.getClass()) return false; 6198 6199 HandlerAction that = (HandlerAction) o; 6200 return !(action != null ? !action.equals(that.action) : that.action != null); 6201 6202 } 6203 6204 @Override 6205 public int hashCode() { 6206 int result = action != null ? action.hashCode() : 0; 6207 result = 31 * result + (int) (delay ^ (delay >>> 32)); 6208 return result; 6209 } 6210 } 6211 } 6212 6213 /** 6214 * Class for managing the accessibility interaction connection 6215 * based on the global accessibility state. 6216 */ 6217 final class AccessibilityInteractionConnectionManager 6218 implements AccessibilityStateChangeListener { 6219 public void onAccessibilityStateChanged(boolean enabled) { 6220 if (enabled) { 6221 ensureConnection(); 6222 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 6223 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 6224 View focusedView = mView.findFocus(); 6225 if (focusedView != null && focusedView != mView) { 6226 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6227 } 6228 } 6229 } else { 6230 ensureNoConnection(); 6231 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 6232 } 6233 } 6234 6235 public void ensureConnection() { 6236 if (mAttachInfo != null) { 6237 final boolean registered = 6238 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 6239 if (!registered) { 6240 mAttachInfo.mAccessibilityWindowId = 6241 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 6242 new AccessibilityInteractionConnection(ViewRootImpl.this)); 6243 } 6244 } 6245 } 6246 6247 public void ensureNoConnection() { 6248 final boolean registered = 6249 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 6250 if (registered) { 6251 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 6252 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 6253 } 6254 } 6255 } 6256 6257 /** 6258 * This class is an interface this ViewAncestor provides to the 6259 * AccessibilityManagerService to the latter can interact with 6260 * the view hierarchy in this ViewAncestor. 6261 */ 6262 static final class AccessibilityInteractionConnection 6263 extends IAccessibilityInteractionConnection.Stub { 6264 private final WeakReference<ViewRootImpl> mViewRootImpl; 6265 6266 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 6267 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 6268 } 6269 6270 @Override 6271 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 6272 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6273 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6274 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6275 if (viewRootImpl != null && viewRootImpl.mView != null) { 6276 viewRootImpl.getAccessibilityInteractionController() 6277 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 6278 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6279 spec); 6280 } else { 6281 // We cannot make the call and notify the caller so it does not wait. 6282 try { 6283 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6284 } catch (RemoteException re) { 6285 /* best effort - ignore */ 6286 } 6287 } 6288 } 6289 6290 @Override 6291 public void performAccessibilityAction(long accessibilityNodeId, int action, 6292 Bundle arguments, int interactionId, 6293 IAccessibilityInteractionConnectionCallback callback, int flags, 6294 int interogatingPid, long interrogatingTid) { 6295 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6296 if (viewRootImpl != null && viewRootImpl.mView != null) { 6297 viewRootImpl.getAccessibilityInteractionController() 6298 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 6299 interactionId, callback, flags, interogatingPid, interrogatingTid); 6300 } else { 6301 // We cannot make the call and notify the caller so it does not wait. 6302 try { 6303 callback.setPerformAccessibilityActionResult(false, interactionId); 6304 } catch (RemoteException re) { 6305 /* best effort - ignore */ 6306 } 6307 } 6308 } 6309 6310 @Override 6311 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId, 6312 String viewId, int interactionId, 6313 IAccessibilityInteractionConnectionCallback callback, int flags, 6314 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6315 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6316 if (viewRootImpl != null && viewRootImpl.mView != null) { 6317 viewRootImpl.getAccessibilityInteractionController() 6318 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId, 6319 viewId, interactionId, callback, flags, interrogatingPid, 6320 interrogatingTid, spec); 6321 } else { 6322 // We cannot make the call and notify the caller so it does not wait. 6323 try { 6324 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6325 } catch (RemoteException re) { 6326 /* best effort - ignore */ 6327 } 6328 } 6329 } 6330 6331 @Override 6332 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 6333 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 6334 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6335 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6336 if (viewRootImpl != null && viewRootImpl.mView != null) { 6337 viewRootImpl.getAccessibilityInteractionController() 6338 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 6339 interactionId, callback, flags, interrogatingPid, interrogatingTid, 6340 spec); 6341 } else { 6342 // We cannot make the call and notify the caller so it does not wait. 6343 try { 6344 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 6345 } catch (RemoteException re) { 6346 /* best effort - ignore */ 6347 } 6348 } 6349 } 6350 6351 @Override 6352 public void findFocus(long accessibilityNodeId, int focusType, int interactionId, 6353 IAccessibilityInteractionConnectionCallback callback, int flags, 6354 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6355 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6356 if (viewRootImpl != null && viewRootImpl.mView != null) { 6357 viewRootImpl.getAccessibilityInteractionController() 6358 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback, 6359 flags, interrogatingPid, interrogatingTid, spec); 6360 } else { 6361 // We cannot make the call and notify the caller so it does not wait. 6362 try { 6363 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6364 } catch (RemoteException re) { 6365 /* best effort - ignore */ 6366 } 6367 } 6368 } 6369 6370 @Override 6371 public void focusSearch(long accessibilityNodeId, int direction, int interactionId, 6372 IAccessibilityInteractionConnectionCallback callback, int flags, 6373 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 6374 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 6375 if (viewRootImpl != null && viewRootImpl.mView != null) { 6376 viewRootImpl.getAccessibilityInteractionController() 6377 .focusSearchClientThread(accessibilityNodeId, direction, interactionId, 6378 callback, flags, interrogatingPid, interrogatingTid, spec); 6379 } else { 6380 // We cannot make the call and notify the caller so it does not wait. 6381 try { 6382 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 6383 } catch (RemoteException re) { 6384 /* best effort - ignore */ 6385 } 6386 } 6387 } 6388 } 6389 6390 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 6391 public View mSource; 6392 6393 public void run() { 6394 if (mSource != null) { 6395 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 6396 mSource.resetAccessibilityStateChanged(); 6397 mSource = null; 6398 } 6399 } 6400 } 6401} 6402