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