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