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