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