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