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