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