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