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