ViewRootImpl.java revision 2eecea3b48ece6f45b30fef9b41dc20075ccc94f
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.Manifest; 20import android.animation.LayoutTransition; 21import android.app.ActivityManagerNative; 22import android.content.ClipDescription; 23import android.content.ComponentCallbacks; 24import android.content.ComponentCallbacks2; 25import android.content.Context; 26import android.content.pm.PackageManager; 27import android.content.res.CompatibilityInfo; 28import android.content.res.Configuration; 29import android.content.res.Resources; 30import android.graphics.Canvas; 31import android.graphics.Paint; 32import android.graphics.PixelFormat; 33import android.graphics.Point; 34import android.graphics.PointF; 35import android.graphics.PorterDuff; 36import android.graphics.Rect; 37import android.graphics.Region; 38import android.media.AudioManager; 39import android.os.Binder; 40import android.os.Bundle; 41import android.os.Debug; 42import android.os.Handler; 43import android.os.LatencyTimer; 44import android.os.Looper; 45import android.os.Message; 46import android.os.ParcelFileDescriptor; 47import android.os.Process; 48import android.os.RemoteException; 49import android.os.SystemClock; 50import android.os.SystemProperties; 51import android.util.AndroidRuntimeException; 52import android.util.DisplayMetrics; 53import android.util.EventLog; 54import android.util.Log; 55import android.util.LongSparseArray; 56import android.util.Pool; 57import android.util.Poolable; 58import android.util.PoolableManager; 59import android.util.Pools; 60import android.util.Slog; 61import android.util.TypedValue; 62import android.view.View.MeasureSpec; 63import android.view.accessibility.AccessibilityEvent; 64import android.view.accessibility.AccessibilityInteractionClient; 65import android.view.accessibility.AccessibilityManager; 66import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener; 67import android.view.accessibility.AccessibilityNodeInfo; 68import android.view.accessibility.AccessibilityNodeProvider; 69import android.view.accessibility.IAccessibilityInteractionConnection; 70import android.view.accessibility.IAccessibilityInteractionConnectionCallback; 71import android.view.animation.AccelerateDecelerateInterpolator; 72import android.view.animation.Interpolator; 73import android.view.inputmethod.InputConnection; 74import android.view.inputmethod.InputMethodManager; 75import android.widget.Scroller; 76 77import com.android.internal.policy.PolicyManager; 78import com.android.internal.view.BaseSurfaceHolder; 79import com.android.internal.view.IInputMethodCallback; 80import com.android.internal.view.IInputMethodSession; 81import com.android.internal.view.RootViewSurfaceTaker; 82 83import java.io.IOException; 84import java.io.OutputStream; 85import java.io.PrintWriter; 86import java.lang.ref.WeakReference; 87import java.util.ArrayList; 88import java.util.List; 89 90/** 91 * The top of a view hierarchy, implementing the needed protocol between View 92 * and the WindowManager. This is for the most part an internal implementation 93 * detail of {@link WindowManagerImpl}. 94 * 95 * {@hide} 96 */ 97@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"}) 98public final class ViewRootImpl extends Handler implements ViewParent, 99 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks, 100 Choreographer.OnDrawListener { 101 private static final String TAG = "ViewRootImpl"; 102 private static final boolean DBG = false; 103 private static final boolean LOCAL_LOGV = false; 104 /** @noinspection PointlessBooleanExpression*/ 105 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV; 106 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV; 107 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV; 108 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV; 109 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV; 110 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV; 111 private static final boolean DEBUG_IMF = false || LOCAL_LOGV; 112 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV; 113 private static final boolean DEBUG_FPS = false; 114 115 /** 116 * Set this system property to true to force the view hierarchy to render 117 * at 60 Hz. This can be used to measure the potential framerate. 118 */ 119 private static final String PROPERTY_PROFILE_RENDERING = "viewancestor.profile_rendering"; 120 121 private static final boolean MEASURE_LATENCY = false; 122 private static LatencyTimer lt; 123 124 /** 125 * Maximum time we allow the user to roll the trackball enough to generate 126 * a key event, before resetting the counters. 127 */ 128 static final int MAX_TRACKBALL_DELAY = 250; 129 130 static IWindowSession sWindowSession; 131 132 static final Object mStaticInit = new Object(); 133 static boolean mInitialized = false; 134 135 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>(); 136 137 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>(); 138 static boolean sFirstDrawComplete = false; 139 140 static final ArrayList<ComponentCallbacks> sConfigCallbacks 141 = new ArrayList<ComponentCallbacks>(); 142 143 long mLastTrackballTime = 0; 144 final TrackballAxis mTrackballAxisX = new TrackballAxis(); 145 final TrackballAxis mTrackballAxisY = new TrackballAxis(); 146 147 int mLastJoystickXDirection; 148 int mLastJoystickYDirection; 149 int mLastJoystickXKeyCode; 150 int mLastJoystickYKeyCode; 151 152 final int[] mTmpLocation = new int[2]; 153 154 final TypedValue mTmpValue = new TypedValue(); 155 156 final InputMethodCallback mInputMethodCallback; 157 final Thread mThread; 158 159 final WindowLeaked mLocation; 160 161 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams(); 162 163 final W mWindow; 164 165 final int mTargetSdkVersion; 166 167 int mSeq; 168 169 View mView; 170 View mFocusedView; 171 View mRealFocusedView; // this is not set to null in touch mode 172 View mOldFocusedView; 173 int mViewVisibility; 174 boolean mAppVisible = true; 175 int mOrigWindowType = -1; 176 177 // Set to true if the owner of this window is in the stopped state, 178 // so the window should no longer be active. 179 boolean mStopped = false; 180 181 boolean mLastInCompatMode = false; 182 183 SurfaceHolder.Callback2 mSurfaceHolderCallback; 184 BaseSurfaceHolder mSurfaceHolder; 185 boolean mIsCreating; 186 boolean mDrawingAllowed; 187 188 final Region mTransparentRegion; 189 final Region mPreviousTransparentRegion; 190 191 int mWidth; 192 int mHeight; 193 Rect mDirty; 194 final Rect mCurrentDirty = new Rect(); 195 final Rect mPreviousDirty = new Rect(); 196 boolean mIsAnimating; 197 198 CompatibilityInfo.Translator mTranslator; 199 200 final View.AttachInfo mAttachInfo; 201 InputChannel mInputChannel; 202 InputQueue.Callback mInputQueueCallback; 203 InputQueue mInputQueue; 204 FallbackEventHandler mFallbackEventHandler; 205 Choreographer mChoreographer; 206 207 final Rect mTempRect; // used in the transaction to not thrash the heap. 208 final Rect mVisRect; // used to retrieve visible rect of focused view. 209 210 boolean mTraversalScheduled; 211 long mLastTraversalFinishedTimeNanos; 212 long mLastDrawFinishedTimeNanos; 213 boolean mWillDrawSoon; 214 boolean mLayoutRequested; 215 boolean mFirst; 216 boolean mReportNextDraw; 217 boolean mFullRedrawNeeded; 218 boolean mNewSurfaceNeeded; 219 boolean mHasHadWindowFocus; 220 boolean mLastWasImTarget; 221 222 // Pool of queued input events. 223 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10; 224 private QueuedInputEvent mQueuedInputEventPool; 225 private int mQueuedInputEventPoolSize; 226 227 // Input event queue. 228 QueuedInputEvent mFirstPendingInputEvent; 229 QueuedInputEvent mCurrentInputEvent; 230 boolean mProcessInputEventsScheduled; 231 232 boolean mWindowAttributesChanged = false; 233 int mWindowAttributesChangesFlag = 0; 234 235 // These can be accessed by any thread, must be protected with a lock. 236 // Surface can never be reassigned or cleared (use Surface.clear()). 237 private final Surface mSurface = new Surface(); 238 239 boolean mAdded; 240 boolean mAddedTouchMode; 241 242 CompatibilityInfoHolder mCompatibilityInfo; 243 244 /*package*/ int mAddNesting; 245 246 // These are accessed by multiple threads. 247 final Rect mWinFrame; // frame given by window manager. 248 249 final Rect mPendingVisibleInsets = new Rect(); 250 final Rect mPendingContentInsets = new Rect(); 251 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets 252 = new ViewTreeObserver.InternalInsetsInfo(); 253 254 final Configuration mLastConfiguration = new Configuration(); 255 final Configuration mPendingConfiguration = new Configuration(); 256 257 class ResizedInfo { 258 Rect coveredInsets; 259 Rect visibleInsets; 260 Configuration newConfig; 261 } 262 263 boolean mScrollMayChange; 264 int mSoftInputMode; 265 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 Thread mRenderProfiler; 286 private volatile 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 /** 294 * see {@link #playSoundEffect(int)} 295 */ 296 AudioManager mAudioManager; 297 298 final AccessibilityManager mAccessibilityManager; 299 300 AccessibilityInteractionController mAccessibilityInteractionController; 301 302 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager; 303 304 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent; 305 306 AccessibilityPrefetchStrategy mAccessibilityPrefetchStrategy; 307 308 private final int mDensity; 309 310 /** 311 * Consistency verifier for debugging purposes. 312 */ 313 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 314 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 315 new InputEventConsistencyVerifier(this, 0) : null; 316 317 public static IWindowSession getWindowSession(Looper mainLooper) { 318 synchronized (mStaticInit) { 319 if (!mInitialized) { 320 try { 321 InputMethodManager imm = InputMethodManager.getInstance(mainLooper); 322 sWindowSession = Display.getWindowManager().openSession( 323 imm.getClient(), imm.getInputContext()); 324 mInitialized = true; 325 } catch (RemoteException e) { 326 } 327 } 328 return sWindowSession; 329 } 330 } 331 332 static final class SystemUiVisibilityInfo { 333 int seq; 334 int globalVisibility; 335 int localValue; 336 int localChanges; 337 } 338 339 public ViewRootImpl(Context context) { 340 super(); 341 342 if (MEASURE_LATENCY) { 343 if (lt == null) { 344 lt = new LatencyTimer(100, 1000); 345 } 346 } 347 348 // Initialize the statics when this class is first instantiated. This is 349 // done here instead of in the static block because Zygote does not 350 // allow the spawning of threads. 351 getWindowSession(context.getMainLooper()); 352 353 mThread = Thread.currentThread(); 354 mLocation = new WindowLeaked(null); 355 mLocation.fillInStackTrace(); 356 mWidth = -1; 357 mHeight = -1; 358 mDirty = new Rect(); 359 mTempRect = new Rect(); 360 mVisRect = new Rect(); 361 mWinFrame = new Rect(); 362 mWindow = new W(this); 363 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion; 364 mInputMethodCallback = new InputMethodCallback(this); 365 mViewVisibility = View.GONE; 366 mTransparentRegion = new Region(); 367 mPreviousTransparentRegion = new Region(); 368 mFirst = true; // true for the first time the view is added 369 mAdded = false; 370 mAccessibilityManager = AccessibilityManager.getInstance(context); 371 mAccessibilityInteractionConnectionManager = 372 new AccessibilityInteractionConnectionManager(); 373 mAccessibilityManager.addAccessibilityStateChangeListener( 374 mAccessibilityInteractionConnectionManager); 375 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this); 376 mViewConfiguration = ViewConfiguration.get(context); 377 mDensity = context.getResources().getDisplayMetrics().densityDpi; 378 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context); 379 mProfileRendering = Boolean.parseBoolean( 380 SystemProperties.get(PROPERTY_PROFILE_RENDERING, "false")); 381 mChoreographer = Choreographer.getInstance(); 382 } 383 384 public static void addFirstDrawHandler(Runnable callback) { 385 synchronized (sFirstDrawHandlers) { 386 if (!sFirstDrawComplete) { 387 sFirstDrawHandlers.add(callback); 388 } 389 } 390 } 391 392 public static void addConfigCallback(ComponentCallbacks callback) { 393 synchronized (sConfigCallbacks) { 394 sConfigCallbacks.add(callback); 395 } 396 } 397 398 // FIXME for perf testing only 399 private boolean mProfile = false; 400 401 /** 402 * Call this to profile the next traversal call. 403 * FIXME for perf testing only. Remove eventually 404 */ 405 public void profile() { 406 mProfile = true; 407 } 408 409 /** 410 * Indicates whether we are in touch mode. Calling this method triggers an IPC 411 * call and should be avoided whenever possible. 412 * 413 * @return True, if the device is in touch mode, false otherwise. 414 * 415 * @hide 416 */ 417 static boolean isInTouchMode() { 418 if (mInitialized) { 419 try { 420 return sWindowSession.getInTouchMode(); 421 } catch (RemoteException e) { 422 } 423 } 424 return false; 425 } 426 427 /** 428 * We have one child 429 */ 430 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) { 431 synchronized (this) { 432 if (mView == null) { 433 mChoreographer.addOnDrawListener(this); 434 435 mView = view; 436 mFallbackEventHandler.setView(view); 437 mWindowAttributes.copyFrom(attrs); 438 attrs = mWindowAttributes; 439 440 if (view instanceof RootViewSurfaceTaker) { 441 mSurfaceHolderCallback = 442 ((RootViewSurfaceTaker)view).willYouTakeTheSurface(); 443 if (mSurfaceHolderCallback != null) { 444 mSurfaceHolder = new TakenSurfaceHolder(); 445 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN); 446 } 447 } 448 449 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 450 mTranslator = compatibilityInfo.getTranslator(); 451 452 // If the application owns the surface, don't enable hardware acceleration 453 if (mSurfaceHolder == null) { 454 enableHardwareAcceleration(attrs); 455 } 456 457 boolean restore = false; 458 if (mTranslator != null) { 459 mSurface.setCompatibilityTranslator(mTranslator); 460 restore = true; 461 attrs.backup(); 462 mTranslator.translateWindowLayout(attrs); 463 } 464 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs); 465 466 if (!compatibilityInfo.supportsScreen()) { 467 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 468 mLastInCompatMode = true; 469 } 470 471 mSoftInputMode = attrs.softInputMode; 472 mWindowAttributesChanged = true; 473 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED; 474 mAttachInfo.mRootView = view; 475 mAttachInfo.mScalingRequired = mTranslator != null; 476 mAttachInfo.mApplicationScale = 477 mTranslator == null ? 1.0f : mTranslator.applicationScale; 478 if (panelParentView != null) { 479 mAttachInfo.mPanelParentWindowToken 480 = panelParentView.getApplicationWindowToken(); 481 } 482 mAdded = true; 483 int res; /* = WindowManagerImpl.ADD_OKAY; */ 484 485 // Schedule the first layout -before- adding to the window 486 // manager, to make sure we do the relayout before receiving 487 // any other events from the system. 488 requestLayout(); 489 if ((mWindowAttributes.inputFeatures 490 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { 491 mInputChannel = new InputChannel(); 492 } 493 try { 494 mOrigWindowType = mWindowAttributes.type; 495 res = sWindowSession.add(mWindow, mSeq, mWindowAttributes, 496 getHostVisibility(), mAttachInfo.mContentInsets, 497 mInputChannel); 498 } catch (RemoteException e) { 499 mAdded = false; 500 mView = null; 501 mAttachInfo.mRootView = null; 502 mInputChannel = null; 503 mFallbackEventHandler.setView(null); 504 unscheduleTraversals(); 505 throw new RuntimeException("Adding window failed", e); 506 } finally { 507 if (restore) { 508 attrs.restore(); 509 } 510 } 511 512 if (mTranslator != null) { 513 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets); 514 } 515 mPendingContentInsets.set(mAttachInfo.mContentInsets); 516 mPendingVisibleInsets.set(0, 0, 0, 0); 517 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow); 518 if (res < WindowManagerImpl.ADD_OKAY) { 519 mView = null; 520 mAttachInfo.mRootView = null; 521 mAdded = false; 522 mFallbackEventHandler.setView(null); 523 unscheduleTraversals(); 524 switch (res) { 525 case WindowManagerImpl.ADD_BAD_APP_TOKEN: 526 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN: 527 throw new WindowManagerImpl.BadTokenException( 528 "Unable to add window -- token " + attrs.token 529 + " is not valid; is your activity running?"); 530 case WindowManagerImpl.ADD_NOT_APP_TOKEN: 531 throw new WindowManagerImpl.BadTokenException( 532 "Unable to add window -- token " + attrs.token 533 + " is not for an application"); 534 case WindowManagerImpl.ADD_APP_EXITING: 535 throw new WindowManagerImpl.BadTokenException( 536 "Unable to add window -- app for token " + attrs.token 537 + " is exiting"); 538 case WindowManagerImpl.ADD_DUPLICATE_ADD: 539 throw new WindowManagerImpl.BadTokenException( 540 "Unable to add window -- window " + mWindow 541 + " has already been added"); 542 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED: 543 // Silently ignore -- we would have just removed it 544 // right away, anyway. 545 return; 546 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON: 547 throw new WindowManagerImpl.BadTokenException( 548 "Unable to add window " + mWindow + 549 " -- another window of this type already exists"); 550 case WindowManagerImpl.ADD_PERMISSION_DENIED: 551 throw new WindowManagerImpl.BadTokenException( 552 "Unable to add window " + mWindow + 553 " -- permission denied for this window type"); 554 } 555 throw new RuntimeException( 556 "Unable to add window -- unknown error code " + res); 557 } 558 559 if (view instanceof RootViewSurfaceTaker) { 560 mInputQueueCallback = 561 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue(); 562 } 563 if (mInputChannel != null) { 564 if (mInputQueueCallback != null) { 565 mInputQueue = new InputQueue(mInputChannel); 566 mInputQueueCallback.onInputQueueCreated(mInputQueue); 567 } else { 568 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel, 569 Looper.myLooper()); 570 } 571 } 572 573 view.assignParent(this); 574 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0; 575 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0; 576 577 if (mAccessibilityManager.isEnabled()) { 578 mAccessibilityInteractionConnectionManager.ensureConnection(); 579 } 580 } 581 } 582 } 583 584 void destroyHardwareResources() { 585 if (mAttachInfo.mHardwareRenderer != null) { 586 if (mAttachInfo.mHardwareRenderer.isEnabled()) { 587 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 588 } 589 mAttachInfo.mHardwareRenderer.destroy(false); 590 } 591 } 592 593 void terminateHardwareResources() { 594 if (mAttachInfo.mHardwareRenderer != null) { 595 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView); 596 mAttachInfo.mHardwareRenderer.destroy(false); 597 } 598 } 599 600 void destroyHardwareLayers() { 601 if (mThread != Thread.currentThread()) { 602 if (mAttachInfo.mHardwareRenderer != null && 603 mAttachInfo.mHardwareRenderer.isEnabled()) { 604 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE); 605 } 606 } else { 607 if (mAttachInfo.mHardwareRenderer != null && 608 mAttachInfo.mHardwareRenderer.isEnabled()) { 609 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 610 } 611 } 612 } 613 614 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) { 615 mAttachInfo.mHardwareAccelerated = false; 616 mAttachInfo.mHardwareAccelerationRequested = false; 617 618 // Don't enable hardware acceleration when the application is in compatibility mode 619 if (mTranslator != null) return; 620 621 // Try to enable hardware acceleration if requested 622 final boolean hardwareAccelerated = 623 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0; 624 625 if (hardwareAccelerated) { 626 if (!HardwareRenderer.isAvailable()) { 627 return; 628 } 629 630 // Persistent processes (including the system) should not do 631 // accelerated rendering on low-end devices. In that case, 632 // sRendererDisabled will be set. In addition, the system process 633 // itself should never do accelerated rendering. In that case, both 634 // sRendererDisabled and sSystemRendererDisabled are set. When 635 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED 636 // can be used by code on the system process to escape that and enable 637 // HW accelerated drawing. (This is basically for the lock screen.) 638 639 final boolean fakeHwAccelerated = (attrs.privateFlags & 640 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0; 641 final boolean forceHwAccelerated = (attrs.privateFlags & 642 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0; 643 644 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled 645 && forceHwAccelerated)) { 646 // Don't enable hardware acceleration when we're not on the main thread 647 if (!HardwareRenderer.sSystemRendererDisabled 648 && Looper.getMainLooper() != Looper.myLooper()) { 649 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware " 650 + "acceleration outside of the main thread, aborting"); 651 return; 652 } 653 654 final boolean translucent = attrs.format != PixelFormat.OPAQUE; 655 if (mAttachInfo.mHardwareRenderer != null) { 656 mAttachInfo.mHardwareRenderer.destroy(true); 657 } 658 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent); 659 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested 660 = mAttachInfo.mHardwareRenderer != null; 661 } else if (fakeHwAccelerated) { 662 // The window had wanted to use hardware acceleration, but this 663 // is not allowed in its process. By setting this flag, it can 664 // still render as if it was accelerated. This is basically for 665 // the preview windows the window manager shows for launching 666 // applications, so they will look more like the app being launched. 667 mAttachInfo.mHardwareAccelerationRequested = true; 668 } 669 } 670 } 671 672 public View getView() { 673 return mView; 674 } 675 676 final WindowLeaked getLocation() { 677 return mLocation; 678 } 679 680 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) { 681 synchronized (this) { 682 int oldSoftInputMode = mWindowAttributes.softInputMode; 683 // preserve compatible window flag if exists. 684 int compatibleWindowFlag = 685 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 686 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs); 687 mWindowAttributes.flags |= compatibleWindowFlag; 688 689 if (newView) { 690 mSoftInputMode = attrs.softInputMode; 691 requestLayout(); 692 } 693 // Don't lose the mode we last auto-computed. 694 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 695 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 696 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode 697 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 698 | (oldSoftInputMode 699 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST); 700 } 701 mWindowAttributesChanged = true; 702 scheduleTraversals(); 703 } 704 } 705 706 void handleAppVisibility(boolean visible) { 707 if (mAppVisible != visible) { 708 mAppVisible = visible; 709 scheduleTraversals(); 710 } 711 } 712 713 void handleGetNewSurface() { 714 mNewSurfaceNeeded = true; 715 mFullRedrawNeeded = true; 716 scheduleTraversals(); 717 } 718 719 /** 720 * {@inheritDoc} 721 */ 722 public void requestLayout() { 723 checkThread(); 724 mLayoutRequested = true; 725 scheduleTraversals(); 726 } 727 728 /** 729 * {@inheritDoc} 730 */ 731 public boolean isLayoutRequested() { 732 return mLayoutRequested; 733 } 734 735 public void invalidateChild(View child, Rect dirty) { 736 checkThread(); 737 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty); 738 if (dirty == null) { 739 // Fast invalidation for GL-enabled applications; GL must redraw everything 740 invalidate(); 741 return; 742 } 743 if (mCurScrollY != 0 || mTranslator != null) { 744 mTempRect.set(dirty); 745 dirty = mTempRect; 746 if (mCurScrollY != 0) { 747 dirty.offset(0, -mCurScrollY); 748 } 749 if (mTranslator != null) { 750 mTranslator.translateRectInAppWindowToScreen(dirty); 751 } 752 if (mAttachInfo.mScalingRequired) { 753 dirty.inset(-1, -1); 754 } 755 } 756 if (!mDirty.isEmpty() && !mDirty.contains(dirty)) { 757 mAttachInfo.mSetIgnoreDirtyState = true; 758 mAttachInfo.mIgnoreDirtyState = true; 759 } 760 mDirty.union(dirty); 761 if (!mWillDrawSoon) { 762 scheduleTraversals(); 763 } 764 } 765 766 void invalidate() { 767 mDirty.set(0, 0, mWidth, mHeight); 768 scheduleTraversals(); 769 } 770 771 void setStopped(boolean stopped) { 772 if (mStopped != stopped) { 773 mStopped = stopped; 774 if (!stopped) { 775 scheduleTraversals(); 776 } 777 } 778 } 779 780 public ViewParent getParent() { 781 return null; 782 } 783 784 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) { 785 invalidateChild(null, dirty); 786 return null; 787 } 788 789 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 790 if (child != mView) { 791 throw new RuntimeException("child is not mine, honest!"); 792 } 793 // Note: don't apply scroll offset, because we want to know its 794 // visibility in the virtual canvas being given to the view hierarchy. 795 return r.intersect(0, 0, mWidth, mHeight); 796 } 797 798 public void bringChildToFront(View child) { 799 } 800 801 public void scheduleTraversals() { 802 if (!mTraversalScheduled) { 803 mTraversalScheduled = true; 804 mChoreographer.scheduleDraw(); 805 } 806 } 807 808 public void unscheduleTraversals() { 809 mTraversalScheduled = false; 810 } 811 812 @Override 813 public void onDraw() { 814 if (mTraversalScheduled) { 815 mTraversalScheduled = false; 816 doTraversal(); 817 } 818 } 819 820 int getHostVisibility() { 821 return mAppVisible ? mView.getVisibility() : View.GONE; 822 } 823 824 void disposeResizeBuffer() { 825 if (mResizeBuffer != null) { 826 mResizeBuffer.destroy(); 827 mResizeBuffer = null; 828 } 829 } 830 831 /** 832 * Add LayoutTransition to the list of transitions to be started in the next traversal. 833 * This list will be cleared after the transitions on the list are start()'ed. These 834 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup 835 * happens during the layout phase of traversal, which we want to complete before any of the 836 * animations are started (because those animations may side-effect properties that layout 837 * depends upon, like the bounding rectangles of the affected views). So we add the transition 838 * to the list and it is started just prior to starting the drawing phase of traversal. 839 * 840 * @param transition The LayoutTransition to be started on the next traversal. 841 * 842 * @hide 843 */ 844 public void requestTransitionStart(LayoutTransition transition) { 845 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) { 846 if (mPendingTransitions == null) { 847 mPendingTransitions = new ArrayList<LayoutTransition>(); 848 } 849 mPendingTransitions.add(transition); 850 } 851 } 852 853 private void doTraversal() { 854 doProcessInputEvents(); 855 856 if (mProfile) { 857 Debug.startMethodTracing("ViewAncestor"); 858 } 859 860 final long traversalStartTime; 861 if (ViewDebug.DEBUG_LATENCY) { 862 traversalStartTime = System.nanoTime(); 863 if (mLastTraversalFinishedTimeNanos != 0) { 864 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting performTraversals(); it has been " 865 + ((traversalStartTime - mLastTraversalFinishedTimeNanos) * 0.000001f) 866 + "ms since the last traversals finished."); 867 } else { 868 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting performTraversals()."); 869 } 870 } 871 872 performTraversals(); 873 874 if (ViewDebug.DEBUG_LATENCY) { 875 long now = System.nanoTime(); 876 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "performTraversals() took " 877 + ((now - traversalStartTime) * 0.000001f) 878 + "ms."); 879 mLastTraversalFinishedTimeNanos = now; 880 } 881 882 if (mProfile) { 883 Debug.stopMethodTracing(); 884 mProfile = false; 885 } 886 } 887 888 private void performTraversals() { 889 // cache mView since it is used so much below... 890 final View host = mView; 891 892 if (DBG) { 893 System.out.println("======================================"); 894 System.out.println("performTraversals"); 895 host.debug(); 896 } 897 898 if (host == null || !mAdded) 899 return; 900 901 mWillDrawSoon = true; 902 boolean windowSizeMayChange = false; 903 boolean newSurface = false; 904 boolean surfaceChanged = false; 905 WindowManager.LayoutParams lp = mWindowAttributes; 906 907 int desiredWindowWidth; 908 int desiredWindowHeight; 909 int childWidthMeasureSpec; 910 int childHeightMeasureSpec; 911 912 final View.AttachInfo attachInfo = mAttachInfo; 913 914 final int viewVisibility = getHostVisibility(); 915 boolean viewVisibilityChanged = mViewVisibility != viewVisibility 916 || mNewSurfaceNeeded; 917 918 WindowManager.LayoutParams params = null; 919 if (mWindowAttributesChanged) { 920 mWindowAttributesChanged = false; 921 surfaceChanged = true; 922 params = lp; 923 } 924 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 925 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) { 926 params = lp; 927 mFullRedrawNeeded = true; 928 mLayoutRequested = true; 929 if (mLastInCompatMode) { 930 params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 931 mLastInCompatMode = false; 932 } else { 933 params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 934 mLastInCompatMode = true; 935 } 936 } 937 938 mWindowAttributesChangesFlag = 0; 939 940 Rect frame = mWinFrame; 941 if (mFirst) { 942 mFullRedrawNeeded = true; 943 mLayoutRequested = true; 944 945 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 946 // NOTE -- system code, won't try to do compat mode. 947 Display disp = WindowManagerImpl.getDefault().getDefaultDisplay(); 948 Point size = new Point(); 949 disp.getRealSize(size); 950 desiredWindowWidth = size.x; 951 desiredWindowHeight = size.y; 952 } else { 953 DisplayMetrics packageMetrics = 954 mView.getContext().getResources().getDisplayMetrics(); 955 desiredWindowWidth = packageMetrics.widthPixels; 956 desiredWindowHeight = packageMetrics.heightPixels; 957 } 958 959 // For the very first time, tell the view hierarchy that it 960 // is attached to the window. Note that at this point the surface 961 // object is not initialized to its backing store, but soon it 962 // will be (assuming the window is visible). 963 attachInfo.mSurface = mSurface; 964 // We used to use the following condition to choose 32 bits drawing caches: 965 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888 966 // However, windows are now always 32 bits by default, so choose 32 bits 967 attachInfo.mUse32BitDrawingCache = true; 968 attachInfo.mHasWindowFocus = false; 969 attachInfo.mWindowVisibility = viewVisibility; 970 attachInfo.mRecomputeGlobalAttributes = false; 971 attachInfo.mKeepScreenOn = false; 972 attachInfo.mSystemUiVisibility = 0; 973 viewVisibilityChanged = false; 974 mLastConfiguration.setTo(host.getResources().getConfiguration()); 975 host.dispatchAttachedToWindow(attachInfo, 0); 976 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn); 977 978 host.fitSystemWindows(mAttachInfo.mContentInsets); 979 980 } else { 981 desiredWindowWidth = frame.width(); 982 desiredWindowHeight = frame.height(); 983 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) { 984 if (DEBUG_ORIENTATION) Log.v(TAG, 985 "View " + host + " resized to: " + frame); 986 mFullRedrawNeeded = true; 987 mLayoutRequested = true; 988 windowSizeMayChange = true; 989 } 990 } 991 992 if (viewVisibilityChanged) { 993 attachInfo.mWindowVisibility = viewVisibility; 994 host.dispatchWindowVisibilityChanged(viewVisibility); 995 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) { 996 destroyHardwareResources(); 997 } 998 if (viewVisibility == View.GONE) { 999 // After making a window gone, we will count it as being 1000 // shown for the first time the next time it gets focus. 1001 mHasHadWindowFocus = false; 1002 } 1003 } 1004 1005 boolean insetsChanged = false; 1006 1007 if (mLayoutRequested && !mStopped) { 1008 // Execute enqueued actions on every layout in case a view that was detached 1009 // enqueued an action after being detached 1010 getRunQueue().executeActions(attachInfo.mHandler); 1011 1012 final Resources res = mView.getContext().getResources(); 1013 1014 if (mFirst) { 1015 // make sure touch mode code executes by setting cached value 1016 // to opposite of the added touch mode. 1017 mAttachInfo.mInTouchMode = !mAddedTouchMode; 1018 ensureTouchModeLocally(mAddedTouchMode); 1019 } else { 1020 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) { 1021 insetsChanged = true; 1022 } 1023 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) { 1024 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1025 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1026 + mAttachInfo.mVisibleInsets); 1027 } 1028 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT 1029 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) { 1030 windowSizeMayChange = true; 1031 1032 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1033 // NOTE -- system code, won't try to do compat mode. 1034 Display disp = WindowManagerImpl.getDefault().getDefaultDisplay(); 1035 Point size = new Point(); 1036 disp.getRealSize(size); 1037 desiredWindowWidth = size.x; 1038 desiredWindowHeight = size.y; 1039 } else { 1040 DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1041 desiredWindowWidth = packageMetrics.widthPixels; 1042 desiredWindowHeight = packageMetrics.heightPixels; 1043 } 1044 } 1045 } 1046 1047 // Ask host how big it wants to be 1048 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG, 1049 "Measuring " + host + " in display " + desiredWindowWidth 1050 + "x" + desiredWindowHeight + "..."); 1051 1052 boolean goodMeasure = false; 1053 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) { 1054 // On large screens, we don't want to allow dialogs to just 1055 // stretch to fill the entire width of the screen to display 1056 // one line of text. First try doing the layout at a smaller 1057 // size to see if it will fit. 1058 final DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1059 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true); 1060 int baseSize = 0; 1061 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) { 1062 baseSize = (int)mTmpValue.getDimension(packageMetrics); 1063 } 1064 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize); 1065 if (baseSize != 0 && desiredWindowWidth > baseSize) { 1066 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1067 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1068 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1069 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1070 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1071 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1072 goodMeasure = true; 1073 } else { 1074 // Didn't fit in that size... try expanding a bit. 1075 baseSize = (baseSize+desiredWindowWidth)/2; 1076 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize=" 1077 + baseSize); 1078 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1079 host.measure(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 if (DEBUG_DIALOG) Log.v(TAG, "Good!"); 1084 goodMeasure = true; 1085 } 1086 } 1087 } 1088 } 1089 1090 if (!goodMeasure) { 1091 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); 1092 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1093 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1094 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) { 1095 windowSizeMayChange = true; 1096 } 1097 } 1098 1099 if (DBG) { 1100 System.out.println("======================================"); 1101 System.out.println("performTraversals -- after measure"); 1102 host.debug(); 1103 } 1104 } 1105 1106 if (attachInfo.mRecomputeGlobalAttributes && host.mAttachInfo != null) { 1107 //Log.i(TAG, "Computing view hierarchy attributes!"); 1108 attachInfo.mRecomputeGlobalAttributes = false; 1109 boolean oldScreenOn = attachInfo.mKeepScreenOn; 1110 int oldVis = attachInfo.mSystemUiVisibility; 1111 boolean oldHasSystemUiListeners = attachInfo.mHasSystemUiListeners; 1112 attachInfo.mKeepScreenOn = false; 1113 attachInfo.mSystemUiVisibility = 0; 1114 attachInfo.mHasSystemUiListeners = false; 1115 host.dispatchCollectViewAttributes(0); 1116 if (attachInfo.mKeepScreenOn != oldScreenOn 1117 || attachInfo.mSystemUiVisibility != oldVis 1118 || attachInfo.mHasSystemUiListeners != oldHasSystemUiListeners) { 1119 params = lp; 1120 } 1121 } 1122 if (attachInfo.mForceReportNewAttributes) { 1123 attachInfo.mForceReportNewAttributes = false; 1124 params = lp; 1125 } 1126 1127 if (mFirst || attachInfo.mViewVisibilityChanged) { 1128 attachInfo.mViewVisibilityChanged = false; 1129 int resizeMode = mSoftInputMode & 1130 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST; 1131 // If we are in auto resize mode, then we need to determine 1132 // what mode to use now. 1133 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 1134 final int N = attachInfo.mScrollContainers.size(); 1135 for (int i=0; i<N; i++) { 1136 if (attachInfo.mScrollContainers.get(i).isShown()) { 1137 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; 1138 } 1139 } 1140 if (resizeMode == 0) { 1141 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN; 1142 } 1143 if ((lp.softInputMode & 1144 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) { 1145 lp.softInputMode = (lp.softInputMode & 1146 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) | 1147 resizeMode; 1148 params = lp; 1149 } 1150 } 1151 } 1152 1153 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) { 1154 if (!PixelFormat.formatHasAlpha(params.format)) { 1155 params.format = PixelFormat.TRANSLUCENT; 1156 } 1157 } 1158 1159 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange 1160 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) 1161 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT && 1162 frame.width() < desiredWindowWidth && frame.width() != mWidth) 1163 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT && 1164 frame.height() < desiredWindowHeight && frame.height() != mHeight)); 1165 1166 final boolean computesInternalInsets = 1167 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners(); 1168 1169 boolean insetsPending = false; 1170 int relayoutResult = 0; 1171 1172 if (mFirst || windowShouldResize || insetsChanged || 1173 viewVisibilityChanged || params != null) { 1174 1175 if (viewVisibility == View.VISIBLE) { 1176 // If this window is giving internal insets to the window 1177 // manager, and it is being added or changing its visibility, 1178 // then we want to first give the window manager "fake" 1179 // insets to cause it to effectively ignore the content of 1180 // the window during layout. This avoids it briefly causing 1181 // other windows to resize/move based on the raw frame of the 1182 // window, waiting until we can finish laying out this window 1183 // and get back to the window manager with the ultimately 1184 // computed insets. 1185 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged); 1186 } 1187 1188 if (mSurfaceHolder != null) { 1189 mSurfaceHolder.mSurfaceLock.lock(); 1190 mDrawingAllowed = true; 1191 } 1192 1193 boolean hwInitialized = false; 1194 boolean contentInsetsChanged = false; 1195 boolean visibleInsetsChanged; 1196 boolean hadSurface = mSurface.isValid(); 1197 1198 try { 1199 int fl = 0; 1200 if (params != null) { 1201 fl = params.flags; 1202 if (attachInfo.mKeepScreenOn) { 1203 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 1204 } 1205 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility; 1206 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners; 1207 } 1208 if (DEBUG_LAYOUT) { 1209 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" + 1210 host.getMeasuredHeight() + ", params=" + params); 1211 } 1212 1213 final int surfaceGenerationId = mSurface.getGenerationId(); 1214 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending); 1215 1216 if (params != null) { 1217 params.flags = fl; 1218 } 1219 1220 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString() 1221 + " content=" + mPendingContentInsets.toShortString() 1222 + " visible=" + mPendingVisibleInsets.toShortString() 1223 + " surface=" + mSurface); 1224 1225 if (mPendingConfiguration.seq != 0) { 1226 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: " 1227 + mPendingConfiguration); 1228 updateConfiguration(mPendingConfiguration, !mFirst); 1229 mPendingConfiguration.seq = 0; 1230 } 1231 1232 contentInsetsChanged = !mPendingContentInsets.equals( 1233 mAttachInfo.mContentInsets); 1234 visibleInsetsChanged = !mPendingVisibleInsets.equals( 1235 mAttachInfo.mVisibleInsets); 1236 if (contentInsetsChanged) { 1237 if (mWidth > 0 && mHeight > 0 && 1238 mSurface != null && mSurface.isValid() && 1239 !mAttachInfo.mTurnOffWindowResizeAnim && 1240 mAttachInfo.mHardwareRenderer != null && 1241 mAttachInfo.mHardwareRenderer.isEnabled() && 1242 mAttachInfo.mHardwareRenderer.validate() && 1243 lp != null && !PixelFormat.formatHasAlpha(lp.format)) { 1244 1245 disposeResizeBuffer(); 1246 1247 boolean completed = false; 1248 HardwareCanvas hwRendererCanvas = mAttachInfo.mHardwareRenderer.getCanvas(); 1249 HardwareCanvas layerCanvas = null; 1250 try { 1251 if (mResizeBuffer == null) { 1252 mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 1253 mWidth, mHeight, false); 1254 } else if (mResizeBuffer.getWidth() != mWidth || 1255 mResizeBuffer.getHeight() != mHeight) { 1256 mResizeBuffer.resize(mWidth, mHeight); 1257 } 1258 layerCanvas = mResizeBuffer.start(hwRendererCanvas); 1259 layerCanvas.setViewport(mWidth, mHeight); 1260 layerCanvas.onPreDraw(null); 1261 final int restoreCount = layerCanvas.save(); 1262 1263 layerCanvas.drawColor(0xff000000, PorterDuff.Mode.SRC); 1264 1265 int yoff; 1266 final boolean scrolling = mScroller != null 1267 && mScroller.computeScrollOffset(); 1268 if (scrolling) { 1269 yoff = mScroller.getCurrY(); 1270 mScroller.abortAnimation(); 1271 } else { 1272 yoff = mScrollY; 1273 } 1274 1275 layerCanvas.translate(0, -yoff); 1276 if (mTranslator != null) { 1277 mTranslator.translateCanvas(layerCanvas); 1278 } 1279 1280 mView.draw(layerCanvas); 1281 1282 mResizeBufferStartTime = SystemClock.uptimeMillis(); 1283 mResizeBufferDuration = mView.getResources().getInteger( 1284 com.android.internal.R.integer.config_mediumAnimTime); 1285 completed = true; 1286 1287 layerCanvas.restoreToCount(restoreCount); 1288 } catch (OutOfMemoryError e) { 1289 Log.w(TAG, "Not enough memory for content change anim buffer", e); 1290 } finally { 1291 if (layerCanvas != null) { 1292 layerCanvas.onPostDraw(); 1293 } 1294 if (mResizeBuffer != null) { 1295 mResizeBuffer.end(hwRendererCanvas); 1296 if (!completed) { 1297 mResizeBuffer.destroy(); 1298 mResizeBuffer = null; 1299 } 1300 } 1301 } 1302 } 1303 mAttachInfo.mContentInsets.set(mPendingContentInsets); 1304 host.fitSystemWindows(mAttachInfo.mContentInsets); 1305 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: " 1306 + mAttachInfo.mContentInsets); 1307 } 1308 if (visibleInsetsChanged) { 1309 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1310 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1311 + mAttachInfo.mVisibleInsets); 1312 } 1313 1314 if (!hadSurface) { 1315 if (mSurface.isValid()) { 1316 // If we are creating a new surface, then we need to 1317 // completely redraw it. Also, when we get to the 1318 // point of drawing it we will hold off and schedule 1319 // a new traversal instead. This is so we can tell the 1320 // window manager about all of the windows being displayed 1321 // before actually drawing them, so it can display then 1322 // all at once. 1323 newSurface = true; 1324 mFullRedrawNeeded = true; 1325 mPreviousTransparentRegion.setEmpty(); 1326 1327 if (mAttachInfo.mHardwareRenderer != null) { 1328 try { 1329 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder); 1330 } catch (Surface.OutOfResourcesException e) { 1331 Log.e(TAG, "OutOfResourcesException initializing HW surface", e); 1332 try { 1333 if (!sWindowSession.outOfMemory(mWindow)) { 1334 Slog.w(TAG, "No processes killed for memory; killing self"); 1335 Process.killProcess(Process.myPid()); 1336 } 1337 } catch (RemoteException ex) { 1338 } 1339 mLayoutRequested = true; // ask wm for a new surface next time. 1340 return; 1341 } 1342 } 1343 } 1344 } else if (!mSurface.isValid()) { 1345 // If the surface has been removed, then reset the scroll 1346 // positions. 1347 mLastScrolledFocus = null; 1348 mScrollY = mCurScrollY = 0; 1349 if (mScroller != null) { 1350 mScroller.abortAnimation(); 1351 } 1352 disposeResizeBuffer(); 1353 // Our surface is gone 1354 if (mAttachInfo.mHardwareRenderer != null && 1355 mAttachInfo.mHardwareRenderer.isEnabled()) { 1356 mAttachInfo.mHardwareRenderer.destroy(true); 1357 } 1358 } else if (surfaceGenerationId != mSurface.getGenerationId() && 1359 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) { 1360 mFullRedrawNeeded = true; 1361 try { 1362 mAttachInfo.mHardwareRenderer.updateSurface(mHolder); 1363 } catch (Surface.OutOfResourcesException e) { 1364 Log.e(TAG, "OutOfResourcesException updating HW surface", e); 1365 try { 1366 if (!sWindowSession.outOfMemory(mWindow)) { 1367 Slog.w(TAG, "No processes killed for memory; killing self"); 1368 Process.killProcess(Process.myPid()); 1369 } 1370 } catch (RemoteException ex) { 1371 } 1372 mLayoutRequested = true; // ask wm for a new surface next time. 1373 return; 1374 } 1375 } 1376 } catch (RemoteException e) { 1377 } 1378 1379 if (DEBUG_ORIENTATION) Log.v( 1380 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface); 1381 1382 attachInfo.mWindowLeft = frame.left; 1383 attachInfo.mWindowTop = frame.top; 1384 1385 // !!FIXME!! This next section handles the case where we did not get the 1386 // window size we asked for. We should avoid this by getting a maximum size from 1387 // the window session beforehand. 1388 mWidth = frame.width(); 1389 mHeight = frame.height(); 1390 1391 if (mSurfaceHolder != null) { 1392 // The app owns the surface; tell it about what is going on. 1393 if (mSurface.isValid()) { 1394 // XXX .copyFrom() doesn't work! 1395 //mSurfaceHolder.mSurface.copyFrom(mSurface); 1396 mSurfaceHolder.mSurface = mSurface; 1397 } 1398 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight); 1399 mSurfaceHolder.mSurfaceLock.unlock(); 1400 if (mSurface.isValid()) { 1401 if (!hadSurface) { 1402 mSurfaceHolder.ungetCallbacks(); 1403 1404 mIsCreating = true; 1405 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder); 1406 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1407 if (callbacks != null) { 1408 for (SurfaceHolder.Callback c : callbacks) { 1409 c.surfaceCreated(mSurfaceHolder); 1410 } 1411 } 1412 surfaceChanged = true; 1413 } 1414 if (surfaceChanged) { 1415 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder, 1416 lp.format, mWidth, mHeight); 1417 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1418 if (callbacks != null) { 1419 for (SurfaceHolder.Callback c : callbacks) { 1420 c.surfaceChanged(mSurfaceHolder, lp.format, 1421 mWidth, mHeight); 1422 } 1423 } 1424 } 1425 mIsCreating = false; 1426 } else if (hadSurface) { 1427 mSurfaceHolder.ungetCallbacks(); 1428 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1429 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder); 1430 if (callbacks != null) { 1431 for (SurfaceHolder.Callback c : callbacks) { 1432 c.surfaceDestroyed(mSurfaceHolder); 1433 } 1434 } 1435 mSurfaceHolder.mSurfaceLock.lock(); 1436 try { 1437 mSurfaceHolder.mSurface = new Surface(); 1438 } finally { 1439 mSurfaceHolder.mSurfaceLock.unlock(); 1440 } 1441 } 1442 } 1443 1444 if (mAttachInfo.mHardwareRenderer != null && 1445 mAttachInfo.mHardwareRenderer.isEnabled()) { 1446 if (hwInitialized || windowShouldResize || 1447 mWidth != mAttachInfo.mHardwareRenderer.getWidth() || 1448 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) { 1449 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight); 1450 if (!hwInitialized) { 1451 mAttachInfo.mHardwareRenderer.invalidate(mHolder); 1452 } 1453 } 1454 } 1455 1456 if (!mStopped) { 1457 boolean focusChangedDueToTouchMode = ensureTouchModeLocally( 1458 (relayoutResult&WindowManagerImpl.RELAYOUT_RES_IN_TOUCH_MODE) != 0); 1459 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth() 1460 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) { 1461 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); 1462 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height); 1463 1464 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth=" 1465 + mWidth + " measuredWidth=" + host.getMeasuredWidth() 1466 + " mHeight=" + mHeight 1467 + " measuredHeight=" + host.getMeasuredHeight() 1468 + " coveredInsetsChanged=" + contentInsetsChanged); 1469 1470 // Ask host how big it wants to be 1471 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1472 1473 // Implementation of weights from WindowManager.LayoutParams 1474 // We just grow the dimensions as needed and re-measure if 1475 // needs be 1476 int width = host.getMeasuredWidth(); 1477 int height = host.getMeasuredHeight(); 1478 boolean measureAgain = false; 1479 1480 if (lp.horizontalWeight > 0.0f) { 1481 width += (int) ((mWidth - width) * lp.horizontalWeight); 1482 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, 1483 MeasureSpec.EXACTLY); 1484 measureAgain = true; 1485 } 1486 if (lp.verticalWeight > 0.0f) { 1487 height += (int) ((mHeight - height) * lp.verticalWeight); 1488 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, 1489 MeasureSpec.EXACTLY); 1490 measureAgain = true; 1491 } 1492 1493 if (measureAgain) { 1494 if (DEBUG_LAYOUT) Log.v(TAG, 1495 "And hey let's measure once more: width=" + width 1496 + " height=" + height); 1497 host.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1498 } 1499 1500 mLayoutRequested = true; 1501 } 1502 } 1503 } 1504 1505 final boolean didLayout = mLayoutRequested && !mStopped; 1506 boolean triggerGlobalLayoutListener = didLayout 1507 || attachInfo.mRecomputeGlobalAttributes; 1508 if (didLayout) { 1509 mLayoutRequested = false; 1510 mScrollMayChange = true; 1511 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v( 1512 TAG, "Laying out " + host + " to (" + 1513 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")"); 1514 long startTime = 0L; 1515 if (ViewDebug.DEBUG_PROFILE_LAYOUT) { 1516 startTime = SystemClock.elapsedRealtime(); 1517 } 1518 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 1519 1520 if (false && ViewDebug.consistencyCheckEnabled) { 1521 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) { 1522 throw new IllegalStateException("The view hierarchy is an inconsistent state," 1523 + "please refer to the logs with the tag " 1524 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation."); 1525 } 1526 } 1527 1528 if (ViewDebug.DEBUG_PROFILE_LAYOUT) { 1529 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime); 1530 } 1531 1532 // By this point all views have been sized and positionned 1533 // We can compute the transparent area 1534 1535 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) { 1536 // start out transparent 1537 // TODO: AVOID THAT CALL BY CACHING THE RESULT? 1538 host.getLocationInWindow(mTmpLocation); 1539 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1], 1540 mTmpLocation[0] + host.mRight - host.mLeft, 1541 mTmpLocation[1] + host.mBottom - host.mTop); 1542 1543 host.gatherTransparentRegion(mTransparentRegion); 1544 if (mTranslator != null) { 1545 mTranslator.translateRegionInWindowToScreen(mTransparentRegion); 1546 } 1547 1548 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) { 1549 mPreviousTransparentRegion.set(mTransparentRegion); 1550 // reconfigure window manager 1551 try { 1552 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion); 1553 } catch (RemoteException e) { 1554 } 1555 } 1556 } 1557 1558 if (DBG) { 1559 System.out.println("======================================"); 1560 System.out.println("performTraversals -- after setFrame"); 1561 host.debug(); 1562 } 1563 } 1564 1565 if (triggerGlobalLayoutListener) { 1566 attachInfo.mRecomputeGlobalAttributes = false; 1567 attachInfo.mTreeObserver.dispatchOnGlobalLayout(); 1568 1569 if (AccessibilityManager.getInstance(host.mContext).isEnabled()) { 1570 postSendWindowContentChangedCallback(); 1571 } 1572 } 1573 1574 if (computesInternalInsets) { 1575 // Clear the original insets. 1576 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets; 1577 insets.reset(); 1578 1579 // Compute new insets in place. 1580 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets); 1581 1582 // Tell the window manager. 1583 if (insetsPending || !mLastGivenInsets.equals(insets)) { 1584 mLastGivenInsets.set(insets); 1585 1586 // Translate insets to screen coordinates if needed. 1587 final Rect contentInsets; 1588 final Rect visibleInsets; 1589 final Region touchableRegion; 1590 if (mTranslator != null) { 1591 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets); 1592 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets); 1593 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion); 1594 } else { 1595 contentInsets = insets.contentInsets; 1596 visibleInsets = insets.visibleInsets; 1597 touchableRegion = insets.touchableRegion; 1598 } 1599 1600 try { 1601 sWindowSession.setInsets(mWindow, insets.mTouchableInsets, 1602 contentInsets, visibleInsets, touchableRegion); 1603 } catch (RemoteException e) { 1604 } 1605 } 1606 } 1607 1608 if (mFirst) { 1609 // handle first focus request 1610 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()=" 1611 + mView.hasFocus()); 1612 if (mView != null) { 1613 if (!mView.hasFocus()) { 1614 mView.requestFocus(View.FOCUS_FORWARD); 1615 mFocusedView = mRealFocusedView = mView.findFocus(); 1616 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view=" 1617 + mFocusedView); 1618 } else { 1619 mRealFocusedView = mView.findFocus(); 1620 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view=" 1621 + mRealFocusedView); 1622 } 1623 } 1624 } 1625 1626 mFirst = false; 1627 mWillDrawSoon = false; 1628 mNewSurfaceNeeded = false; 1629 mViewVisibility = viewVisibility; 1630 1631 if (mAttachInfo.mHasWindowFocus) { 1632 final boolean imTarget = WindowManager.LayoutParams 1633 .mayUseInputMethod(mWindowAttributes.flags); 1634 if (imTarget != mLastWasImTarget) { 1635 mLastWasImTarget = imTarget; 1636 InputMethodManager imm = InputMethodManager.peekInstance(); 1637 if (imm != null && imTarget) { 1638 imm.startGettingWindowFocus(mView); 1639 imm.onWindowFocus(mView, mView.findFocus(), 1640 mWindowAttributes.softInputMode, 1641 !mHasHadWindowFocus, mWindowAttributes.flags); 1642 } 1643 } 1644 } 1645 1646 // Remember if we must report the next draw. 1647 if ((relayoutResult & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) { 1648 mReportNextDraw = true; 1649 } 1650 1651 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() || 1652 viewVisibility != View.VISIBLE; 1653 1654 if (!cancelDraw && !newSurface) { 1655 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1656 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1657 mPendingTransitions.get(i).startChangingAnimations(); 1658 } 1659 mPendingTransitions.clear(); 1660 } 1661 1662 performDraw(); 1663 } else { 1664 // End any pending transitions on this non-visible window 1665 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1666 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1667 mPendingTransitions.get(i).endChangingAnimations(); 1668 } 1669 mPendingTransitions.clear(); 1670 } 1671 1672 if (viewVisibility == View.VISIBLE) { 1673 // Try again 1674 scheduleTraversals(); 1675 } 1676 } 1677 } 1678 1679 public void requestTransparentRegion(View child) { 1680 // the test below should not fail unless someone is messing with us 1681 checkThread(); 1682 if (mView == child) { 1683 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS; 1684 // Need to make sure we re-evaluate the window attributes next 1685 // time around, to ensure the window has the correct format. 1686 mWindowAttributesChanged = true; 1687 mWindowAttributesChangesFlag = 0; 1688 requestLayout(); 1689 } 1690 } 1691 1692 /** 1693 * Figures out the measure spec for the root view in a window based on it's 1694 * layout params. 1695 * 1696 * @param windowSize 1697 * The available width or height of the window 1698 * 1699 * @param rootDimension 1700 * The layout params for one dimension (width or height) of the 1701 * window. 1702 * 1703 * @return The measure spec to use to measure the root view. 1704 */ 1705 private int getRootMeasureSpec(int windowSize, int rootDimension) { 1706 int measureSpec; 1707 switch (rootDimension) { 1708 1709 case ViewGroup.LayoutParams.MATCH_PARENT: 1710 // Window can't resize. Force root view to be windowSize. 1711 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); 1712 break; 1713 case ViewGroup.LayoutParams.WRAP_CONTENT: 1714 // Window can resize. Set max size for root view. 1715 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST); 1716 break; 1717 default: 1718 // Window wants to be an exact size. Force root view to be that size. 1719 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY); 1720 break; 1721 } 1722 return measureSpec; 1723 } 1724 1725 int mHardwareYOffset; 1726 int mResizeAlpha; 1727 final Paint mResizePaint = new Paint(); 1728 1729 public void onHardwarePreDraw(HardwareCanvas canvas) { 1730 canvas.translate(0, -mHardwareYOffset); 1731 } 1732 1733 public void onHardwarePostDraw(HardwareCanvas canvas) { 1734 if (mResizeBuffer != null) { 1735 mResizePaint.setAlpha(mResizeAlpha); 1736 canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint); 1737 } 1738 } 1739 1740 /** 1741 * @hide 1742 */ 1743 void outputDisplayList(View view) { 1744 if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) { 1745 DisplayList displayList = view.getDisplayList(); 1746 if (displayList != null) { 1747 mAttachInfo.mHardwareCanvas.outputDisplayList(displayList); 1748 } 1749 } 1750 } 1751 1752 /** 1753 * @see #PROPERTY_PROFILE_RENDERING 1754 */ 1755 private void profileRendering(boolean enabled) { 1756 if (mProfileRendering) { 1757 mRenderProfilingEnabled = enabled; 1758 if (mRenderProfiler == null) { 1759 mRenderProfiler = new Thread(new Runnable() { 1760 @Override 1761 public void run() { 1762 Log.d(TAG, "Starting profiling thread"); 1763 while (mRenderProfilingEnabled) { 1764 mAttachInfo.mHandler.post(new Runnable() { 1765 @Override 1766 public void run() { 1767 mDirty.set(0, 0, mWidth, mHeight); 1768 scheduleTraversals(); 1769 } 1770 }); 1771 try { 1772 // TODO: This should use vsync when we get an API 1773 Thread.sleep(15); 1774 } catch (InterruptedException e) { 1775 Log.d(TAG, "Exiting profiling thread"); 1776 } 1777 } 1778 } 1779 }, "Rendering Profiler"); 1780 mRenderProfiler.start(); 1781 } else { 1782 mRenderProfiler.interrupt(); 1783 mRenderProfiler = null; 1784 } 1785 } 1786 } 1787 1788 /** 1789 * Called from draw() when DEBUG_FPS is enabled 1790 */ 1791 private void trackFPS() { 1792 // Tracks frames per second drawn. First value in a series of draws may be bogus 1793 // because it down not account for the intervening idle time 1794 long nowTime = System.currentTimeMillis(); 1795 if (mFpsStartTime < 0) { 1796 mFpsStartTime = mFpsPrevTime = nowTime; 1797 mFpsNumFrames = 0; 1798 } else { 1799 ++mFpsNumFrames; 1800 String thisHash = Integer.toHexString(System.identityHashCode(this)); 1801 long frameTime = nowTime - mFpsPrevTime; 1802 long totalTime = nowTime - mFpsStartTime; 1803 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime); 1804 mFpsPrevTime = nowTime; 1805 if (totalTime > 1000) { 1806 float fps = (float) mFpsNumFrames * 1000 / totalTime; 1807 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps); 1808 mFpsStartTime = nowTime; 1809 mFpsNumFrames = 0; 1810 } 1811 } 1812 } 1813 1814 private void performDraw() { 1815 final long drawStartTime; 1816 if (ViewDebug.DEBUG_LATENCY) { 1817 drawStartTime = System.nanoTime(); 1818 if (mLastDrawFinishedTimeNanos != 0) { 1819 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting draw(); it has been " 1820 + ((drawStartTime - mLastDrawFinishedTimeNanos) * 0.000001f) 1821 + "ms since the last draw finished."); 1822 } else { 1823 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "Starting draw()."); 1824 } 1825 } 1826 1827 final boolean fullRedrawNeeded = mFullRedrawNeeded; 1828 mFullRedrawNeeded = false; 1829 draw(fullRedrawNeeded); 1830 1831 if (ViewDebug.DEBUG_LATENCY) { 1832 long now = System.nanoTime(); 1833 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "performDraw() took " 1834 + ((now - drawStartTime) * 0.000001f) 1835 + "ms."); 1836 mLastDrawFinishedTimeNanos = now; 1837 } 1838 1839 if (mReportNextDraw) { 1840 mReportNextDraw = false; 1841 1842 if (LOCAL_LOGV) { 1843 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle()); 1844 } 1845 if (mSurfaceHolder != null && mSurface.isValid()) { 1846 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder); 1847 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1848 if (callbacks != null) { 1849 for (SurfaceHolder.Callback c : callbacks) { 1850 if (c instanceof SurfaceHolder.Callback2) { 1851 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 1852 mSurfaceHolder); 1853 } 1854 } 1855 } 1856 } 1857 try { 1858 sWindowSession.finishDrawing(mWindow); 1859 } catch (RemoteException e) { 1860 } 1861 } 1862 } 1863 1864 private void draw(boolean fullRedrawNeeded) { 1865 Surface surface = mSurface; 1866 if (surface == null || !surface.isValid()) { 1867 return; 1868 } 1869 1870 if (DEBUG_FPS) { 1871 trackFPS(); 1872 } 1873 1874 if (!sFirstDrawComplete) { 1875 synchronized (sFirstDrawHandlers) { 1876 sFirstDrawComplete = true; 1877 final int count = sFirstDrawHandlers.size(); 1878 for (int i = 0; i< count; i++) { 1879 post(sFirstDrawHandlers.get(i)); 1880 } 1881 } 1882 } 1883 1884 scrollToRectOrFocus(null, false); 1885 1886 if (mAttachInfo.mViewScrollChanged) { 1887 mAttachInfo.mViewScrollChanged = false; 1888 mAttachInfo.mTreeObserver.dispatchOnScrollChanged(); 1889 } 1890 1891 int yoff; 1892 boolean animating = mScroller != null && mScroller.computeScrollOffset(); 1893 if (animating) { 1894 yoff = mScroller.getCurrY(); 1895 } else { 1896 yoff = mScrollY; 1897 } 1898 if (mCurScrollY != yoff) { 1899 mCurScrollY = yoff; 1900 fullRedrawNeeded = true; 1901 } 1902 1903 final float appScale = mAttachInfo.mApplicationScale; 1904 final boolean scalingRequired = mAttachInfo.mScalingRequired; 1905 1906 int resizeAlpha = 0; 1907 if (mResizeBuffer != null) { 1908 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime; 1909 if (deltaTime < mResizeBufferDuration) { 1910 float amt = deltaTime/(float) mResizeBufferDuration; 1911 amt = mResizeInterpolator.getInterpolation(amt); 1912 animating = true; 1913 resizeAlpha = 255 - (int)(amt*255); 1914 } else { 1915 disposeResizeBuffer(); 1916 } 1917 } 1918 1919 final Rect dirty = mDirty; 1920 if (mSurfaceHolder != null) { 1921 // The app owns the surface, we won't draw. 1922 dirty.setEmpty(); 1923 if (animating) { 1924 if (mScroller != null) { 1925 mScroller.abortAnimation(); 1926 } 1927 disposeResizeBuffer(); 1928 } 1929 return; 1930 } 1931 1932 if (fullRedrawNeeded) { 1933 mAttachInfo.mIgnoreDirtyState = true; 1934 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 1935 } 1936 1937 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 1938 Log.v(TAG, "Draw " + mView + "/" 1939 + mWindowAttributes.getTitle() 1940 + ": dirty={" + dirty.left + "," + dirty.top 1941 + "," + dirty.right + "," + dirty.bottom + "} surface=" 1942 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" + 1943 appScale + ", width=" + mWidth + ", height=" + mHeight); 1944 } 1945 1946 if (!dirty.isEmpty() || mIsAnimating) { 1947 if (mAttachInfo.mHardwareRenderer != null 1948 && mAttachInfo.mHardwareRenderer.isEnabled()) { 1949 // Draw with hardware renderer. 1950 mIsAnimating = false; 1951 mHardwareYOffset = yoff; 1952 mResizeAlpha = resizeAlpha; 1953 1954 mCurrentDirty.set(dirty); 1955 mCurrentDirty.union(mPreviousDirty); 1956 mPreviousDirty.set(dirty); 1957 dirty.setEmpty(); 1958 1959 if (mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, 1960 animating ? null : mCurrentDirty)) { 1961 mPreviousDirty.set(0, 0, mWidth, mHeight); 1962 } 1963 } else { 1964 // Draw with software renderer. 1965 Canvas canvas; 1966 try { 1967 int left = dirty.left; 1968 int top = dirty.top; 1969 int right = dirty.right; 1970 int bottom = dirty.bottom; 1971 1972 final long lockCanvasStartTime; 1973 if (ViewDebug.DEBUG_LATENCY) { 1974 lockCanvasStartTime = System.nanoTime(); 1975 } 1976 1977 canvas = mSurface.lockCanvas(dirty); 1978 1979 if (ViewDebug.DEBUG_LATENCY) { 1980 long now = System.nanoTime(); 1981 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- lockCanvas() took " 1982 + ((now - lockCanvasStartTime) * 0.000001f) + "ms"); 1983 } 1984 1985 if (left != dirty.left || top != dirty.top || right != dirty.right || 1986 bottom != dirty.bottom) { 1987 mAttachInfo.mIgnoreDirtyState = true; 1988 } 1989 1990 // TODO: Do this in native 1991 canvas.setDensity(mDensity); 1992 } catch (Surface.OutOfResourcesException e) { 1993 Log.e(TAG, "OutOfResourcesException locking surface", e); 1994 try { 1995 if (!sWindowSession.outOfMemory(mWindow)) { 1996 Slog.w(TAG, "No processes killed for memory; killing self"); 1997 Process.killProcess(Process.myPid()); 1998 } 1999 } catch (RemoteException ex) { 2000 } 2001 mLayoutRequested = true; // ask wm for a new surface next time. 2002 return; 2003 } catch (IllegalArgumentException e) { 2004 Log.e(TAG, "IllegalArgumentException locking surface", e); 2005 // Don't assume this is due to out of memory, it could be 2006 // something else, and if it is something else then we could 2007 // kill stuff (or ourself) for no reason. 2008 mLayoutRequested = true; // ask wm for a new surface next time. 2009 return; 2010 } 2011 2012 try { 2013 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2014 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2015 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2016 //canvas.drawARGB(255, 255, 0, 0); 2017 } 2018 2019 long startTime = 0L; 2020 if (ViewDebug.DEBUG_PROFILE_DRAWING) { 2021 startTime = SystemClock.elapsedRealtime(); 2022 } 2023 2024 // If this bitmap's format includes an alpha channel, we 2025 // need to clear it before drawing so that the child will 2026 // properly re-composite its drawing on a transparent 2027 // background. This automatically respects the clip/dirty region 2028 // or 2029 // If we are applying an offset, we need to clear the area 2030 // where the offset doesn't appear to avoid having garbage 2031 // left in the blank areas. 2032 if (!canvas.isOpaque() || yoff != 0) { 2033 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2034 } 2035 2036 dirty.setEmpty(); 2037 mIsAnimating = false; 2038 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis(); 2039 mView.mPrivateFlags |= View.DRAWN; 2040 2041 if (DEBUG_DRAW) { 2042 Context cxt = mView.getContext(); 2043 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2044 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2045 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2046 } 2047 try { 2048 canvas.translate(0, -yoff); 2049 if (mTranslator != null) { 2050 mTranslator.translateCanvas(canvas); 2051 } 2052 canvas.setScreenDensity(scalingRequired 2053 ? DisplayMetrics.DENSITY_DEVICE : 0); 2054 mAttachInfo.mSetIgnoreDirtyState = false; 2055 2056 final long drawStartTime; 2057 if (ViewDebug.DEBUG_LATENCY) { 2058 drawStartTime = System.nanoTime(); 2059 } 2060 2061 mView.draw(canvas); 2062 2063 if (ViewDebug.DEBUG_LATENCY) { 2064 long now = System.nanoTime(); 2065 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- draw() took " 2066 + ((now - drawStartTime) * 0.000001f) + "ms"); 2067 } 2068 } finally { 2069 if (!mAttachInfo.mSetIgnoreDirtyState) { 2070 // Only clear the flag if it was not set during the mView.draw() call 2071 mAttachInfo.mIgnoreDirtyState = false; 2072 } 2073 } 2074 2075 if (false && ViewDebug.consistencyCheckEnabled) { 2076 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING); 2077 } 2078 2079 if (ViewDebug.DEBUG_PROFILE_DRAWING) { 2080 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime); 2081 } 2082 } finally { 2083 final long unlockCanvasAndPostStartTime; 2084 if (ViewDebug.DEBUG_LATENCY) { 2085 unlockCanvasAndPostStartTime = System.nanoTime(); 2086 } 2087 2088 surface.unlockCanvasAndPost(canvas); 2089 2090 if (ViewDebug.DEBUG_LATENCY) { 2091 long now = System.nanoTime(); 2092 Log.d(ViewDebug.DEBUG_LATENCY_TAG, "- unlockCanvasAndPost() took " 2093 + ((now - unlockCanvasAndPostStartTime) * 0.000001f) + "ms"); 2094 } 2095 2096 if (LOCAL_LOGV) { 2097 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2098 } 2099 } 2100 } 2101 } 2102 2103 if (animating) { 2104 mFullRedrawNeeded = true; 2105 scheduleTraversals(); 2106 } 2107 } 2108 2109 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2110 final View.AttachInfo attachInfo = mAttachInfo; 2111 final Rect ci = attachInfo.mContentInsets; 2112 final Rect vi = attachInfo.mVisibleInsets; 2113 int scrollY = 0; 2114 boolean handled = false; 2115 2116 if (vi.left > ci.left || vi.top > ci.top 2117 || vi.right > ci.right || vi.bottom > ci.bottom) { 2118 // We'll assume that we aren't going to change the scroll 2119 // offset, since we want to avoid that unless it is actually 2120 // going to make the focus visible... otherwise we scroll 2121 // all over the place. 2122 scrollY = mScrollY; 2123 // We can be called for two different situations: during a draw, 2124 // to update the scroll position if the focus has changed (in which 2125 // case 'rectangle' is null), or in response to a 2126 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2127 // is non-null and we just want to scroll to whatever that 2128 // rectangle is). 2129 View focus = mRealFocusedView; 2130 2131 // When in touch mode, focus points to the previously focused view, 2132 // which may have been removed from the view hierarchy. The following 2133 // line checks whether the view is still in our hierarchy. 2134 if (focus == null || focus.mAttachInfo != mAttachInfo) { 2135 mRealFocusedView = null; 2136 return false; 2137 } 2138 2139 if (focus != mLastScrolledFocus) { 2140 // If the focus has changed, then ignore any requests to scroll 2141 // to a rectangle; first we want to make sure the entire focus 2142 // view is visible. 2143 rectangle = null; 2144 } 2145 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2146 + " rectangle=" + rectangle + " ci=" + ci 2147 + " vi=" + vi); 2148 if (focus == mLastScrolledFocus && !mScrollMayChange 2149 && rectangle == null) { 2150 // Optimization: if the focus hasn't changed since last 2151 // time, and no layout has happened, then just leave things 2152 // as they are. 2153 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2154 + mScrollY + " vi=" + vi.toShortString()); 2155 } else if (focus != null) { 2156 // We need to determine if the currently focused view is 2157 // within the visible part of the window and, if not, apply 2158 // a pan so it can be seen. 2159 mLastScrolledFocus = focus; 2160 mScrollMayChange = false; 2161 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2162 // Try to find the rectangle from the focus view. 2163 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2164 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2165 + mView.getWidth() + " h=" + mView.getHeight() 2166 + " ci=" + ci.toShortString() 2167 + " vi=" + vi.toShortString()); 2168 if (rectangle == null) { 2169 focus.getFocusedRect(mTempRect); 2170 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2171 + ": focusRect=" + mTempRect.toShortString()); 2172 if (mView instanceof ViewGroup) { 2173 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2174 focus, mTempRect); 2175 } 2176 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2177 "Focus in window: focusRect=" 2178 + mTempRect.toShortString() 2179 + " visRect=" + mVisRect.toShortString()); 2180 } else { 2181 mTempRect.set(rectangle); 2182 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2183 "Request scroll to rect: " 2184 + mTempRect.toShortString() 2185 + " visRect=" + mVisRect.toShortString()); 2186 } 2187 if (mTempRect.intersect(mVisRect)) { 2188 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2189 "Focus window visible rect: " 2190 + mTempRect.toShortString()); 2191 if (mTempRect.height() > 2192 (mView.getHeight()-vi.top-vi.bottom)) { 2193 // If the focus simply is not going to fit, then 2194 // best is probably just to leave things as-is. 2195 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2196 "Too tall; leaving scrollY=" + scrollY); 2197 } else if ((mTempRect.top-scrollY) < vi.top) { 2198 scrollY -= vi.top - (mTempRect.top-scrollY); 2199 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2200 "Top covered; scrollY=" + scrollY); 2201 } else if ((mTempRect.bottom-scrollY) 2202 > (mView.getHeight()-vi.bottom)) { 2203 scrollY += (mTempRect.bottom-scrollY) 2204 - (mView.getHeight()-vi.bottom); 2205 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2206 "Bottom covered; scrollY=" + scrollY); 2207 } 2208 handled = true; 2209 } 2210 } 2211 } 2212 } 2213 2214 if (scrollY != mScrollY) { 2215 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2216 + mScrollY + " , new=" + scrollY); 2217 if (!immediate && mResizeBuffer == null) { 2218 if (mScroller == null) { 2219 mScroller = new Scroller(mView.getContext()); 2220 } 2221 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2222 } else if (mScroller != null) { 2223 mScroller.abortAnimation(); 2224 } 2225 mScrollY = scrollY; 2226 } 2227 2228 return handled; 2229 } 2230 2231 public void requestChildFocus(View child, View focused) { 2232 checkThread(); 2233 2234 if (DEBUG_INPUT_RESIZE) { 2235 Log.v(TAG, "Request child focus: focus now " + focused); 2236 } 2237 2238 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused); 2239 scheduleTraversals(); 2240 2241 mFocusedView = mRealFocusedView = focused; 2242 } 2243 2244 public void clearChildFocus(View child) { 2245 checkThread(); 2246 2247 if (DEBUG_INPUT_RESIZE) { 2248 Log.v(TAG, "Clearing child focus"); 2249 } 2250 2251 mOldFocusedView = mFocusedView; 2252 2253 // Invoke the listener only if there is no view to take focus 2254 if (focusSearch(null, View.FOCUS_FORWARD) == null) { 2255 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null); 2256 } 2257 2258 mFocusedView = mRealFocusedView = null; 2259 } 2260 2261 public void focusableViewAvailable(View v) { 2262 checkThread(); 2263 2264 if (mView != null) { 2265 if (!mView.hasFocus()) { 2266 v.requestFocus(); 2267 } else { 2268 // the one case where will transfer focus away from the current one 2269 // is if the current view is a view group that prefers to give focus 2270 // to its children first AND the view is a descendant of it. 2271 mFocusedView = mView.findFocus(); 2272 boolean descendantsHaveDibsOnFocus = 2273 (mFocusedView instanceof ViewGroup) && 2274 (((ViewGroup) mFocusedView).getDescendantFocusability() == 2275 ViewGroup.FOCUS_AFTER_DESCENDANTS); 2276 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) { 2277 // If a view gets the focus, the listener will be invoked from requestChildFocus() 2278 v.requestFocus(); 2279 } 2280 } 2281 } 2282 } 2283 2284 public void recomputeViewAttributes(View child) { 2285 checkThread(); 2286 if (mView == child) { 2287 mAttachInfo.mRecomputeGlobalAttributes = true; 2288 if (!mWillDrawSoon) { 2289 scheduleTraversals(); 2290 } 2291 } 2292 } 2293 2294 void dispatchDetachedFromWindow() { 2295 if (mView != null && mView.mAttachInfo != null) { 2296 if (mAttachInfo.mHardwareRenderer != null && 2297 mAttachInfo.mHardwareRenderer.isEnabled()) { 2298 mAttachInfo.mHardwareRenderer.validate(); 2299 } 2300 mView.dispatchDetachedFromWindow(); 2301 } 2302 2303 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2304 mAccessibilityManager.removeAccessibilityStateChangeListener( 2305 mAccessibilityInteractionConnectionManager); 2306 removeSendWindowContentChangedCallback(); 2307 2308 mView = null; 2309 mAttachInfo.mRootView = null; 2310 mAttachInfo.mSurface = null; 2311 2312 destroyHardwareRenderer(); 2313 2314 mSurface.release(); 2315 2316 if (mInputQueueCallback != null && mInputQueue != null) { 2317 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2318 mInputQueueCallback = null; 2319 mInputQueue = null; 2320 } else if (mInputEventReceiver != null) { 2321 mInputEventReceiver.dispose(); 2322 mInputEventReceiver = null; 2323 } 2324 try { 2325 sWindowSession.remove(mWindow); 2326 } catch (RemoteException e) { 2327 } 2328 2329 // Dispose the input channel after removing the window so the Window Manager 2330 // doesn't interpret the input channel being closed as an abnormal termination. 2331 if (mInputChannel != null) { 2332 mInputChannel.dispose(); 2333 mInputChannel = null; 2334 } 2335 2336 mChoreographer.removeOnDrawListener(this); 2337 } 2338 2339 void updateConfiguration(Configuration config, boolean force) { 2340 if (DEBUG_CONFIGURATION) Log.v(TAG, 2341 "Applying new config to window " 2342 + mWindowAttributes.getTitle() 2343 + ": " + config); 2344 2345 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded(); 2346 if (ci != null) { 2347 config = new Configuration(config); 2348 ci.applyToConfiguration(config); 2349 } 2350 2351 synchronized (sConfigCallbacks) { 2352 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2353 sConfigCallbacks.get(i).onConfigurationChanged(config); 2354 } 2355 } 2356 if (mView != null) { 2357 // At this point the resources have been updated to 2358 // have the most recent config, whatever that is. Use 2359 // the on in them which may be newer. 2360 config = mView.getResources().getConfiguration(); 2361 if (force || mLastConfiguration.diff(config) != 0) { 2362 mLastConfiguration.setTo(config); 2363 mView.dispatchConfigurationChanged(config); 2364 } 2365 } 2366 } 2367 2368 /** 2369 * Return true if child is an ancestor of parent, (or equal to the parent). 2370 */ 2371 private static boolean isViewDescendantOf(View child, View parent) { 2372 if (child == parent) { 2373 return true; 2374 } 2375 2376 final ViewParent theParent = child.getParent(); 2377 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2378 } 2379 2380 private static void forceLayout(View view) { 2381 view.forceLayout(); 2382 if (view instanceof ViewGroup) { 2383 ViewGroup group = (ViewGroup) view; 2384 final int count = group.getChildCount(); 2385 for (int i = 0; i < count; i++) { 2386 forceLayout(group.getChildAt(i)); 2387 } 2388 } 2389 } 2390 2391 public final static int DIE = 1001; 2392 public final static int RESIZED = 1002; 2393 public final static int RESIZED_REPORT = 1003; 2394 public final static int WINDOW_FOCUS_CHANGED = 1004; 2395 public final static int DISPATCH_KEY = 1005; 2396 public final static int DISPATCH_APP_VISIBILITY = 1008; 2397 public final static int DISPATCH_GET_NEW_SURFACE = 1009; 2398 public final static int IME_FINISHED_EVENT = 1010; 2399 public final static int DISPATCH_KEY_FROM_IME = 1011; 2400 public final static int FINISH_INPUT_CONNECTION = 1012; 2401 public final static int CHECK_FOCUS = 1013; 2402 public final static int CLOSE_SYSTEM_DIALOGS = 1014; 2403 public final static int DISPATCH_DRAG_EVENT = 1015; 2404 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016; 2405 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017; 2406 public final static int DISPATCH_GENERIC_MOTION = 1018; 2407 public final static int UPDATE_CONFIGURATION = 1019; 2408 public final static int DO_PERFORM_ACCESSIBILITY_ACTION = 1020; 2409 public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID = 1021; 2410 public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID = 1022; 2411 public final static int DO_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT = 1023; 2412 public final static int DO_PROCESS_INPUT_EVENTS = 1024; 2413 2414 @Override 2415 public String getMessageName(Message message) { 2416 switch (message.what) { 2417 case DIE: 2418 return "DIE"; 2419 case RESIZED: 2420 return "RESIZED"; 2421 case RESIZED_REPORT: 2422 return "RESIZED_REPORT"; 2423 case WINDOW_FOCUS_CHANGED: 2424 return "WINDOW_FOCUS_CHANGED"; 2425 case DISPATCH_KEY: 2426 return "DISPATCH_KEY"; 2427 case DISPATCH_APP_VISIBILITY: 2428 return "DISPATCH_APP_VISIBILITY"; 2429 case DISPATCH_GET_NEW_SURFACE: 2430 return "DISPATCH_GET_NEW_SURFACE"; 2431 case IME_FINISHED_EVENT: 2432 return "IME_FINISHED_EVENT"; 2433 case DISPATCH_KEY_FROM_IME: 2434 return "DISPATCH_KEY_FROM_IME"; 2435 case FINISH_INPUT_CONNECTION: 2436 return "FINISH_INPUT_CONNECTION"; 2437 case CHECK_FOCUS: 2438 return "CHECK_FOCUS"; 2439 case CLOSE_SYSTEM_DIALOGS: 2440 return "CLOSE_SYSTEM_DIALOGS"; 2441 case DISPATCH_DRAG_EVENT: 2442 return "DISPATCH_DRAG_EVENT"; 2443 case DISPATCH_DRAG_LOCATION_EVENT: 2444 return "DISPATCH_DRAG_LOCATION_EVENT"; 2445 case DISPATCH_SYSTEM_UI_VISIBILITY: 2446 return "DISPATCH_SYSTEM_UI_VISIBILITY"; 2447 case DISPATCH_GENERIC_MOTION: 2448 return "DISPATCH_GENERIC_MOTION"; 2449 case UPDATE_CONFIGURATION: 2450 return "UPDATE_CONFIGURATION"; 2451 case DO_PERFORM_ACCESSIBILITY_ACTION: 2452 return "DO_PERFORM_ACCESSIBILITY_ACTION"; 2453 case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID: 2454 return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID"; 2455 case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID: 2456 return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID"; 2457 case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT: 2458 return "DO_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT"; 2459 case DO_PROCESS_INPUT_EVENTS: 2460 return "DO_PROCESS_INPUT_EVENTS"; 2461 } 2462 return super.getMessageName(message); 2463 } 2464 2465 @Override 2466 public void handleMessage(Message msg) { 2467 switch (msg.what) { 2468 case View.AttachInfo.INVALIDATE_MSG: 2469 ((View) msg.obj).invalidate(); 2470 break; 2471 case View.AttachInfo.INVALIDATE_RECT_MSG: 2472 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 2473 info.target.invalidate(info.left, info.top, info.right, info.bottom); 2474 info.release(); 2475 break; 2476 case IME_FINISHED_EVENT: 2477 handleImeFinishedEvent(msg.arg1, msg.arg2 != 0); 2478 break; 2479 case DO_PROCESS_INPUT_EVENTS: 2480 mProcessInputEventsScheduled = false; 2481 doProcessInputEvents(); 2482 break; 2483 case DISPATCH_APP_VISIBILITY: 2484 handleAppVisibility(msg.arg1 != 0); 2485 break; 2486 case DISPATCH_GET_NEW_SURFACE: 2487 handleGetNewSurface(); 2488 break; 2489 case RESIZED: 2490 ResizedInfo ri = (ResizedInfo)msg.obj; 2491 2492 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2 2493 && mPendingContentInsets.equals(ri.coveredInsets) 2494 && mPendingVisibleInsets.equals(ri.visibleInsets) 2495 && ((ResizedInfo)msg.obj).newConfig == null) { 2496 break; 2497 } 2498 // fall through... 2499 case RESIZED_REPORT: 2500 if (mAdded) { 2501 Configuration config = ((ResizedInfo)msg.obj).newConfig; 2502 if (config != null) { 2503 updateConfiguration(config, false); 2504 } 2505 mWinFrame.left = 0; 2506 mWinFrame.right = msg.arg1; 2507 mWinFrame.top = 0; 2508 mWinFrame.bottom = msg.arg2; 2509 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets); 2510 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets); 2511 if (msg.what == RESIZED_REPORT) { 2512 mReportNextDraw = true; 2513 } 2514 2515 if (mView != null) { 2516 forceLayout(mView); 2517 } 2518 requestLayout(); 2519 } 2520 break; 2521 case WINDOW_FOCUS_CHANGED: { 2522 if (mAdded) { 2523 boolean hasWindowFocus = msg.arg1 != 0; 2524 mAttachInfo.mHasWindowFocus = hasWindowFocus; 2525 2526 profileRendering(hasWindowFocus); 2527 2528 if (hasWindowFocus) { 2529 boolean inTouchMode = msg.arg2 != 0; 2530 ensureTouchModeLocally(inTouchMode); 2531 2532 if (mAttachInfo.mHardwareRenderer != null && 2533 mSurface != null && mSurface.isValid()) { 2534 mFullRedrawNeeded = true; 2535 try { 2536 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2537 mHolder); 2538 } catch (Surface.OutOfResourcesException e) { 2539 Log.e(TAG, "OutOfResourcesException locking surface", e); 2540 try { 2541 if (!sWindowSession.outOfMemory(mWindow)) { 2542 Slog.w(TAG, "No processes killed for memory; killing self"); 2543 Process.killProcess(Process.myPid()); 2544 } 2545 } catch (RemoteException ex) { 2546 } 2547 // Retry in a bit. 2548 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 2549 return; 2550 } 2551 } 2552 } 2553 2554 mLastWasImTarget = WindowManager.LayoutParams 2555 .mayUseInputMethod(mWindowAttributes.flags); 2556 2557 InputMethodManager imm = InputMethodManager.peekInstance(); 2558 if (mView != null) { 2559 if (hasWindowFocus && imm != null && mLastWasImTarget) { 2560 imm.startGettingWindowFocus(mView); 2561 } 2562 mAttachInfo.mKeyDispatchState.reset(); 2563 mView.dispatchWindowFocusChanged(hasWindowFocus); 2564 } 2565 2566 // Note: must be done after the focus change callbacks, 2567 // so all of the view state is set up correctly. 2568 if (hasWindowFocus) { 2569 if (imm != null && mLastWasImTarget) { 2570 imm.onWindowFocus(mView, mView.findFocus(), 2571 mWindowAttributes.softInputMode, 2572 !mHasHadWindowFocus, mWindowAttributes.flags); 2573 } 2574 // Clear the forward bit. We can just do this directly, since 2575 // the window manager doesn't care about it. 2576 mWindowAttributes.softInputMode &= 2577 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2578 ((WindowManager.LayoutParams)mView.getLayoutParams()) 2579 .softInputMode &= 2580 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2581 mHasHadWindowFocus = true; 2582 } 2583 2584 if (hasWindowFocus && mView != null) { 2585 sendAccessibilityEvents(); 2586 } 2587 } 2588 } break; 2589 case DIE: 2590 doDie(); 2591 break; 2592 case DISPATCH_KEY: { 2593 KeyEvent event = (KeyEvent)msg.obj; 2594 enqueueInputEvent(event, null, 0); 2595 } break; 2596 case DISPATCH_KEY_FROM_IME: { 2597 if (LOCAL_LOGV) Log.v( 2598 TAG, "Dispatching key " 2599 + msg.obj + " from IME to " + mView); 2600 KeyEvent event = (KeyEvent)msg.obj; 2601 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 2602 // The IME is trying to say this event is from the 2603 // system! Bad bad bad! 2604 //noinspection UnusedAssignment 2605 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 2606 } 2607 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME); 2608 } break; 2609 case FINISH_INPUT_CONNECTION: { 2610 InputMethodManager imm = InputMethodManager.peekInstance(); 2611 if (imm != null) { 2612 imm.reportFinishInputConnection((InputConnection)msg.obj); 2613 } 2614 } break; 2615 case CHECK_FOCUS: { 2616 InputMethodManager imm = InputMethodManager.peekInstance(); 2617 if (imm != null) { 2618 imm.checkFocus(); 2619 } 2620 } break; 2621 case CLOSE_SYSTEM_DIALOGS: { 2622 if (mView != null) { 2623 mView.onCloseSystemDialogs((String)msg.obj); 2624 } 2625 } break; 2626 case DISPATCH_DRAG_EVENT: 2627 case DISPATCH_DRAG_LOCATION_EVENT: { 2628 DragEvent event = (DragEvent)msg.obj; 2629 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 2630 handleDragEvent(event); 2631 } break; 2632 case DISPATCH_SYSTEM_UI_VISIBILITY: { 2633 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj); 2634 } break; 2635 case UPDATE_CONFIGURATION: { 2636 Configuration config = (Configuration)msg.obj; 2637 if (config.isOtherSeqNewer(mLastConfiguration)) { 2638 config = mLastConfiguration; 2639 } 2640 updateConfiguration(config, false); 2641 } break; 2642 case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID: { 2643 if (mView != null) { 2644 getAccessibilityInteractionController() 2645 .findAccessibilityNodeInfoByAccessibilityIdUiThread(msg); 2646 } 2647 } break; 2648 case DO_PERFORM_ACCESSIBILITY_ACTION: { 2649 if (mView != null) { 2650 getAccessibilityInteractionController() 2651 .perfromAccessibilityActionUiThread(msg); 2652 } 2653 } break; 2654 case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID: { 2655 if (mView != null) { 2656 getAccessibilityInteractionController() 2657 .findAccessibilityNodeInfoByViewIdUiThread(msg); 2658 } 2659 } break; 2660 case DO_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT: { 2661 if (mView != null) { 2662 getAccessibilityInteractionController() 2663 .findAccessibilityNodeInfosByTextUiThread(msg); 2664 } 2665 } break; 2666 } 2667 } 2668 2669 /** 2670 * Something in the current window tells us we need to change the touch mode. For 2671 * example, we are not in touch mode, and the user touches the screen. 2672 * 2673 * If the touch mode has changed, tell the window manager, and handle it locally. 2674 * 2675 * @param inTouchMode Whether we want to be in touch mode. 2676 * @return True if the touch mode changed and focus changed was changed as a result 2677 */ 2678 boolean ensureTouchMode(boolean inTouchMode) { 2679 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 2680 + "touch mode is " + mAttachInfo.mInTouchMode); 2681 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 2682 2683 // tell the window manager 2684 try { 2685 sWindowSession.setInTouchMode(inTouchMode); 2686 } catch (RemoteException e) { 2687 throw new RuntimeException(e); 2688 } 2689 2690 // handle the change 2691 return ensureTouchModeLocally(inTouchMode); 2692 } 2693 2694 /** 2695 * Ensure that the touch mode for this window is set, and if it is changing, 2696 * take the appropriate action. 2697 * @param inTouchMode Whether we want to be in touch mode. 2698 * @return True if the touch mode changed and focus changed was changed as a result 2699 */ 2700 private boolean ensureTouchModeLocally(boolean inTouchMode) { 2701 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 2702 + "touch mode is " + mAttachInfo.mInTouchMode); 2703 2704 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 2705 2706 mAttachInfo.mInTouchMode = inTouchMode; 2707 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 2708 2709 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 2710 } 2711 2712 private boolean enterTouchMode() { 2713 if (mView != null) { 2714 if (mView.hasFocus()) { 2715 // note: not relying on mFocusedView here because this could 2716 // be when the window is first being added, and mFocused isn't 2717 // set yet. 2718 final View focused = mView.findFocus(); 2719 if (focused != null && !focused.isFocusableInTouchMode()) { 2720 2721 final ViewGroup ancestorToTakeFocus = 2722 findAncestorToTakeFocusInTouchMode(focused); 2723 if (ancestorToTakeFocus != null) { 2724 // there is an ancestor that wants focus after its descendants that 2725 // is focusable in touch mode.. give it focus 2726 return ancestorToTakeFocus.requestFocus(); 2727 } else { 2728 // nothing appropriate to have focus in touch mode, clear it out 2729 mView.unFocus(); 2730 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null); 2731 mFocusedView = null; 2732 mOldFocusedView = null; 2733 return true; 2734 } 2735 } 2736 } 2737 } 2738 return false; 2739 } 2740 2741 2742 /** 2743 * Find an ancestor of focused that wants focus after its descendants and is 2744 * focusable in touch mode. 2745 * @param focused The currently focused view. 2746 * @return An appropriate view, or null if no such view exists. 2747 */ 2748 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 2749 ViewParent parent = focused.getParent(); 2750 while (parent instanceof ViewGroup) { 2751 final ViewGroup vgParent = (ViewGroup) parent; 2752 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 2753 && vgParent.isFocusableInTouchMode()) { 2754 return vgParent; 2755 } 2756 if (vgParent.isRootNamespace()) { 2757 return null; 2758 } else { 2759 parent = vgParent.getParent(); 2760 } 2761 } 2762 return null; 2763 } 2764 2765 private boolean leaveTouchMode() { 2766 if (mView != null) { 2767 if (mView.hasFocus()) { 2768 // i learned the hard way to not trust mFocusedView :) 2769 mFocusedView = mView.findFocus(); 2770 if (!(mFocusedView instanceof ViewGroup)) { 2771 // some view has focus, let it keep it 2772 return false; 2773 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() != 2774 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 2775 // some view group has focus, and doesn't prefer its children 2776 // over itself for focus, so let them keep it. 2777 return false; 2778 } 2779 } 2780 2781 // find the best view to give focus to in this brave new non-touch-mode 2782 // world 2783 final View focused = focusSearch(null, View.FOCUS_DOWN); 2784 if (focused != null) { 2785 return focused.requestFocus(View.FOCUS_DOWN); 2786 } 2787 } 2788 return false; 2789 } 2790 2791 private void deliverInputEvent(QueuedInputEvent q) { 2792 if (ViewDebug.DEBUG_LATENCY) { 2793 q.mDeliverTimeNanos = System.nanoTime(); 2794 } 2795 2796 if (q.mEvent instanceof KeyEvent) { 2797 deliverKeyEvent(q); 2798 } else { 2799 final int source = q.mEvent.getSource(); 2800 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 2801 deliverPointerEvent(q); 2802 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 2803 deliverTrackballEvent(q); 2804 } else { 2805 deliverGenericMotionEvent(q); 2806 } 2807 } 2808 } 2809 2810 private void deliverPointerEvent(QueuedInputEvent q) { 2811 final MotionEvent event = (MotionEvent)q.mEvent; 2812 final boolean isTouchEvent = event.isTouchEvent(); 2813 if (mInputEventConsistencyVerifier != null) { 2814 if (isTouchEvent) { 2815 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 2816 } else { 2817 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 2818 } 2819 } 2820 2821 // If there is no view, then the event will not be handled. 2822 if (mView == null || !mAdded) { 2823 finishInputEvent(q, false); 2824 return; 2825 } 2826 2827 // Translate the pointer event for compatibility, if needed. 2828 if (mTranslator != null) { 2829 mTranslator.translateEventInScreenToAppWindow(event); 2830 } 2831 2832 // Enter touch mode on down or scroll. 2833 final int action = event.getAction(); 2834 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 2835 ensureTouchMode(true); 2836 } 2837 2838 // Offset the scroll position. 2839 if (mCurScrollY != 0) { 2840 event.offsetLocation(0, mCurScrollY); 2841 } 2842 if (MEASURE_LATENCY) { 2843 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano()); 2844 } 2845 2846 // Remember the touch position for possible drag-initiation. 2847 if (isTouchEvent) { 2848 mLastTouchPoint.x = event.getRawX(); 2849 mLastTouchPoint.y = event.getRawY(); 2850 } 2851 2852 // Dispatch touch to view hierarchy. 2853 boolean handled = mView.dispatchPointerEvent(event); 2854 if (MEASURE_LATENCY) { 2855 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano()); 2856 } 2857 if (handled) { 2858 finishInputEvent(q, true); 2859 return; 2860 } 2861 2862 // Pointer event was unhandled. 2863 finishInputEvent(q, false); 2864 } 2865 2866 private void deliverTrackballEvent(QueuedInputEvent q) { 2867 final MotionEvent event = (MotionEvent)q.mEvent; 2868 if (mInputEventConsistencyVerifier != null) { 2869 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 2870 } 2871 2872 // If there is no view, then the event will not be handled. 2873 if (mView == null || !mAdded) { 2874 finishInputEvent(q, false); 2875 return; 2876 } 2877 2878 // Deliver the trackball event to the view. 2879 if (mView.dispatchTrackballEvent(event)) { 2880 // If we reach this, we delivered a trackball event to mView and 2881 // mView consumed it. Because we will not translate the trackball 2882 // event into a key event, touch mode will not exit, so we exit 2883 // touch mode here. 2884 ensureTouchMode(false); 2885 2886 finishInputEvent(q, true); 2887 mLastTrackballTime = Integer.MIN_VALUE; 2888 return; 2889 } 2890 2891 // Translate the trackball event into DPAD keys and try to deliver those. 2892 final TrackballAxis x = mTrackballAxisX; 2893 final TrackballAxis y = mTrackballAxisY; 2894 2895 long curTime = SystemClock.uptimeMillis(); 2896 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) { 2897 // It has been too long since the last movement, 2898 // so restart at the beginning. 2899 x.reset(0); 2900 y.reset(0); 2901 mLastTrackballTime = curTime; 2902 } 2903 2904 final int action = event.getAction(); 2905 final int metaState = event.getMetaState(); 2906 switch (action) { 2907 case MotionEvent.ACTION_DOWN: 2908 x.reset(2); 2909 y.reset(2); 2910 dispatchKey(new KeyEvent(curTime, curTime, 2911 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 2912 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 2913 InputDevice.SOURCE_KEYBOARD)); 2914 break; 2915 case MotionEvent.ACTION_UP: 2916 x.reset(2); 2917 y.reset(2); 2918 dispatchKey(new KeyEvent(curTime, curTime, 2919 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 2920 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 2921 InputDevice.SOURCE_KEYBOARD)); 2922 break; 2923 } 2924 2925 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step=" 2926 + x.step + " dir=" + x.dir + " acc=" + x.acceleration 2927 + " move=" + event.getX() 2928 + " / Y=" + y.position + " step=" 2929 + y.step + " dir=" + y.dir + " acc=" + y.acceleration 2930 + " move=" + event.getY()); 2931 final float xOff = x.collect(event.getX(), event.getEventTime(), "X"); 2932 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y"); 2933 2934 // Generate DPAD events based on the trackball movement. 2935 // We pick the axis that has moved the most as the direction of 2936 // the DPAD. When we generate DPAD events for one axis, then the 2937 // other axis is reset -- we don't want to perform DPAD jumps due 2938 // to slight movements in the trackball when making major movements 2939 // along the other axis. 2940 int keycode = 0; 2941 int movement = 0; 2942 float accel = 1; 2943 if (xOff > yOff) { 2944 movement = x.generate((2/event.getXPrecision())); 2945 if (movement != 0) { 2946 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 2947 : KeyEvent.KEYCODE_DPAD_LEFT; 2948 accel = x.acceleration; 2949 y.reset(2); 2950 } 2951 } else if (yOff > 0) { 2952 movement = y.generate((2/event.getYPrecision())); 2953 if (movement != 0) { 2954 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 2955 : KeyEvent.KEYCODE_DPAD_UP; 2956 accel = y.acceleration; 2957 x.reset(2); 2958 } 2959 } 2960 2961 if (keycode != 0) { 2962 if (movement < 0) movement = -movement; 2963 int accelMovement = (int)(movement * accel); 2964 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 2965 + " accelMovement=" + accelMovement 2966 + " accel=" + accel); 2967 if (accelMovement > movement) { 2968 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 2969 + keycode); 2970 movement--; 2971 int repeatCount = accelMovement - movement; 2972 dispatchKey(new KeyEvent(curTime, curTime, 2973 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 2974 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 2975 InputDevice.SOURCE_KEYBOARD)); 2976 } 2977 while (movement > 0) { 2978 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 2979 + keycode); 2980 movement--; 2981 curTime = SystemClock.uptimeMillis(); 2982 dispatchKey(new KeyEvent(curTime, curTime, 2983 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 2984 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 2985 InputDevice.SOURCE_KEYBOARD)); 2986 dispatchKey(new KeyEvent(curTime, curTime, 2987 KeyEvent.ACTION_UP, keycode, 0, metaState, 2988 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 2989 InputDevice.SOURCE_KEYBOARD)); 2990 } 2991 mLastTrackballTime = curTime; 2992 } 2993 2994 // Unfortunately we can't tell whether the application consumed the keys, so 2995 // we always consider the trackball event handled. 2996 finishInputEvent(q, true); 2997 } 2998 2999 private void deliverGenericMotionEvent(QueuedInputEvent q) { 3000 final MotionEvent event = (MotionEvent)q.mEvent; 3001 if (mInputEventConsistencyVerifier != null) { 3002 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3003 } 3004 3005 final int source = event.getSource(); 3006 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0; 3007 3008 // If there is no view, then the event will not be handled. 3009 if (mView == null || !mAdded) { 3010 if (isJoystick) { 3011 updateJoystickDirection(event, false); 3012 } 3013 finishInputEvent(q, false); 3014 return; 3015 } 3016 3017 // Deliver the event to the view. 3018 if (mView.dispatchGenericMotionEvent(event)) { 3019 if (isJoystick) { 3020 updateJoystickDirection(event, false); 3021 } 3022 finishInputEvent(q, true); 3023 return; 3024 } 3025 3026 if (isJoystick) { 3027 // Translate the joystick event into DPAD keys and try to deliver those. 3028 updateJoystickDirection(event, true); 3029 finishInputEvent(q, true); 3030 } else { 3031 finishInputEvent(q, false); 3032 } 3033 } 3034 3035 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) { 3036 final long time = event.getEventTime(); 3037 final int metaState = event.getMetaState(); 3038 final int deviceId = event.getDeviceId(); 3039 final int source = event.getSource(); 3040 3041 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X)); 3042 if (xDirection == 0) { 3043 xDirection = joystickAxisValueToDirection(event.getX()); 3044 } 3045 3046 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 3047 if (yDirection == 0) { 3048 yDirection = joystickAxisValueToDirection(event.getY()); 3049 } 3050 3051 if (xDirection != mLastJoystickXDirection) { 3052 if (mLastJoystickXKeyCode != 0) { 3053 dispatchKey(new KeyEvent(time, time, 3054 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState, 3055 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3056 mLastJoystickXKeyCode = 0; 3057 } 3058 3059 mLastJoystickXDirection = xDirection; 3060 3061 if (xDirection != 0 && synthesizeNewKeys) { 3062 mLastJoystickXKeyCode = xDirection > 0 3063 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 3064 dispatchKey(new KeyEvent(time, time, 3065 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState, 3066 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3067 } 3068 } 3069 3070 if (yDirection != mLastJoystickYDirection) { 3071 if (mLastJoystickYKeyCode != 0) { 3072 dispatchKey(new KeyEvent(time, time, 3073 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState, 3074 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3075 mLastJoystickYKeyCode = 0; 3076 } 3077 3078 mLastJoystickYDirection = yDirection; 3079 3080 if (yDirection != 0 && synthesizeNewKeys) { 3081 mLastJoystickYKeyCode = yDirection > 0 3082 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 3083 dispatchKey(new KeyEvent(time, time, 3084 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState, 3085 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3086 } 3087 } 3088 } 3089 3090 private static int joystickAxisValueToDirection(float value) { 3091 if (value >= 0.5f) { 3092 return 1; 3093 } else if (value <= -0.5f) { 3094 return -1; 3095 } else { 3096 return 0; 3097 } 3098 } 3099 3100 /** 3101 * Returns true if the key is used for keyboard navigation. 3102 * @param keyEvent The key event. 3103 * @return True if the key is used for keyboard navigation. 3104 */ 3105 private static boolean isNavigationKey(KeyEvent keyEvent) { 3106 switch (keyEvent.getKeyCode()) { 3107 case KeyEvent.KEYCODE_DPAD_LEFT: 3108 case KeyEvent.KEYCODE_DPAD_RIGHT: 3109 case KeyEvent.KEYCODE_DPAD_UP: 3110 case KeyEvent.KEYCODE_DPAD_DOWN: 3111 case KeyEvent.KEYCODE_DPAD_CENTER: 3112 case KeyEvent.KEYCODE_PAGE_UP: 3113 case KeyEvent.KEYCODE_PAGE_DOWN: 3114 case KeyEvent.KEYCODE_MOVE_HOME: 3115 case KeyEvent.KEYCODE_MOVE_END: 3116 case KeyEvent.KEYCODE_TAB: 3117 case KeyEvent.KEYCODE_SPACE: 3118 case KeyEvent.KEYCODE_ENTER: 3119 return true; 3120 } 3121 return false; 3122 } 3123 3124 /** 3125 * Returns true if the key is used for typing. 3126 * @param keyEvent The key event. 3127 * @return True if the key is used for typing. 3128 */ 3129 private static boolean isTypingKey(KeyEvent keyEvent) { 3130 return keyEvent.getUnicodeChar() > 0; 3131 } 3132 3133 /** 3134 * See if the key event means we should leave touch mode (and leave touch mode if so). 3135 * @param event The key event. 3136 * @return Whether this key event should be consumed (meaning the act of 3137 * leaving touch mode alone is considered the event). 3138 */ 3139 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 3140 // Only relevant in touch mode. 3141 if (!mAttachInfo.mInTouchMode) { 3142 return false; 3143 } 3144 3145 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 3146 final int action = event.getAction(); 3147 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 3148 return false; 3149 } 3150 3151 // Don't leave touch mode if the IME told us not to. 3152 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 3153 return false; 3154 } 3155 3156 // If the key can be used for keyboard navigation then leave touch mode 3157 // and select a focused view if needed (in ensureTouchMode). 3158 // When a new focused view is selected, we consume the navigation key because 3159 // navigation doesn't make much sense unless a view already has focus so 3160 // the key's purpose is to set focus. 3161 if (isNavigationKey(event)) { 3162 return ensureTouchMode(false); 3163 } 3164 3165 // If the key can be used for typing then leave touch mode 3166 // and select a focused view if needed (in ensureTouchMode). 3167 // Always allow the view to process the typing key. 3168 if (isTypingKey(event)) { 3169 ensureTouchMode(false); 3170 return false; 3171 } 3172 3173 return false; 3174 } 3175 3176 private void deliverKeyEvent(QueuedInputEvent q) { 3177 final KeyEvent event = (KeyEvent)q.mEvent; 3178 if (mInputEventConsistencyVerifier != null) { 3179 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 3180 } 3181 3182 if ((q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3183 // If there is no view, then the event will not be handled. 3184 if (mView == null || !mAdded) { 3185 finishInputEvent(q, false); 3186 return; 3187 } 3188 3189 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView); 3190 3191 // Perform predispatching before the IME. 3192 if (mView.dispatchKeyEventPreIme(event)) { 3193 finishInputEvent(q, true); 3194 return; 3195 } 3196 3197 // Dispatch to the IME before propagating down the view hierarchy. 3198 // The IME will eventually call back into handleImeFinishedEvent. 3199 if (mLastWasImTarget) { 3200 InputMethodManager imm = InputMethodManager.peekInstance(); 3201 if (imm != null) { 3202 final int seq = event.getSequenceNumber(); 3203 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq=" 3204 + seq + " event=" + event); 3205 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback); 3206 return; 3207 } 3208 } 3209 } 3210 3211 // Not dispatching to IME, continue with post IME actions. 3212 deliverKeyEventPostIme(q); 3213 } 3214 3215 void handleImeFinishedEvent(int seq, boolean handled) { 3216 final QueuedInputEvent q = mCurrentInputEvent; 3217 if (q != null && q.mEvent.getSequenceNumber() == seq) { 3218 final KeyEvent event = (KeyEvent)q.mEvent; 3219 if (DEBUG_IMF) { 3220 Log.v(TAG, "IME finished event: seq=" + seq 3221 + " handled=" + handled + " event=" + event); 3222 } 3223 if (handled) { 3224 finishInputEvent(q, true); 3225 } else { 3226 deliverKeyEventPostIme(q); 3227 } 3228 } else { 3229 if (DEBUG_IMF) { 3230 Log.v(TAG, "IME finished event: seq=" + seq 3231 + " handled=" + handled + ", event not found!"); 3232 } 3233 } 3234 } 3235 3236 private void deliverKeyEventPostIme(QueuedInputEvent q) { 3237 final KeyEvent event = (KeyEvent)q.mEvent; 3238 if (ViewDebug.DEBUG_LATENCY) { 3239 q.mDeliverPostImeTimeNanos = System.nanoTime(); 3240 } 3241 3242 // If the view went away, then the event will not be handled. 3243 if (mView == null || !mAdded) { 3244 finishInputEvent(q, false); 3245 return; 3246 } 3247 3248 // If the key's purpose is to exit touch mode then we consume it and consider it handled. 3249 if (checkForLeavingTouchModeAndConsume(event)) { 3250 finishInputEvent(q, true); 3251 return; 3252 } 3253 3254 // Make sure the fallback event policy sees all keys that will be delivered to the 3255 // view hierarchy. 3256 mFallbackEventHandler.preDispatchKeyEvent(event); 3257 3258 // Deliver the key to the view hierarchy. 3259 if (mView.dispatchKeyEvent(event)) { 3260 finishInputEvent(q, true); 3261 return; 3262 } 3263 3264 // If the Control modifier is held, try to interpret the key as a shortcut. 3265 if (event.getAction() == KeyEvent.ACTION_DOWN 3266 && event.isCtrlPressed() 3267 && event.getRepeatCount() == 0 3268 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3269 if (mView.dispatchKeyShortcutEvent(event)) { 3270 finishInputEvent(q, true); 3271 return; 3272 } 3273 } 3274 3275 // Apply the fallback event policy. 3276 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3277 finishInputEvent(q, true); 3278 return; 3279 } 3280 3281 // Handle automatic focus changes. 3282 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3283 int direction = 0; 3284 switch (event.getKeyCode()) { 3285 case KeyEvent.KEYCODE_DPAD_LEFT: 3286 if (event.hasNoModifiers()) { 3287 direction = View.FOCUS_LEFT; 3288 } 3289 break; 3290 case KeyEvent.KEYCODE_DPAD_RIGHT: 3291 if (event.hasNoModifiers()) { 3292 direction = View.FOCUS_RIGHT; 3293 } 3294 break; 3295 case KeyEvent.KEYCODE_DPAD_UP: 3296 if (event.hasNoModifiers()) { 3297 direction = View.FOCUS_UP; 3298 } 3299 break; 3300 case KeyEvent.KEYCODE_DPAD_DOWN: 3301 if (event.hasNoModifiers()) { 3302 direction = View.FOCUS_DOWN; 3303 } 3304 break; 3305 case KeyEvent.KEYCODE_TAB: 3306 if (event.hasNoModifiers()) { 3307 direction = View.FOCUS_FORWARD; 3308 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3309 direction = View.FOCUS_BACKWARD; 3310 } 3311 break; 3312 } 3313 3314 if (direction != 0) { 3315 View focused = mView != null ? mView.findFocus() : null; 3316 if (focused != null) { 3317 View v = focused.focusSearch(direction); 3318 if (v != null && v != focused) { 3319 // do the math the get the interesting rect 3320 // of previous focused into the coord system of 3321 // newly focused view 3322 focused.getFocusedRect(mTempRect); 3323 if (mView instanceof ViewGroup) { 3324 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3325 focused, mTempRect); 3326 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3327 v, mTempRect); 3328 } 3329 if (v.requestFocus(direction, mTempRect)) { 3330 playSoundEffect( 3331 SoundEffectConstants.getContantForFocusDirection(direction)); 3332 finishInputEvent(q, true); 3333 return; 3334 } 3335 } 3336 3337 // Give the focused view a last chance to handle the dpad key. 3338 if (mView.dispatchUnhandledMove(focused, direction)) { 3339 finishInputEvent(q, true); 3340 return; 3341 } 3342 } 3343 } 3344 } 3345 3346 // Key was unhandled. 3347 finishInputEvent(q, false); 3348 } 3349 3350 /* drag/drop */ 3351 void setLocalDragState(Object obj) { 3352 mLocalDragState = obj; 3353 } 3354 3355 private void handleDragEvent(DragEvent event) { 3356 // From the root, only drag start/end/location are dispatched. entered/exited 3357 // are determined and dispatched by the viewgroup hierarchy, who then report 3358 // that back here for ultimate reporting back to the framework. 3359 if (mView != null && mAdded) { 3360 final int what = event.mAction; 3361 3362 if (what == DragEvent.ACTION_DRAG_EXITED) { 3363 // A direct EXITED event means that the window manager knows we've just crossed 3364 // a window boundary, so the current drag target within this one must have 3365 // just been exited. Send it the usual notifications and then we're done 3366 // for now. 3367 mView.dispatchDragEvent(event); 3368 } else { 3369 // Cache the drag description when the operation starts, then fill it in 3370 // on subsequent calls as a convenience 3371 if (what == DragEvent.ACTION_DRAG_STARTED) { 3372 mCurrentDragView = null; // Start the current-recipient tracking 3373 mDragDescription = event.mClipDescription; 3374 } else { 3375 event.mClipDescription = mDragDescription; 3376 } 3377 3378 // For events with a [screen] location, translate into window coordinates 3379 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 3380 mDragPoint.set(event.mX, event.mY); 3381 if (mTranslator != null) { 3382 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 3383 } 3384 3385 if (mCurScrollY != 0) { 3386 mDragPoint.offset(0, mCurScrollY); 3387 } 3388 3389 event.mX = mDragPoint.x; 3390 event.mY = mDragPoint.y; 3391 } 3392 3393 // Remember who the current drag target is pre-dispatch 3394 final View prevDragView = mCurrentDragView; 3395 3396 // Now dispatch the drag/drop event 3397 boolean result = mView.dispatchDragEvent(event); 3398 3399 // If we changed apparent drag target, tell the OS about it 3400 if (prevDragView != mCurrentDragView) { 3401 try { 3402 if (prevDragView != null) { 3403 sWindowSession.dragRecipientExited(mWindow); 3404 } 3405 if (mCurrentDragView != null) { 3406 sWindowSession.dragRecipientEntered(mWindow); 3407 } 3408 } catch (RemoteException e) { 3409 Slog.e(TAG, "Unable to note drag target change"); 3410 } 3411 } 3412 3413 // Report the drop result when we're done 3414 if (what == DragEvent.ACTION_DROP) { 3415 mDragDescription = null; 3416 try { 3417 Log.i(TAG, "Reporting drop result: " + result); 3418 sWindowSession.reportDropResult(mWindow, result); 3419 } catch (RemoteException e) { 3420 Log.e(TAG, "Unable to report drop result"); 3421 } 3422 } 3423 3424 // When the drag operation ends, release any local state object 3425 // that may have been in use 3426 if (what == DragEvent.ACTION_DRAG_ENDED) { 3427 setLocalDragState(null); 3428 } 3429 } 3430 } 3431 event.recycle(); 3432 } 3433 3434 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 3435 if (mSeq != args.seq) { 3436 // The sequence has changed, so we need to update our value and make 3437 // sure to do a traversal afterward so the window manager is given our 3438 // most recent data. 3439 mSeq = args.seq; 3440 mAttachInfo.mForceReportNewAttributes = true; 3441 scheduleTraversals(); 3442 } 3443 if (mView == null) return; 3444 if (args.localChanges != 0) { 3445 if (mAttachInfo != null) { 3446 mAttachInfo.mSystemUiVisibility = 3447 (mAttachInfo.mSystemUiVisibility&~args.localChanges) 3448 | (args.localValue&args.localChanges); 3449 } 3450 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 3451 mAttachInfo.mRecomputeGlobalAttributes = true; 3452 scheduleTraversals(); 3453 } 3454 mView.dispatchSystemUiVisibilityChanged(args.globalVisibility); 3455 } 3456 3457 public void getLastTouchPoint(Point outLocation) { 3458 outLocation.x = (int) mLastTouchPoint.x; 3459 outLocation.y = (int) mLastTouchPoint.y; 3460 } 3461 3462 public void setDragFocus(View newDragTarget) { 3463 if (mCurrentDragView != newDragTarget) { 3464 mCurrentDragView = newDragTarget; 3465 } 3466 } 3467 3468 private AudioManager getAudioManager() { 3469 if (mView == null) { 3470 throw new IllegalStateException("getAudioManager called when there is no mView"); 3471 } 3472 if (mAudioManager == null) { 3473 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 3474 } 3475 return mAudioManager; 3476 } 3477 3478 public AccessibilityInteractionController getAccessibilityInteractionController() { 3479 if (mView == null) { 3480 throw new IllegalStateException("getAccessibilityInteractionController" 3481 + " called when there is no mView"); 3482 } 3483 if (mAccessibilityInteractionController == null) { 3484 mAccessibilityInteractionController = new AccessibilityInteractionController(); 3485 } 3486 return mAccessibilityInteractionController; 3487 } 3488 3489 public AccessibilityPrefetchStrategy getAccessibilityPrefetchStrategy() { 3490 if (mView == null) { 3491 throw new IllegalStateException("getAccessibilityPrefetchStrategy" 3492 + " called when there is no mView"); 3493 } 3494 if (mAccessibilityPrefetchStrategy == null) { 3495 mAccessibilityPrefetchStrategy = new AccessibilityPrefetchStrategy(); 3496 } 3497 return mAccessibilityPrefetchStrategy; 3498 } 3499 3500 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 3501 boolean insetsPending) throws RemoteException { 3502 3503 float appScale = mAttachInfo.mApplicationScale; 3504 boolean restore = false; 3505 if (params != null && mTranslator != null) { 3506 restore = true; 3507 params.backup(); 3508 mTranslator.translateWindowLayout(params); 3509 } 3510 if (params != null) { 3511 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 3512 } 3513 mPendingConfiguration.seq = 0; 3514 //Log.d(TAG, ">>>>>> CALLING relayout"); 3515 if (params != null && mOrigWindowType != params.type) { 3516 // For compatibility with old apps, don't crash here. 3517 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 3518 Slog.w(TAG, "Window type can not be changed after " 3519 + "the window is added; ignoring change of " + mView); 3520 params.type = mOrigWindowType; 3521 } 3522 } 3523 int relayoutResult = sWindowSession.relayout( 3524 mWindow, mSeq, params, 3525 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 3526 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 3527 viewVisibility, insetsPending ? WindowManagerImpl.RELAYOUT_INSETS_PENDING : 0, 3528 mWinFrame, mPendingContentInsets, mPendingVisibleInsets, 3529 mPendingConfiguration, mSurface); 3530 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 3531 if (restore) { 3532 params.restore(); 3533 } 3534 3535 if (mTranslator != null) { 3536 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 3537 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 3538 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 3539 } 3540 return relayoutResult; 3541 } 3542 3543 /** 3544 * {@inheritDoc} 3545 */ 3546 public void playSoundEffect(int effectId) { 3547 checkThread(); 3548 3549 try { 3550 final AudioManager audioManager = getAudioManager(); 3551 3552 switch (effectId) { 3553 case SoundEffectConstants.CLICK: 3554 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 3555 return; 3556 case SoundEffectConstants.NAVIGATION_DOWN: 3557 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 3558 return; 3559 case SoundEffectConstants.NAVIGATION_LEFT: 3560 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 3561 return; 3562 case SoundEffectConstants.NAVIGATION_RIGHT: 3563 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 3564 return; 3565 case SoundEffectConstants.NAVIGATION_UP: 3566 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 3567 return; 3568 default: 3569 throw new IllegalArgumentException("unknown effect id " + effectId + 3570 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 3571 } 3572 } catch (IllegalStateException e) { 3573 // Exception thrown by getAudioManager() when mView is null 3574 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 3575 e.printStackTrace(); 3576 } 3577 } 3578 3579 /** 3580 * {@inheritDoc} 3581 */ 3582 public boolean performHapticFeedback(int effectId, boolean always) { 3583 try { 3584 return sWindowSession.performHapticFeedback(mWindow, effectId, always); 3585 } catch (RemoteException e) { 3586 return false; 3587 } 3588 } 3589 3590 /** 3591 * {@inheritDoc} 3592 */ 3593 public View focusSearch(View focused, int direction) { 3594 checkThread(); 3595 if (!(mView instanceof ViewGroup)) { 3596 return null; 3597 } 3598 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 3599 } 3600 3601 public void debug() { 3602 mView.debug(); 3603 } 3604 3605 public void dumpGfxInfo(PrintWriter pw, int[] info) { 3606 if (mView != null) { 3607 getGfxInfo(mView, info); 3608 } else { 3609 info[0] = info[1] = 0; 3610 } 3611 } 3612 3613 private void getGfxInfo(View view, int[] info) { 3614 DisplayList displayList = view.mDisplayList; 3615 info[0]++; 3616 if (displayList != null) { 3617 info[1] += displayList.getSize(); 3618 } 3619 3620 if (view instanceof ViewGroup) { 3621 ViewGroup group = (ViewGroup) view; 3622 3623 int count = group.getChildCount(); 3624 for (int i = 0; i < count; i++) { 3625 getGfxInfo(group.getChildAt(i), info); 3626 } 3627 } 3628 } 3629 3630 public void die(boolean immediate) { 3631 if (immediate) { 3632 doDie(); 3633 } else { 3634 sendEmptyMessage(DIE); 3635 } 3636 } 3637 3638 void doDie() { 3639 checkThread(); 3640 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 3641 synchronized (this) { 3642 if (mAdded) { 3643 mAdded = false; 3644 dispatchDetachedFromWindow(); 3645 } 3646 3647 if (mAdded && !mFirst) { 3648 destroyHardwareRenderer(); 3649 3650 int viewVisibility = mView.getVisibility(); 3651 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 3652 if (mWindowAttributesChanged || viewVisibilityChanged) { 3653 // If layout params have been changed, first give them 3654 // to the window manager to make sure it has the correct 3655 // animation info. 3656 try { 3657 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 3658 & WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0) { 3659 sWindowSession.finishDrawing(mWindow); 3660 } 3661 } catch (RemoteException e) { 3662 } 3663 } 3664 3665 mSurface.release(); 3666 } 3667 } 3668 } 3669 3670 public void requestUpdateConfiguration(Configuration config) { 3671 Message msg = obtainMessage(UPDATE_CONFIGURATION, config); 3672 sendMessage(msg); 3673 } 3674 3675 private void destroyHardwareRenderer() { 3676 if (mAttachInfo.mHardwareRenderer != null) { 3677 mAttachInfo.mHardwareRenderer.destroy(true); 3678 mAttachInfo.mHardwareRenderer = null; 3679 mAttachInfo.mHardwareAccelerated = false; 3680 } 3681 } 3682 3683 void dispatchImeFinishedEvent(int seq, boolean handled) { 3684 Message msg = obtainMessage(IME_FINISHED_EVENT); 3685 msg.arg1 = seq; 3686 msg.arg2 = handled ? 1 : 0; 3687 sendMessage(msg); 3688 } 3689 3690 public void dispatchResized(int w, int h, Rect coveredInsets, 3691 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 3692 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w 3693 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString() 3694 + " visibleInsets=" + visibleInsets.toShortString() 3695 + " reportDraw=" + reportDraw); 3696 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED); 3697 if (mTranslator != null) { 3698 mTranslator.translateRectInScreenToAppWindow(coveredInsets); 3699 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 3700 w *= mTranslator.applicationInvertedScale; 3701 h *= mTranslator.applicationInvertedScale; 3702 } 3703 msg.arg1 = w; 3704 msg.arg2 = h; 3705 ResizedInfo ri = new ResizedInfo(); 3706 ri.coveredInsets = new Rect(coveredInsets); 3707 ri.visibleInsets = new Rect(visibleInsets); 3708 ri.newConfig = newConfig; 3709 msg.obj = ri; 3710 sendMessage(msg); 3711 } 3712 3713 /** 3714 * Represents a pending input event that is waiting in a queue. 3715 * 3716 * Input events are processed in serial order by the timestamp specified by 3717 * {@link InputEvent#getEventTime()}. In general, the input dispatcher delivers 3718 * one input event to the application at a time and waits for the application 3719 * to finish handling it before delivering the next one. 3720 * 3721 * However, because the application or IME can synthesize and inject multiple 3722 * key events at a time without going through the input dispatcher, we end up 3723 * needing a queue on the application's side. 3724 */ 3725 private static final class QueuedInputEvent { 3726 public static final int FLAG_DELIVER_POST_IME = 1 << 0; 3727 3728 public QueuedInputEvent mNext; 3729 3730 public InputEvent mEvent; 3731 public InputEventReceiver mReceiver; 3732 public int mFlags; 3733 3734 // Used for latency calculations. 3735 public long mReceiveTimeNanos; 3736 public long mDeliverTimeNanos; 3737 public long mDeliverPostImeTimeNanos; 3738 } 3739 3740 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 3741 InputEventReceiver receiver, int flags) { 3742 QueuedInputEvent q = mQueuedInputEventPool; 3743 if (q != null) { 3744 mQueuedInputEventPoolSize -= 1; 3745 mQueuedInputEventPool = q.mNext; 3746 q.mNext = null; 3747 } else { 3748 q = new QueuedInputEvent(); 3749 } 3750 3751 q.mEvent = event; 3752 q.mReceiver = receiver; 3753 q.mFlags = flags; 3754 return q; 3755 } 3756 3757 private void recycleQueuedInputEvent(QueuedInputEvent q) { 3758 q.mEvent = null; 3759 q.mReceiver = null; 3760 3761 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 3762 mQueuedInputEventPoolSize += 1; 3763 q.mNext = mQueuedInputEventPool; 3764 mQueuedInputEventPool = q; 3765 } 3766 } 3767 3768 void enqueueInputEvent(InputEvent event, 3769 InputEventReceiver receiver, int flags) { 3770 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 3771 3772 if (ViewDebug.DEBUG_LATENCY) { 3773 q.mReceiveTimeNanos = System.nanoTime(); 3774 q.mDeliverTimeNanos = 0; 3775 q.mDeliverPostImeTimeNanos = 0; 3776 } 3777 3778 // Always enqueue the input event in order, regardless of its time stamp. 3779 // We do this because the application or the IME may inject key events 3780 // in response to touch events and we want to ensure that the injected keys 3781 // are processed in the order they were received and we cannot trust that 3782 // the time stamp of injected events are monotonic. 3783 QueuedInputEvent last = mFirstPendingInputEvent; 3784 if (last == null) { 3785 mFirstPendingInputEvent = q; 3786 } else { 3787 while (last.mNext != null) { 3788 last = last.mNext; 3789 } 3790 last.mNext = q; 3791 } 3792 3793 scheduleProcessInputEvents(); 3794 } 3795 3796 private void scheduleProcessInputEvents() { 3797 if (!mProcessInputEventsScheduled) { 3798 mProcessInputEventsScheduled = true; 3799 sendEmptyMessage(DO_PROCESS_INPUT_EVENTS); 3800 } 3801 } 3802 3803 private void doProcessInputEvents() { 3804 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 3805 QueuedInputEvent q = mFirstPendingInputEvent; 3806 mFirstPendingInputEvent = q.mNext; 3807 q.mNext = null; 3808 mCurrentInputEvent = q; 3809 deliverInputEvent(q); 3810 } 3811 3812 // We are done processing all input events that we can process right now 3813 // so we can clear the pending flag immediately. 3814 if (mProcessInputEventsScheduled) { 3815 mProcessInputEventsScheduled = false; 3816 removeMessages(DO_PROCESS_INPUT_EVENTS); 3817 } 3818 } 3819 3820 private void finishInputEvent(QueuedInputEvent q, boolean handled) { 3821 if (q != mCurrentInputEvent) { 3822 throw new IllegalStateException("finished input event out of order"); 3823 } 3824 3825 if (ViewDebug.DEBUG_LATENCY) { 3826 final long now = System.nanoTime(); 3827 final long eventTime = q.mEvent.getEventTimeNano(); 3828 final StringBuilder msg = new StringBuilder(); 3829 msg.append("Spent "); 3830 msg.append((now - q.mReceiveTimeNanos) * 0.000001f); 3831 msg.append("ms processing "); 3832 if (q.mEvent instanceof KeyEvent) { 3833 final KeyEvent keyEvent = (KeyEvent)q.mEvent; 3834 msg.append("key event, action="); 3835 msg.append(KeyEvent.actionToString(keyEvent.getAction())); 3836 } else { 3837 final MotionEvent motionEvent = (MotionEvent)q.mEvent; 3838 msg.append("motion event, action="); 3839 msg.append(MotionEvent.actionToString(motionEvent.getAction())); 3840 msg.append(", historySize="); 3841 msg.append(motionEvent.getHistorySize()); 3842 } 3843 msg.append(", handled="); 3844 msg.append(handled); 3845 msg.append(", received at +"); 3846 msg.append((q.mReceiveTimeNanos - eventTime) * 0.000001f); 3847 if (q.mDeliverTimeNanos != 0) { 3848 msg.append("ms, delivered at +"); 3849 msg.append((q.mDeliverTimeNanos - eventTime) * 0.000001f); 3850 } 3851 if (q.mDeliverPostImeTimeNanos != 0) { 3852 msg.append("ms, delivered post IME at +"); 3853 msg.append((q.mDeliverPostImeTimeNanos - eventTime) * 0.000001f); 3854 } 3855 msg.append("ms, finished at +"); 3856 msg.append((now - eventTime) * 0.000001f); 3857 msg.append("ms."); 3858 Log.d(ViewDebug.DEBUG_LATENCY_TAG, msg.toString()); 3859 } 3860 3861 if (q.mReceiver != null) { 3862 q.mReceiver.finishInputEvent(q.mEvent, handled); 3863 } else { 3864 q.mEvent.recycleIfNeededAfterDispatch(); 3865 } 3866 3867 recycleQueuedInputEvent(q); 3868 3869 mCurrentInputEvent = null; 3870 if (mFirstPendingInputEvent != null) { 3871 scheduleProcessInputEvents(); 3872 } 3873 } 3874 3875 final class WindowInputEventReceiver extends InputEventReceiver { 3876 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 3877 super(inputChannel, looper); 3878 } 3879 3880 @Override 3881 public void onInputEvent(InputEvent event) { 3882 enqueueInputEvent(event, this, 0); 3883 } 3884 } 3885 WindowInputEventReceiver mInputEventReceiver; 3886 3887 public void dispatchKey(KeyEvent event) { 3888 enqueueInputEvent(event, null, 0); 3889 } 3890 3891 public void dispatchAppVisibility(boolean visible) { 3892 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY); 3893 msg.arg1 = visible ? 1 : 0; 3894 sendMessage(msg); 3895 } 3896 3897 public void dispatchGetNewSurface() { 3898 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE); 3899 sendMessage(msg); 3900 } 3901 3902 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 3903 Message msg = Message.obtain(); 3904 msg.what = WINDOW_FOCUS_CHANGED; 3905 msg.arg1 = hasFocus ? 1 : 0; 3906 msg.arg2 = inTouchMode ? 1 : 0; 3907 sendMessage(msg); 3908 } 3909 3910 public void dispatchCloseSystemDialogs(String reason) { 3911 Message msg = Message.obtain(); 3912 msg.what = CLOSE_SYSTEM_DIALOGS; 3913 msg.obj = reason; 3914 sendMessage(msg); 3915 } 3916 3917 public void dispatchDragEvent(DragEvent event) { 3918 final int what; 3919 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 3920 what = DISPATCH_DRAG_LOCATION_EVENT; 3921 removeMessages(what); 3922 } else { 3923 what = DISPATCH_DRAG_EVENT; 3924 } 3925 Message msg = obtainMessage(what, event); 3926 sendMessage(msg); 3927 } 3928 3929 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 3930 int localValue, int localChanges) { 3931 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 3932 args.seq = seq; 3933 args.globalVisibility = globalVisibility; 3934 args.localValue = localValue; 3935 args.localChanges = localChanges; 3936 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, args)); 3937 } 3938 3939 /** 3940 * The window is getting focus so if there is anything focused/selected 3941 * send an {@link AccessibilityEvent} to announce that. 3942 */ 3943 private void sendAccessibilityEvents() { 3944 if (!mAccessibilityManager.isEnabled()) { 3945 return; 3946 } 3947 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 3948 View focusedView = mView.findFocus(); 3949 if (focusedView != null && focusedView != mView) { 3950 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3951 } 3952 } 3953 3954 /** 3955 * Post a callback to send a 3956 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 3957 * This event is send at most once every 3958 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 3959 */ 3960 private void postSendWindowContentChangedCallback() { 3961 if (mSendWindowContentChangedAccessibilityEvent == null) { 3962 mSendWindowContentChangedAccessibilityEvent = 3963 new SendWindowContentChangedAccessibilityEvent(); 3964 } 3965 if (!mSendWindowContentChangedAccessibilityEvent.mIsPending) { 3966 mSendWindowContentChangedAccessibilityEvent.mIsPending = true; 3967 postDelayed(mSendWindowContentChangedAccessibilityEvent, 3968 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 3969 } 3970 } 3971 3972 /** 3973 * Remove a posted callback to send a 3974 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 3975 */ 3976 private void removeSendWindowContentChangedCallback() { 3977 if (mSendWindowContentChangedAccessibilityEvent != null) { 3978 removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 3979 } 3980 } 3981 3982 public boolean showContextMenuForChild(View originalView) { 3983 return false; 3984 } 3985 3986 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 3987 return null; 3988 } 3989 3990 public void createContextMenu(ContextMenu menu) { 3991 } 3992 3993 public void childDrawableStateChanged(View child) { 3994 } 3995 3996 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 3997 if (mView == null) { 3998 return false; 3999 } 4000 getAccessibilityPrefetchStrategy().onAccessibilityEvent(event); 4001 mAccessibilityManager.sendAccessibilityEvent(event); 4002 return true; 4003 } 4004 4005 void checkThread() { 4006 if (mThread != Thread.currentThread()) { 4007 throw new CalledFromWrongThreadException( 4008 "Only the original thread that created a view hierarchy can touch its views."); 4009 } 4010 } 4011 4012 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4013 // ViewAncestor never intercepts touch event, so this can be a no-op 4014 } 4015 4016 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, 4017 boolean immediate) { 4018 return scrollToRectOrFocus(rectangle, immediate); 4019 } 4020 4021 class TakenSurfaceHolder extends BaseSurfaceHolder { 4022 @Override 4023 public boolean onAllowLockCanvas() { 4024 return mDrawingAllowed; 4025 } 4026 4027 @Override 4028 public void onRelayoutContainer() { 4029 // Not currently interesting -- from changing between fixed and layout size. 4030 } 4031 4032 public void setFormat(int format) { 4033 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4034 } 4035 4036 public void setType(int type) { 4037 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4038 } 4039 4040 @Override 4041 public void onUpdateSurface() { 4042 // We take care of format and type changes on our own. 4043 throw new IllegalStateException("Shouldn't be here"); 4044 } 4045 4046 public boolean isCreating() { 4047 return mIsCreating; 4048 } 4049 4050 @Override 4051 public void setFixedSize(int width, int height) { 4052 throw new UnsupportedOperationException( 4053 "Currently only support sizing from layout"); 4054 } 4055 4056 public void setKeepScreenOn(boolean screenOn) { 4057 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4058 } 4059 } 4060 4061 static class InputMethodCallback extends IInputMethodCallback.Stub { 4062 private WeakReference<ViewRootImpl> mViewAncestor; 4063 4064 public InputMethodCallback(ViewRootImpl viewAncestor) { 4065 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4066 } 4067 4068 public void finishedEvent(int seq, boolean handled) { 4069 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4070 if (viewAncestor != null) { 4071 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4072 } 4073 } 4074 4075 public void sessionCreated(IInputMethodSession session) { 4076 // Stub -- not for use in the client. 4077 } 4078 } 4079 4080 static class W extends IWindow.Stub { 4081 private final WeakReference<ViewRootImpl> mViewAncestor; 4082 4083 W(ViewRootImpl viewAncestor) { 4084 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4085 } 4086 4087 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets, 4088 boolean reportDraw, Configuration newConfig) { 4089 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4090 if (viewAncestor != null) { 4091 viewAncestor.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, 4092 newConfig); 4093 } 4094 } 4095 4096 public void dispatchAppVisibility(boolean visible) { 4097 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4098 if (viewAncestor != null) { 4099 viewAncestor.dispatchAppVisibility(visible); 4100 } 4101 } 4102 4103 public void dispatchGetNewSurface() { 4104 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4105 if (viewAncestor != null) { 4106 viewAncestor.dispatchGetNewSurface(); 4107 } 4108 } 4109 4110 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4111 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4112 if (viewAncestor != null) { 4113 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4114 } 4115 } 4116 4117 private static int checkCallingPermission(String permission) { 4118 try { 4119 return ActivityManagerNative.getDefault().checkPermission( 4120 permission, Binder.getCallingPid(), Binder.getCallingUid()); 4121 } catch (RemoteException e) { 4122 return PackageManager.PERMISSION_DENIED; 4123 } 4124 } 4125 4126 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 4127 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4128 if (viewAncestor != null) { 4129 final View view = viewAncestor.mView; 4130 if (view != null) { 4131 if (checkCallingPermission(Manifest.permission.DUMP) != 4132 PackageManager.PERMISSION_GRANTED) { 4133 throw new SecurityException("Insufficient permissions to invoke" 4134 + " executeCommand() from pid=" + Binder.getCallingPid() 4135 + ", uid=" + Binder.getCallingUid()); 4136 } 4137 4138 OutputStream clientStream = null; 4139 try { 4140 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 4141 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 4142 } catch (IOException e) { 4143 e.printStackTrace(); 4144 } finally { 4145 if (clientStream != null) { 4146 try { 4147 clientStream.close(); 4148 } catch (IOException e) { 4149 e.printStackTrace(); 4150 } 4151 } 4152 } 4153 } 4154 } 4155 } 4156 4157 public void closeSystemDialogs(String reason) { 4158 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4159 if (viewAncestor != null) { 4160 viewAncestor.dispatchCloseSystemDialogs(reason); 4161 } 4162 } 4163 4164 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 4165 boolean sync) { 4166 if (sync) { 4167 try { 4168 sWindowSession.wallpaperOffsetsComplete(asBinder()); 4169 } catch (RemoteException e) { 4170 } 4171 } 4172 } 4173 4174 public void dispatchWallpaperCommand(String action, int x, int y, 4175 int z, Bundle extras, boolean sync) { 4176 if (sync) { 4177 try { 4178 sWindowSession.wallpaperCommandComplete(asBinder(), null); 4179 } catch (RemoteException e) { 4180 } 4181 } 4182 } 4183 4184 /* Drag/drop */ 4185 public void dispatchDragEvent(DragEvent event) { 4186 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4187 if (viewAncestor != null) { 4188 viewAncestor.dispatchDragEvent(event); 4189 } 4190 } 4191 4192 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4193 int localValue, int localChanges) { 4194 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4195 if (viewAncestor != null) { 4196 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 4197 localValue, localChanges); 4198 } 4199 } 4200 } 4201 4202 /** 4203 * Maintains state information for a single trackball axis, generating 4204 * discrete (DPAD) movements based on raw trackball motion. 4205 */ 4206 static final class TrackballAxis { 4207 /** 4208 * The maximum amount of acceleration we will apply. 4209 */ 4210 static final float MAX_ACCELERATION = 20; 4211 4212 /** 4213 * The maximum amount of time (in milliseconds) between events in order 4214 * for us to consider the user to be doing fast trackball movements, 4215 * and thus apply an acceleration. 4216 */ 4217 static final long FAST_MOVE_TIME = 150; 4218 4219 /** 4220 * Scaling factor to the time (in milliseconds) between events to how 4221 * much to multiple/divide the current acceleration. When movement 4222 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4223 * FAST_MOVE_TIME it divides it. 4224 */ 4225 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4226 4227 float position; 4228 float absPosition; 4229 float acceleration = 1; 4230 long lastMoveTime = 0; 4231 int step; 4232 int dir; 4233 int nonAccelMovement; 4234 4235 void reset(int _step) { 4236 position = 0; 4237 acceleration = 1; 4238 lastMoveTime = 0; 4239 step = _step; 4240 dir = 0; 4241 } 4242 4243 /** 4244 * Add trackball movement into the state. If the direction of movement 4245 * has been reversed, the state is reset before adding the 4246 * movement (so that you don't have to compensate for any previously 4247 * collected movement before see the result of the movement in the 4248 * new direction). 4249 * 4250 * @return Returns the absolute value of the amount of movement 4251 * collected so far. 4252 */ 4253 float collect(float off, long time, String axis) { 4254 long normTime; 4255 if (off > 0) { 4256 normTime = (long)(off * FAST_MOVE_TIME); 4257 if (dir < 0) { 4258 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 4259 position = 0; 4260 step = 0; 4261 acceleration = 1; 4262 lastMoveTime = 0; 4263 } 4264 dir = 1; 4265 } else if (off < 0) { 4266 normTime = (long)((-off) * FAST_MOVE_TIME); 4267 if (dir > 0) { 4268 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 4269 position = 0; 4270 step = 0; 4271 acceleration = 1; 4272 lastMoveTime = 0; 4273 } 4274 dir = -1; 4275 } else { 4276 normTime = 0; 4277 } 4278 4279 // The number of milliseconds between each movement that is 4280 // considered "normal" and will not result in any acceleration 4281 // or deceleration, scaled by the offset we have here. 4282 if (normTime > 0) { 4283 long delta = time - lastMoveTime; 4284 lastMoveTime = time; 4285 float acc = acceleration; 4286 if (delta < normTime) { 4287 // The user is scrolling rapidly, so increase acceleration. 4288 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 4289 if (scale > 1) acc *= scale; 4290 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 4291 + off + " normTime=" + normTime + " delta=" + delta 4292 + " scale=" + scale + " acc=" + acc); 4293 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 4294 } else { 4295 // The user is scrolling slowly, so decrease acceleration. 4296 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 4297 if (scale > 1) acc /= scale; 4298 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 4299 + off + " normTime=" + normTime + " delta=" + delta 4300 + " scale=" + scale + " acc=" + acc); 4301 acceleration = acc > 1 ? acc : 1; 4302 } 4303 } 4304 position += off; 4305 return (absPosition = Math.abs(position)); 4306 } 4307 4308 /** 4309 * Generate the number of discrete movement events appropriate for 4310 * the currently collected trackball movement. 4311 * 4312 * @param precision The minimum movement required to generate the 4313 * first discrete movement. 4314 * 4315 * @return Returns the number of discrete movements, either positive 4316 * or negative, or 0 if there is not enough trackball movement yet 4317 * for a discrete movement. 4318 */ 4319 int generate(float precision) { 4320 int movement = 0; 4321 nonAccelMovement = 0; 4322 do { 4323 final int dir = position >= 0 ? 1 : -1; 4324 switch (step) { 4325 // If we are going to execute the first step, then we want 4326 // to do this as soon as possible instead of waiting for 4327 // a full movement, in order to make things look responsive. 4328 case 0: 4329 if (absPosition < precision) { 4330 return movement; 4331 } 4332 movement += dir; 4333 nonAccelMovement += dir; 4334 step = 1; 4335 break; 4336 // If we have generated the first movement, then we need 4337 // to wait for the second complete trackball motion before 4338 // generating the second discrete movement. 4339 case 1: 4340 if (absPosition < 2) { 4341 return movement; 4342 } 4343 movement += dir; 4344 nonAccelMovement += dir; 4345 position += dir > 0 ? -2 : 2; 4346 absPosition = Math.abs(position); 4347 step = 2; 4348 break; 4349 // After the first two, we generate discrete movements 4350 // consistently with the trackball, applying an acceleration 4351 // if the trackball is moving quickly. This is a simple 4352 // acceleration on top of what we already compute based 4353 // on how quickly the wheel is being turned, to apply 4354 // a longer increasing acceleration to continuous movement 4355 // in one direction. 4356 default: 4357 if (absPosition < 1) { 4358 return movement; 4359 } 4360 movement += dir; 4361 position += dir >= 0 ? -1 : 1; 4362 absPosition = Math.abs(position); 4363 float acc = acceleration; 4364 acc *= 1.1f; 4365 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 4366 break; 4367 } 4368 } while (true); 4369 } 4370 } 4371 4372 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 4373 public CalledFromWrongThreadException(String msg) { 4374 super(msg); 4375 } 4376 } 4377 4378 private SurfaceHolder mHolder = new SurfaceHolder() { 4379 // we only need a SurfaceHolder for opengl. it would be nice 4380 // to implement everything else though, especially the callback 4381 // support (opengl doesn't make use of it right now, but eventually 4382 // will). 4383 public Surface getSurface() { 4384 return mSurface; 4385 } 4386 4387 public boolean isCreating() { 4388 return false; 4389 } 4390 4391 public void addCallback(Callback callback) { 4392 } 4393 4394 public void removeCallback(Callback callback) { 4395 } 4396 4397 public void setFixedSize(int width, int height) { 4398 } 4399 4400 public void setSizeFromLayout() { 4401 } 4402 4403 public void setFormat(int format) { 4404 } 4405 4406 public void setType(int type) { 4407 } 4408 4409 public void setKeepScreenOn(boolean screenOn) { 4410 } 4411 4412 public Canvas lockCanvas() { 4413 return null; 4414 } 4415 4416 public Canvas lockCanvas(Rect dirty) { 4417 return null; 4418 } 4419 4420 public void unlockCanvasAndPost(Canvas canvas) { 4421 } 4422 public Rect getSurfaceFrame() { 4423 return null; 4424 } 4425 }; 4426 4427 static RunQueue getRunQueue() { 4428 RunQueue rq = sRunQueues.get(); 4429 if (rq != null) { 4430 return rq; 4431 } 4432 rq = new RunQueue(); 4433 sRunQueues.set(rq); 4434 return rq; 4435 } 4436 4437 /** 4438 * @hide 4439 */ 4440 static final class RunQueue { 4441 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 4442 4443 void post(Runnable action) { 4444 postDelayed(action, 0); 4445 } 4446 4447 void postDelayed(Runnable action, long delayMillis) { 4448 HandlerAction handlerAction = new HandlerAction(); 4449 handlerAction.action = action; 4450 handlerAction.delay = delayMillis; 4451 4452 synchronized (mActions) { 4453 mActions.add(handlerAction); 4454 } 4455 } 4456 4457 void removeCallbacks(Runnable action) { 4458 final HandlerAction handlerAction = new HandlerAction(); 4459 handlerAction.action = action; 4460 4461 synchronized (mActions) { 4462 final ArrayList<HandlerAction> actions = mActions; 4463 4464 while (actions.remove(handlerAction)) { 4465 // Keep going 4466 } 4467 } 4468 } 4469 4470 void executeActions(Handler handler) { 4471 synchronized (mActions) { 4472 final ArrayList<HandlerAction> actions = mActions; 4473 final int count = actions.size(); 4474 4475 for (int i = 0; i < count; i++) { 4476 final HandlerAction handlerAction = actions.get(i); 4477 handler.postDelayed(handlerAction.action, handlerAction.delay); 4478 } 4479 4480 actions.clear(); 4481 } 4482 } 4483 4484 private static class HandlerAction { 4485 Runnable action; 4486 long delay; 4487 4488 @Override 4489 public boolean equals(Object o) { 4490 if (this == o) return true; 4491 if (o == null || getClass() != o.getClass()) return false; 4492 4493 HandlerAction that = (HandlerAction) o; 4494 return !(action != null ? !action.equals(that.action) : that.action != null); 4495 4496 } 4497 4498 @Override 4499 public int hashCode() { 4500 int result = action != null ? action.hashCode() : 0; 4501 result = 31 * result + (int) (delay ^ (delay >>> 32)); 4502 return result; 4503 } 4504 } 4505 } 4506 4507 /** 4508 * Class for managing the accessibility interaction connection 4509 * based on the global accessibility state. 4510 */ 4511 final class AccessibilityInteractionConnectionManager 4512 implements AccessibilityStateChangeListener { 4513 public void onAccessibilityStateChanged(boolean enabled) { 4514 if (enabled) { 4515 ensureConnection(); 4516 } else { 4517 ensureNoConnection(); 4518 } 4519 } 4520 4521 public void ensureConnection() { 4522 final boolean registered = mAttachInfo.mAccessibilityWindowId != View.NO_ID; 4523 if (!registered) { 4524 mAttachInfo.mAccessibilityWindowId = 4525 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 4526 new AccessibilityInteractionConnection(ViewRootImpl.this)); 4527 } 4528 } 4529 4530 public void ensureNoConnection() { 4531 final boolean registered = mAttachInfo.mAccessibilityWindowId != View.NO_ID; 4532 if (registered) { 4533 mAttachInfo.mAccessibilityWindowId = View.NO_ID; 4534 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 4535 } 4536 } 4537 } 4538 4539 /** 4540 * This class is an interface this ViewAncestor provides to the 4541 * AccessibilityManagerService to the latter can interact with 4542 * the view hierarchy in this ViewAncestor. 4543 */ 4544 static final class AccessibilityInteractionConnection 4545 extends IAccessibilityInteractionConnection.Stub { 4546 private final WeakReference<ViewRootImpl> mViewRootImpl; 4547 4548 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 4549 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 4550 } 4551 4552 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 4553 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4554 int interrogatingPid, long interrogatingTid) { 4555 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4556 if (viewRootImpl != null && viewRootImpl.mView != null) { 4557 viewRootImpl.getAccessibilityInteractionController() 4558 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 4559 interactionId, callback, interrogatingPid, interrogatingTid); 4560 } else { 4561 // We cannot make the call and notify the caller so it does not wait. 4562 try { 4563 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 4564 } catch (RemoteException re) { 4565 /* best effort - ignore */ 4566 } 4567 } 4568 } 4569 4570 public void performAccessibilityAction(long accessibilityNodeId, int action, 4571 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4572 int interogatingPid, long interrogatingTid) { 4573 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4574 if (viewRootImpl != null && viewRootImpl.mView != null) { 4575 viewRootImpl.getAccessibilityInteractionController() 4576 .performAccessibilityActionClientThread(accessibilityNodeId, action, 4577 interactionId, callback, interogatingPid, interrogatingTid); 4578 } else { 4579 // We cannot make the call and notify the caller so it does not 4580 try { 4581 callback.setPerformAccessibilityActionResult(false, interactionId); 4582 } catch (RemoteException re) { 4583 /* best effort - ignore */ 4584 } 4585 } 4586 } 4587 4588 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId, 4589 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4590 int interrogatingPid, long interrogatingTid) { 4591 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4592 if (viewRootImpl != null && viewRootImpl.mView != null) { 4593 viewRootImpl.getAccessibilityInteractionController() 4594 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId, 4595 interactionId, callback, interrogatingPid, interrogatingTid); 4596 } else { 4597 // We cannot make the call and notify the caller so it does not 4598 try { 4599 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 4600 } catch (RemoteException re) { 4601 /* best effort - ignore */ 4602 } 4603 } 4604 } 4605 4606 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 4607 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4608 int interrogatingPid, long interrogatingTid) { 4609 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 4610 if (viewRootImpl != null && viewRootImpl.mView != null) { 4611 viewRootImpl.getAccessibilityInteractionController() 4612 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 4613 interactionId, callback, interrogatingPid, interrogatingTid); 4614 } else { 4615 // We cannot make the call and notify the caller so it does not 4616 try { 4617 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 4618 } catch (RemoteException re) { 4619 /* best effort - ignore */ 4620 } 4621 } 4622 } 4623 } 4624 4625 /** 4626 * Class for managing accessibility interactions initiated from the system 4627 * and targeting the view hierarchy. A *ClientThread method is to be 4628 * called from the interaction connection this ViewAncestor gives the 4629 * system to talk to it and a corresponding *UiThread method that is executed 4630 * on the UI thread. 4631 */ 4632 final class AccessibilityInteractionController { 4633 private static final int POOL_SIZE = 5; 4634 4635 private ArrayList<AccessibilityNodeInfo> mTempAccessibilityNodeInfoList = 4636 new ArrayList<AccessibilityNodeInfo>(); 4637 4638 // Reusable poolable arguments for interacting with the view hierarchy 4639 // to fit more arguments than Message and to avoid sharing objects between 4640 // two messages since several threads can send messages concurrently. 4641 private final Pool<SomeArgs> mPool = Pools.synchronizedPool(Pools.finitePool( 4642 new PoolableManager<SomeArgs>() { 4643 public SomeArgs newInstance() { 4644 return new SomeArgs(); 4645 } 4646 4647 public void onAcquired(SomeArgs info) { 4648 /* do nothing */ 4649 } 4650 4651 public void onReleased(SomeArgs info) { 4652 info.clear(); 4653 } 4654 }, POOL_SIZE) 4655 ); 4656 4657 public class SomeArgs implements Poolable<SomeArgs> { 4658 private SomeArgs mNext; 4659 private boolean mIsPooled; 4660 4661 public Object arg1; 4662 public Object arg2; 4663 public int argi1; 4664 public int argi2; 4665 public int argi3; 4666 4667 public SomeArgs getNextPoolable() { 4668 return mNext; 4669 } 4670 4671 public boolean isPooled() { 4672 return mIsPooled; 4673 } 4674 4675 public void setNextPoolable(SomeArgs args) { 4676 mNext = args; 4677 } 4678 4679 public void setPooled(boolean isPooled) { 4680 mIsPooled = isPooled; 4681 } 4682 4683 private void clear() { 4684 arg1 = null; 4685 arg2 = null; 4686 argi1 = 0; 4687 argi2 = 0; 4688 argi3 = 0; 4689 } 4690 } 4691 4692 public void findAccessibilityNodeInfoByAccessibilityIdClientThread( 4693 long accessibilityNodeId, int interactionId, 4694 IAccessibilityInteractionConnectionCallback callback, int interrogatingPid, 4695 long interrogatingTid) { 4696 Message message = Message.obtain(); 4697 message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_ACCESSIBILITY_ID; 4698 message.arg1 = interrogatingPid; 4699 SomeArgs args = mPool.acquire(); 4700 args.argi1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 4701 args.argi2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 4702 args.argi3 = interactionId; 4703 args.arg1 = callback; 4704 message.obj = args; 4705 // If the interrogation is performed by the same thread as the main UI 4706 // thread in this process, set the message as a static reference so 4707 // after this call completes the same thread but in the interrogating 4708 // client can handle the message to generate the result. 4709 if (interrogatingPid == Process.myPid() 4710 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 4711 message.setTarget(ViewRootImpl.this); 4712 AccessibilityInteractionClient.getInstanceForThread( 4713 interrogatingTid).setSameThreadMessage(message); 4714 } else { 4715 sendMessage(message); 4716 } 4717 } 4718 4719 public void findAccessibilityNodeInfoByAccessibilityIdUiThread(Message message) { 4720 SomeArgs args = (SomeArgs) message.obj; 4721 final int interrogatingPid = message.arg1; 4722 final int accessibilityViewId = args.argi1; 4723 final int virtualDescendantId = args.argi2; 4724 final int interactionId = args.argi3; 4725 final IAccessibilityInteractionConnectionCallback callback = 4726 (IAccessibilityInteractionConnectionCallback) args.arg1; 4727 mPool.release(args); 4728 List<AccessibilityNodeInfo> infos = mTempAccessibilityNodeInfoList; 4729 infos.clear(); 4730 try { 4731 View target = findViewByAccessibilityId(accessibilityViewId); 4732 if (target != null && target.getVisibility() == View.VISIBLE) { 4733 AccessibilityNodeProvider provider = target.getAccessibilityNodeProvider(); 4734 if (provider != null) { 4735 infos.add(provider.createAccessibilityNodeInfo(virtualDescendantId)); 4736 } else if (virtualDescendantId == View.NO_ID) { 4737 getAccessibilityPrefetchStrategy().prefetchAccessibilityNodeInfos( 4738 interrogatingPid, target, infos); 4739 } 4740 } 4741 } finally { 4742 try { 4743 callback.setFindAccessibilityNodeInfosResult(infos, interactionId); 4744 infos.clear(); 4745 } catch (RemoteException re) { 4746 /* ignore - the other side will time out */ 4747 } 4748 } 4749 } 4750 4751 public void findAccessibilityNodeInfoByViewIdClientThread(long accessibilityNodeId, 4752 int viewId, int interactionId, IAccessibilityInteractionConnectionCallback callback, 4753 int interrogatingPid, long interrogatingTid) { 4754 Message message = Message.obtain(); 4755 message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_VIEW_ID; 4756 message.arg1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 4757 SomeArgs args = mPool.acquire(); 4758 args.argi1 = viewId; 4759 args.argi2 = interactionId; 4760 args.arg1 = callback; 4761 message.obj = args; 4762 // If the interrogation is performed by the same thread as the main UI 4763 // thread in this process, set the message as a static reference so 4764 // after this call completes the same thread but in the interrogating 4765 // client can handle the message to generate the result. 4766 if (interrogatingPid == Process.myPid() 4767 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 4768 message.setTarget(ViewRootImpl.this); 4769 AccessibilityInteractionClient.getInstanceForThread( 4770 interrogatingTid).setSameThreadMessage(message); 4771 } else { 4772 sendMessage(message); 4773 } 4774 } 4775 4776 public void findAccessibilityNodeInfoByViewIdUiThread(Message message) { 4777 final int accessibilityViewId = message.arg1; 4778 SomeArgs args = (SomeArgs) message.obj; 4779 final int viewId = args.argi1; 4780 final int interactionId = args.argi2; 4781 final IAccessibilityInteractionConnectionCallback callback = 4782 (IAccessibilityInteractionConnectionCallback) args.arg1; 4783 mPool.release(args); 4784 AccessibilityNodeInfo info = null; 4785 try { 4786 View root = null; 4787 if (accessibilityViewId != View.NO_ID) { 4788 root = findViewByAccessibilityId(accessibilityViewId); 4789 } else { 4790 root = ViewRootImpl.this.mView; 4791 } 4792 if (root != null) { 4793 View target = root.findViewById(viewId); 4794 if (target != null && target.getVisibility() == View.VISIBLE) { 4795 info = target.createAccessibilityNodeInfo(); 4796 } 4797 } 4798 } finally { 4799 try { 4800 callback.setFindAccessibilityNodeInfoResult(info, interactionId); 4801 } catch (RemoteException re) { 4802 /* ignore - the other side will time out */ 4803 } 4804 } 4805 } 4806 4807 public void findAccessibilityNodeInfosByTextClientThread(long accessibilityNodeId, 4808 String text, int interactionId, 4809 IAccessibilityInteractionConnectionCallback callback, int interrogatingPid, 4810 long interrogatingTid) { 4811 Message message = Message.obtain(); 4812 message.what = DO_FIND_ACCESSIBLITY_NODE_INFO_BY_TEXT; 4813 SomeArgs args = mPool.acquire(); 4814 args.arg1 = text; 4815 args.argi1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 4816 args.argi2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 4817 args.argi3 = interactionId; 4818 args.arg2 = callback; 4819 message.obj = args; 4820 // If the interrogation is performed by the same thread as the main UI 4821 // thread in this process, set the message as a static reference so 4822 // after this call completes the same thread but in the interrogating 4823 // client can handle the message to generate the result. 4824 if (interrogatingPid == Process.myPid() 4825 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 4826 message.setTarget(ViewRootImpl.this); 4827 AccessibilityInteractionClient.getInstanceForThread( 4828 interrogatingTid).setSameThreadMessage(message); 4829 } else { 4830 sendMessage(message); 4831 } 4832 } 4833 4834 public void findAccessibilityNodeInfosByTextUiThread(Message message) { 4835 SomeArgs args = (SomeArgs) message.obj; 4836 final String text = (String) args.arg1; 4837 final int accessibilityViewId = args.argi1; 4838 final int virtualDescendantId = args.argi2; 4839 final int interactionId = args.argi3; 4840 final IAccessibilityInteractionConnectionCallback callback = 4841 (IAccessibilityInteractionConnectionCallback) args.arg2; 4842 mPool.release(args); 4843 List<AccessibilityNodeInfo> infos = null; 4844 try { 4845 View target = null; 4846 if (accessibilityViewId != View.NO_ID) { 4847 target = findViewByAccessibilityId(accessibilityViewId); 4848 } else { 4849 target = ViewRootImpl.this.mView; 4850 } 4851 if (target != null && target.getVisibility() == View.VISIBLE) { 4852 AccessibilityNodeProvider provider = target.getAccessibilityNodeProvider(); 4853 if (provider != null) { 4854 infos = provider.findAccessibilityNodeInfosByText(text, 4855 virtualDescendantId); 4856 } else if (virtualDescendantId == View.NO_ID) { 4857 ArrayList<View> foundViews = mAttachInfo.mFocusablesTempList; 4858 foundViews.clear(); 4859 target.findViewsWithText(foundViews, text, View.FIND_VIEWS_WITH_TEXT 4860 | View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION 4861 | View.FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS); 4862 if (!foundViews.isEmpty()) { 4863 infos = mTempAccessibilityNodeInfoList; 4864 infos.clear(); 4865 final int viewCount = foundViews.size(); 4866 for (int i = 0; i < viewCount; i++) { 4867 View foundView = foundViews.get(i); 4868 if (foundView.getVisibility() == View.VISIBLE) { 4869 provider = foundView.getAccessibilityNodeProvider(); 4870 if (provider != null) { 4871 List<AccessibilityNodeInfo> infosFromProvider = 4872 provider.findAccessibilityNodeInfosByText(text, 4873 virtualDescendantId); 4874 if (infosFromProvider != null) { 4875 infos.addAll(infosFromProvider); 4876 } 4877 } else { 4878 infos.add(foundView.createAccessibilityNodeInfo()); 4879 } 4880 } 4881 } 4882 } 4883 } 4884 } 4885 } finally { 4886 try { 4887 callback.setFindAccessibilityNodeInfosResult(infos, interactionId); 4888 } catch (RemoteException re) { 4889 /* ignore - the other side will time out */ 4890 } 4891 } 4892 } 4893 4894 public void performAccessibilityActionClientThread(long accessibilityNodeId, int action, 4895 int interactionId, IAccessibilityInteractionConnectionCallback callback, 4896 int interogatingPid, long interrogatingTid) { 4897 Message message = Message.obtain(); 4898 message.what = DO_PERFORM_ACCESSIBILITY_ACTION; 4899 message.arg1 = AccessibilityNodeInfo.getAccessibilityViewId(accessibilityNodeId); 4900 message.arg2 = AccessibilityNodeInfo.getVirtualDescendantId(accessibilityNodeId); 4901 SomeArgs args = mPool.acquire(); 4902 args.argi1 = action; 4903 args.argi2 = interactionId; 4904 args.arg1 = callback; 4905 message.obj = args; 4906 // If the interrogation is performed by the same thread as the main UI 4907 // thread in this process, set the message as a static reference so 4908 // after this call completes the same thread but in the interrogating 4909 // client can handle the message to generate the result. 4910 if (interogatingPid == Process.myPid() 4911 && interrogatingTid == Looper.getMainLooper().getThread().getId()) { 4912 message.setTarget(ViewRootImpl.this); 4913 AccessibilityInteractionClient.getInstanceForThread( 4914 interrogatingTid).setSameThreadMessage(message); 4915 } else { 4916 sendMessage(message); 4917 } 4918 } 4919 4920 public void perfromAccessibilityActionUiThread(Message message) { 4921 final int accessibilityViewId = message.arg1; 4922 final int virtualDescendantId = message.arg2; 4923 SomeArgs args = (SomeArgs) message.obj; 4924 final int action = args.argi1; 4925 final int interactionId = args.argi2; 4926 final IAccessibilityInteractionConnectionCallback callback = 4927 (IAccessibilityInteractionConnectionCallback) args.arg1; 4928 mPool.release(args); 4929 boolean succeeded = false; 4930 try { 4931 View target = findViewByAccessibilityId(accessibilityViewId); 4932 if (target != null && target.getVisibility() == View.VISIBLE) { 4933 AccessibilityNodeProvider provider = target.getAccessibilityNodeProvider(); 4934 if (provider != null) { 4935 succeeded = provider.performAccessibilityAction(action, 4936 virtualDescendantId); 4937 } else if (virtualDescendantId == View.NO_ID) { 4938 switch (action) { 4939 case AccessibilityNodeInfo.ACTION_FOCUS: { 4940 if (!target.hasFocus()) { 4941 // Get out of touch mode since accessibility 4942 // wants to move focus around. 4943 ensureTouchMode(false); 4944 succeeded = target.requestFocus(); 4945 } 4946 } break; 4947 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 4948 if (target.hasFocus()) { 4949 target.clearFocus(); 4950 succeeded = !target.isFocused(); 4951 } 4952 } break; 4953 case AccessibilityNodeInfo.ACTION_SELECT: { 4954 if (!target.isSelected()) { 4955 target.setSelected(true); 4956 succeeded = target.isSelected(); 4957 } 4958 } break; 4959 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 4960 if (target.isSelected()) { 4961 target.setSelected(false); 4962 succeeded = !target.isSelected(); 4963 } 4964 } break; 4965 } 4966 } 4967 } 4968 } finally { 4969 try { 4970 callback.setPerformAccessibilityActionResult(succeeded, interactionId); 4971 } catch (RemoteException re) { 4972 /* ignore - the other side will time out */ 4973 } 4974 } 4975 } 4976 4977 private View findViewByAccessibilityId(int accessibilityId) { 4978 View root = ViewRootImpl.this.mView; 4979 if (root == null) { 4980 return null; 4981 } 4982 View foundView = root.findViewByAccessibilityId(accessibilityId); 4983 if (foundView != null && foundView.getVisibility() != View.VISIBLE) { 4984 return null; 4985 } 4986 return foundView; 4987 } 4988 } 4989 4990 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 4991 public volatile boolean mIsPending; 4992 4993 public void run() { 4994 if (mView != null) { 4995 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 4996 mIsPending = false; 4997 } 4998 } 4999 } 5000 5001 /** 5002 * This class encapsulates a prefetching strategy for the accessibility APIs for 5003 * querying window content.It is responsible to prefetch a batch of 5004 * AccessibilityNodeInfos in addition to the one for a requested node. It caches 5005 * the ids of the prefeteched nodes such that they are fetched only once. 5006 */ 5007 class AccessibilityPrefetchStrategy { 5008 private static final int MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE = 100; 5009 5010 // We need to keep track of what we have sent for each interrogating 5011 // process. Usually there will be only one such process but we 5012 // should support the general case. Note that the accessibility event 5013 // stream will take care of clearing caches of querying processes that 5014 // are not longer alive, so we do not waste memory. 5015 private final LongSparseArray<AccessibilityNodeInfoCache> mAccessibilityNodeInfoCaches = 5016 new LongSparseArray<AccessibilityNodeInfoCache>(); 5017 5018 private AccessibilityNodeInfoCache getCacheForInterrogatingPid(long interrogatingPid) { 5019 AccessibilityNodeInfoCache cache = mAccessibilityNodeInfoCaches.get(interrogatingPid); 5020 if (cache == null) { 5021 cache = AccessibilityNodeInfoCache.newAccessibilityNodeInfoCache(); 5022 mAccessibilityNodeInfoCaches.put(interrogatingPid, cache); 5023 } 5024 return cache; 5025 } 5026 5027 public void onAccessibilityEvent(AccessibilityEvent event) { 5028 final int cacheCount = mAccessibilityNodeInfoCaches.size(); 5029 for (int i = 0; i < cacheCount; i++) { 5030 AccessibilityNodeInfoCache cache = mAccessibilityNodeInfoCaches.valueAt(i); 5031 cache.onAccessibilityEvent(event); 5032 } 5033 } 5034 5035 public void prefetchAccessibilityNodeInfos(long interrogatingPid, View root, 5036 List<AccessibilityNodeInfo> outInfos) { 5037 addAndCacheNotCachedNodeInfo(interrogatingPid, root, outInfos); 5038 addAndCacheNotCachedPredecessorInfos(interrogatingPid, root, outInfos); 5039 addAndCacheNotCachedDescendantInfos(interrogatingPid, root, outInfos); 5040 } 5041 5042 private void addAndCacheNotCachedNodeInfo(long interrogatingPid, 5043 View view, List<AccessibilityNodeInfo> outInfos) { 5044 final long accessibilityNodeId = AccessibilityNodeInfo.makeNodeId( 5045 view.getAccessibilityViewId(), View.NO_ID); 5046 AccessibilityNodeInfoCache cache = getCacheForInterrogatingPid(interrogatingPid); 5047 if (!cache.containsKey(accessibilityNodeId)) { 5048 // Account for the ids of the fetched infos. The infos will be 5049 // cached in the window querying process. We just need to know 5050 // which infos are cached to avoid fetching a cached one again. 5051 cache.put(accessibilityNodeId, null); 5052 outInfos.add(view.createAccessibilityNodeInfo()); 5053 } 5054 } 5055 5056 private void addAndCacheNotCachedPredecessorInfos(long interrogatingPid, View view, 5057 List<AccessibilityNodeInfo> outInfos) { 5058 ViewParent predecessor = view.getParent(); 5059 while (predecessor instanceof View 5060 && outInfos.size() < MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE) { 5061 View predecessorView = (View) predecessor; 5062 addAndCacheNotCachedNodeInfo(interrogatingPid, predecessorView, outInfos); 5063 predecessor = predecessor.getParent(); 5064 } 5065 } 5066 5067 private void addAndCacheNotCachedDescendantInfos(long interrogatingPid, View view, 5068 List<AccessibilityNodeInfo> outInfos) { 5069 if (outInfos.size() > MAX_ACCESSIBILITY_NODE_INFO_BATCH_SIZE 5070 || view.getAccessibilityNodeProvider() != null) { 5071 return; 5072 } 5073 addAndCacheNotCachedNodeInfo(interrogatingPid, view, outInfos); 5074 if (view instanceof ViewGroup) { 5075 ViewGroup rootGroup = (ViewGroup) view; 5076 final int childCount = rootGroup.getChildCount(); 5077 for (int i = 0; i < childCount; i++) { 5078 View child = rootGroup.getChildAt(i); 5079 addAndCacheNotCachedDescendantInfos(interrogatingPid, child, outInfos); 5080 } 5081 } 5082 } 5083 } 5084} 5085