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