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