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