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