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