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