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