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