ViewRootImpl.java revision c2293025a25e04b26bf53713d71f85fd9ca5e8e9
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 if (mRenderProfiler == null) { 2115 mRenderProfiler = new Choreographer.FrameCallback() { 2116 @Override 2117 public void doFrame(long frameTimeNanos) { 2118 mDirty.set(0, 0, mWidth, mHeight); 2119 scheduleTraversals(); 2120 if (mRenderProfilingEnabled) { 2121 mChoreographer.postFrameCallback(mRenderProfiler); 2122 } 2123 } 2124 }; 2125 mChoreographer.postFrameCallback(mRenderProfiler); 2126 } else { 2127 mChoreographer.removeFrameCallback(mRenderProfiler); 2128 mRenderProfiler = null; 2129 } 2130 } 2131 } 2132 2133 /** 2134 * Called from draw() when DEBUG_FPS is enabled 2135 */ 2136 private void trackFPS() { 2137 // Tracks frames per second drawn. First value in a series of draws may be bogus 2138 // because it down not account for the intervening idle time 2139 long nowTime = System.currentTimeMillis(); 2140 if (mFpsStartTime < 0) { 2141 mFpsStartTime = mFpsPrevTime = nowTime; 2142 mFpsNumFrames = 0; 2143 } else { 2144 ++mFpsNumFrames; 2145 String thisHash = Integer.toHexString(System.identityHashCode(this)); 2146 long frameTime = nowTime - mFpsPrevTime; 2147 long totalTime = nowTime - mFpsStartTime; 2148 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime); 2149 mFpsPrevTime = nowTime; 2150 if (totalTime > 1000) { 2151 float fps = (float) mFpsNumFrames * 1000 / totalTime; 2152 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps); 2153 mFpsStartTime = nowTime; 2154 mFpsNumFrames = 0; 2155 } 2156 } 2157 } 2158 2159 private void performDraw() { 2160 if (!mAttachInfo.mScreenOn && !mReportNextDraw) { 2161 return; 2162 } 2163 2164 final boolean fullRedrawNeeded = mFullRedrawNeeded; 2165 mFullRedrawNeeded = false; 2166 2167 mIsDrawing = true; 2168 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw"); 2169 try { 2170 draw(fullRedrawNeeded); 2171 } finally { 2172 mIsDrawing = false; 2173 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2174 } 2175 2176 if (mReportNextDraw) { 2177 mReportNextDraw = false; 2178 2179 if (LOCAL_LOGV) { 2180 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle()); 2181 } 2182 if (mSurfaceHolder != null && mSurface.isValid()) { 2183 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder); 2184 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 2185 if (callbacks != null) { 2186 for (SurfaceHolder.Callback c : callbacks) { 2187 if (c instanceof SurfaceHolder.Callback2) { 2188 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 2189 mSurfaceHolder); 2190 } 2191 } 2192 } 2193 } 2194 try { 2195 mWindowSession.finishDrawing(mWindow); 2196 } catch (RemoteException e) { 2197 } 2198 } 2199 } 2200 2201 private void draw(boolean fullRedrawNeeded) { 2202 Surface surface = mSurface; 2203 if (!surface.isValid()) { 2204 return; 2205 } 2206 2207 if (DEBUG_FPS) { 2208 trackFPS(); 2209 } 2210 2211 if (!sFirstDrawComplete) { 2212 synchronized (sFirstDrawHandlers) { 2213 sFirstDrawComplete = true; 2214 final int count = sFirstDrawHandlers.size(); 2215 for (int i = 0; i< count; i++) { 2216 mHandler.post(sFirstDrawHandlers.get(i)); 2217 } 2218 } 2219 } 2220 2221 scrollToRectOrFocus(null, false); 2222 2223 final AttachInfo attachInfo = mAttachInfo; 2224 if (attachInfo.mViewScrollChanged) { 2225 attachInfo.mViewScrollChanged = false; 2226 attachInfo.mTreeObserver.dispatchOnScrollChanged(); 2227 } 2228 2229 int yoff; 2230 boolean animating = mScroller != null && mScroller.computeScrollOffset(); 2231 if (animating) { 2232 yoff = mScroller.getCurrY(); 2233 } else { 2234 yoff = mScrollY; 2235 } 2236 if (mCurScrollY != yoff) { 2237 mCurScrollY = yoff; 2238 fullRedrawNeeded = true; 2239 } 2240 2241 final float appScale = attachInfo.mApplicationScale; 2242 final boolean scalingRequired = attachInfo.mScalingRequired; 2243 2244 int resizeAlpha = 0; 2245 if (mResizeBuffer != null) { 2246 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime; 2247 if (deltaTime < mResizeBufferDuration) { 2248 float amt = deltaTime/(float) mResizeBufferDuration; 2249 amt = mResizeInterpolator.getInterpolation(amt); 2250 animating = true; 2251 resizeAlpha = 255 - (int)(amt*255); 2252 } else { 2253 disposeResizeBuffer(); 2254 } 2255 } 2256 2257 final Rect dirty = mDirty; 2258 if (mSurfaceHolder != null) { 2259 // The app owns the surface, we won't draw. 2260 dirty.setEmpty(); 2261 if (animating) { 2262 if (mScroller != null) { 2263 mScroller.abortAnimation(); 2264 } 2265 disposeResizeBuffer(); 2266 } 2267 return; 2268 } 2269 2270 if (fullRedrawNeeded) { 2271 attachInfo.mIgnoreDirtyState = true; 2272 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 2273 } 2274 2275 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2276 Log.v(TAG, "Draw " + mView + "/" 2277 + mWindowAttributes.getTitle() 2278 + ": dirty={" + dirty.left + "," + dirty.top 2279 + "," + dirty.right + "," + dirty.bottom + "} surface=" 2280 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" + 2281 appScale + ", width=" + mWidth + ", height=" + mHeight); 2282 } 2283 2284 invalidateDisplayLists(); 2285 2286 attachInfo.mTreeObserver.dispatchOnDraw(); 2287 2288 if (!dirty.isEmpty() || mIsAnimating) { 2289 if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) { 2290 // Draw with hardware renderer. 2291 mIsAnimating = false; 2292 mHardwareYOffset = yoff; 2293 mResizeAlpha = resizeAlpha; 2294 2295 mCurrentDirty.set(dirty); 2296 mCurrentDirty.union(mPreviousDirty); 2297 mPreviousDirty.set(dirty); 2298 dirty.setEmpty(); 2299 2300 if (attachInfo.mHardwareRenderer.draw(mView, attachInfo, this, 2301 animating ? null : mCurrentDirty)) { 2302 mPreviousDirty.set(0, 0, mWidth, mHeight); 2303 } 2304 } else { 2305 // If we get here with a disabled & requested hardware renderer, something went 2306 // wrong (an invalidate posted right before we destroyed the hardware surface 2307 // for instance) so we should just bail out. Locking the surface with software 2308 // rendering at this point would lock it forever and prevent hardware renderer 2309 // from doing its job when it comes back. 2310 // Before we request a new frame we must however attempt to reinitiliaze the 2311 // hardware renderer if it's in requested state. This would happen after an 2312 // eglTerminate() for instance. 2313 if (attachInfo.mHardwareRenderer != null && 2314 !attachInfo.mHardwareRenderer.isEnabled() && 2315 attachInfo.mHardwareRenderer.isRequested()) { 2316 2317 try { 2318 attachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2319 mHolder.getSurface()); 2320 } catch (Surface.OutOfResourcesException e) { 2321 handleOutOfResourcesException(e); 2322 return; 2323 } 2324 2325 mFullRedrawNeeded = true; 2326 scheduleTraversals(); 2327 return; 2328 } 2329 2330 if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) { 2331 return; 2332 } 2333 } 2334 } 2335 2336 if (animating) { 2337 mFullRedrawNeeded = true; 2338 scheduleTraversals(); 2339 } 2340 } 2341 2342 /** 2343 * @return true if drawing was succesfull, false if an error occurred 2344 */ 2345 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff, 2346 boolean scalingRequired, Rect dirty) { 2347 2348 // Draw with software renderer. 2349 Canvas canvas; 2350 try { 2351 int left = dirty.left; 2352 int top = dirty.top; 2353 int right = dirty.right; 2354 int bottom = dirty.bottom; 2355 2356 canvas = mSurface.lockCanvas(dirty); 2357 2358 if (left != dirty.left || top != dirty.top || right != dirty.right || 2359 bottom != dirty.bottom) { 2360 attachInfo.mIgnoreDirtyState = true; 2361 } 2362 2363 // TODO: Do this in native 2364 canvas.setDensity(mDensity); 2365 } catch (Surface.OutOfResourcesException e) { 2366 handleOutOfResourcesException(e); 2367 return false; 2368 } catch (IllegalArgumentException e) { 2369 Log.e(TAG, "Could not lock surface", e); 2370 // Don't assume this is due to out of memory, it could be 2371 // something else, and if it is something else then we could 2372 // kill stuff (or ourself) for no reason. 2373 mLayoutRequested = true; // ask wm for a new surface next time. 2374 return false; 2375 } 2376 2377 try { 2378 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2379 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2380 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2381 //canvas.drawARGB(255, 255, 0, 0); 2382 } 2383 2384 // If this bitmap's format includes an alpha channel, we 2385 // need to clear it before drawing so that the child will 2386 // properly re-composite its drawing on a transparent 2387 // background. This automatically respects the clip/dirty region 2388 // or 2389 // If we are applying an offset, we need to clear the area 2390 // where the offset doesn't appear to avoid having garbage 2391 // left in the blank areas. 2392 if (!canvas.isOpaque() || yoff != 0) { 2393 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2394 } 2395 2396 dirty.setEmpty(); 2397 mIsAnimating = false; 2398 attachInfo.mDrawingTime = SystemClock.uptimeMillis(); 2399 mView.mPrivateFlags |= View.PFLAG_DRAWN; 2400 2401 if (DEBUG_DRAW) { 2402 Context cxt = mView.getContext(); 2403 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2404 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2405 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2406 } 2407 try { 2408 canvas.translate(0, -yoff); 2409 if (mTranslator != null) { 2410 mTranslator.translateCanvas(canvas); 2411 } 2412 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0); 2413 attachInfo.mSetIgnoreDirtyState = false; 2414 2415 mView.draw(canvas); 2416 2417 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2418 } finally { 2419 if (!attachInfo.mSetIgnoreDirtyState) { 2420 // Only clear the flag if it was not set during the mView.draw() call 2421 attachInfo.mIgnoreDirtyState = false; 2422 } 2423 } 2424 } finally { 2425 try { 2426 surface.unlockCanvasAndPost(canvas); 2427 } catch (IllegalArgumentException e) { 2428 Log.e(TAG, "Could not unlock surface", e); 2429 mLayoutRequested = true; // ask wm for a new surface next time. 2430 //noinspection ReturnInsideFinallyBlock 2431 return false; 2432 } 2433 2434 if (LOCAL_LOGV) { 2435 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2436 } 2437 } 2438 return true; 2439 } 2440 2441 /** 2442 * We want to draw a highlight around the current accessibility focused. 2443 * Since adding a style for all possible view is not a viable option we 2444 * have this specialized drawing method. 2445 * 2446 * Note: We are doing this here to be able to draw the highlight for 2447 * virtual views in addition to real ones. 2448 * 2449 * @param canvas The canvas on which to draw. 2450 */ 2451 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) { 2452 AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext); 2453 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 2454 return; 2455 } 2456 if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) { 2457 return; 2458 } 2459 Drawable drawable = getAccessibilityFocusedDrawable(); 2460 if (drawable == null) { 2461 return; 2462 } 2463 AccessibilityNodeProvider provider = 2464 mAccessibilityFocusedHost.getAccessibilityNodeProvider(); 2465 Rect bounds = mView.mAttachInfo.mTmpInvalRect; 2466 if (provider == null) { 2467 mAccessibilityFocusedHost.getBoundsOnScreen(bounds); 2468 } else { 2469 if (mAccessibilityFocusedVirtualView == null) { 2470 return; 2471 } 2472 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds); 2473 } 2474 bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop); 2475 bounds.intersect(0, 0, mAttachInfo.mViewRootImpl.mWidth, mAttachInfo.mViewRootImpl.mHeight); 2476 drawable.setBounds(bounds); 2477 drawable.draw(canvas); 2478 } 2479 2480 private Drawable getAccessibilityFocusedDrawable() { 2481 if (mAttachInfo != null) { 2482 // Lazily load the accessibility focus drawable. 2483 if (mAttachInfo.mAccessibilityFocusDrawable == null) { 2484 TypedValue value = new TypedValue(); 2485 final boolean resolved = mView.mContext.getTheme().resolveAttribute( 2486 R.attr.accessibilityFocusedDrawable, value, true); 2487 if (resolved) { 2488 mAttachInfo.mAccessibilityFocusDrawable = 2489 mView.mContext.getResources().getDrawable(value.resourceId); 2490 } 2491 } 2492 return mAttachInfo.mAccessibilityFocusDrawable; 2493 } 2494 return null; 2495 } 2496 2497 void invalidateDisplayLists() { 2498 final ArrayList<DisplayList> displayLists = mDisplayLists; 2499 final int count = displayLists.size(); 2500 2501 for (int i = 0; i < count; i++) { 2502 final DisplayList displayList = displayLists.get(i); 2503 if (displayList.isDirty()) { 2504 displayList.invalidate(); 2505 displayList.clear(); 2506 displayList.setDirty(false); 2507 } 2508 } 2509 2510 displayLists.clear(); 2511 } 2512 2513 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2514 final View.AttachInfo attachInfo = mAttachInfo; 2515 final Rect ci = attachInfo.mContentInsets; 2516 final Rect vi = attachInfo.mVisibleInsets; 2517 int scrollY = 0; 2518 boolean handled = false; 2519 2520 if (vi.left > ci.left || vi.top > ci.top 2521 || vi.right > ci.right || vi.bottom > ci.bottom) { 2522 // We'll assume that we aren't going to change the scroll 2523 // offset, since we want to avoid that unless it is actually 2524 // going to make the focus visible... otherwise we scroll 2525 // all over the place. 2526 scrollY = mScrollY; 2527 // We can be called for two different situations: during a draw, 2528 // to update the scroll position if the focus has changed (in which 2529 // case 'rectangle' is null), or in response to a 2530 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2531 // is non-null and we just want to scroll to whatever that 2532 // rectangle is). 2533 View focus = mView.findFocus(); 2534 if (focus == null) { 2535 return false; 2536 } 2537 View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null; 2538 if (lastScrolledFocus != null && focus != lastScrolledFocus) { 2539 // If the focus has changed, then ignore any requests to scroll 2540 // to a rectangle; first we want to make sure the entire focus 2541 // view is visible. 2542 rectangle = null; 2543 } 2544 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2545 + " rectangle=" + rectangle + " ci=" + ci 2546 + " vi=" + vi); 2547 if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) { 2548 // Optimization: if the focus hasn't changed since last 2549 // time, and no layout has happened, then just leave things 2550 // as they are. 2551 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2552 + mScrollY + " vi=" + vi.toShortString()); 2553 } else if (focus != null) { 2554 // We need to determine if the currently focused view is 2555 // within the visible part of the window and, if not, apply 2556 // a pan so it can be seen. 2557 mLastScrolledFocus = new WeakReference<View>(focus); 2558 mScrollMayChange = false; 2559 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2560 // Try to find the rectangle from the focus view. 2561 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2562 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2563 + mView.getWidth() + " h=" + mView.getHeight() 2564 + " ci=" + ci.toShortString() 2565 + " vi=" + vi.toShortString()); 2566 if (rectangle == null) { 2567 focus.getFocusedRect(mTempRect); 2568 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2569 + ": focusRect=" + mTempRect.toShortString()); 2570 if (mView instanceof ViewGroup) { 2571 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2572 focus, mTempRect); 2573 } 2574 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2575 "Focus in window: focusRect=" 2576 + mTempRect.toShortString() 2577 + " visRect=" + mVisRect.toShortString()); 2578 } else { 2579 mTempRect.set(rectangle); 2580 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2581 "Request scroll to rect: " 2582 + mTempRect.toShortString() 2583 + " visRect=" + mVisRect.toShortString()); 2584 } 2585 if (mTempRect.intersect(mVisRect)) { 2586 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2587 "Focus window visible rect: " 2588 + mTempRect.toShortString()); 2589 if (mTempRect.height() > 2590 (mView.getHeight()-vi.top-vi.bottom)) { 2591 // If the focus simply is not going to fit, then 2592 // best is probably just to leave things as-is. 2593 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2594 "Too tall; leaving scrollY=" + scrollY); 2595 } else if ((mTempRect.top-scrollY) < vi.top) { 2596 scrollY -= vi.top - (mTempRect.top-scrollY); 2597 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2598 "Top covered; scrollY=" + scrollY); 2599 } else if ((mTempRect.bottom-scrollY) 2600 > (mView.getHeight()-vi.bottom)) { 2601 scrollY += (mTempRect.bottom-scrollY) 2602 - (mView.getHeight()-vi.bottom); 2603 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2604 "Bottom covered; scrollY=" + scrollY); 2605 } 2606 handled = true; 2607 } 2608 } 2609 } 2610 } 2611 2612 if (scrollY != mScrollY) { 2613 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2614 + mScrollY + " , new=" + scrollY); 2615 if (!immediate && mResizeBuffer == null) { 2616 if (mScroller == null) { 2617 mScroller = new Scroller(mView.getContext()); 2618 } 2619 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2620 } else if (mScroller != null) { 2621 mScroller.abortAnimation(); 2622 } 2623 mScrollY = scrollY; 2624 } 2625 2626 return handled; 2627 } 2628 2629 /** 2630 * @hide 2631 */ 2632 public View getAccessibilityFocusedHost() { 2633 return mAccessibilityFocusedHost; 2634 } 2635 2636 /** 2637 * @hide 2638 */ 2639 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() { 2640 return mAccessibilityFocusedVirtualView; 2641 } 2642 2643 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) { 2644 // If we have a virtual view with accessibility focus we need 2645 // to clear the focus and invalidate the virtual view bounds. 2646 if (mAccessibilityFocusedVirtualView != null) { 2647 2648 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView; 2649 View focusHost = mAccessibilityFocusedHost; 2650 focusHost.clearAccessibilityFocusNoCallbacks(); 2651 2652 // Wipe the state of the current accessibility focus since 2653 // the call into the provider to clear accessibility focus 2654 // will fire an accessibility event which will end up calling 2655 // this method and we want to have clean state when this 2656 // invocation happens. 2657 mAccessibilityFocusedHost = null; 2658 mAccessibilityFocusedVirtualView = null; 2659 2660 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider(); 2661 if (provider != null) { 2662 // Invalidate the area of the cleared accessibility focus. 2663 focusNode.getBoundsInParent(mTempRect); 2664 focusHost.invalidate(mTempRect); 2665 // Clear accessibility focus in the virtual node. 2666 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 2667 focusNode.getSourceNodeId()); 2668 provider.performAction(virtualNodeId, 2669 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); 2670 } 2671 focusNode.recycle(); 2672 } 2673 if (mAccessibilityFocusedHost != null) { 2674 // Clear accessibility focus in the view. 2675 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(); 2676 } 2677 2678 // Set the new focus host and node. 2679 mAccessibilityFocusedHost = view; 2680 mAccessibilityFocusedVirtualView = node; 2681 } 2682 2683 public void requestChildFocus(View child, View focused) { 2684 if (DEBUG_INPUT_RESIZE) { 2685 Log.v(TAG, "Request child focus: focus now " + focused); 2686 } 2687 checkThread(); 2688 scheduleTraversals(); 2689 } 2690 2691 public void clearChildFocus(View child) { 2692 if (DEBUG_INPUT_RESIZE) { 2693 Log.v(TAG, "Clearing child focus"); 2694 } 2695 checkThread(); 2696 scheduleTraversals(); 2697 } 2698 2699 @Override 2700 public ViewParent getParentForAccessibility() { 2701 return null; 2702 } 2703 2704 public void focusableViewAvailable(View v) { 2705 checkThread(); 2706 if (mView != null) { 2707 if (!mView.hasFocus()) { 2708 v.requestFocus(); 2709 } else { 2710 // the one case where will transfer focus away from the current one 2711 // is if the current view is a view group that prefers to give focus 2712 // to its children first AND the view is a descendant of it. 2713 View focused = mView.findFocus(); 2714 if (focused instanceof ViewGroup) { 2715 ViewGroup group = (ViewGroup) focused; 2716 if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 2717 && isViewDescendantOf(v, focused)) { 2718 v.requestFocus(); 2719 } 2720 } 2721 } 2722 } 2723 } 2724 2725 public void recomputeViewAttributes(View child) { 2726 checkThread(); 2727 if (mView == child) { 2728 mAttachInfo.mRecomputeGlobalAttributes = true; 2729 if (!mWillDrawSoon) { 2730 scheduleTraversals(); 2731 } 2732 } 2733 } 2734 2735 void dispatchDetachedFromWindow() { 2736 if (mView != null && mView.mAttachInfo != null) { 2737 if (mAttachInfo.mHardwareRenderer != null && 2738 mAttachInfo.mHardwareRenderer.isEnabled()) { 2739 mAttachInfo.mHardwareRenderer.validate(); 2740 } 2741 mView.dispatchDetachedFromWindow(); 2742 } 2743 2744 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2745 mAccessibilityManager.removeAccessibilityStateChangeListener( 2746 mAccessibilityInteractionConnectionManager); 2747 removeSendWindowContentChangedCallback(); 2748 2749 destroyHardwareRenderer(); 2750 2751 setAccessibilityFocus(null, null); 2752 2753 mView = null; 2754 mAttachInfo.mRootView = null; 2755 mAttachInfo.mSurface = null; 2756 2757 mSurface.release(); 2758 2759 if (mInputQueueCallback != null && mInputQueue != null) { 2760 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2761 mInputQueueCallback = null; 2762 mInputQueue = null; 2763 } else if (mInputEventReceiver != null) { 2764 mInputEventReceiver.dispose(); 2765 mInputEventReceiver = null; 2766 } 2767 try { 2768 mWindowSession.remove(mWindow); 2769 } catch (RemoteException e) { 2770 } 2771 2772 // Dispose the input channel after removing the window so the Window Manager 2773 // doesn't interpret the input channel being closed as an abnormal termination. 2774 if (mInputChannel != null) { 2775 mInputChannel.dispose(); 2776 mInputChannel = null; 2777 } 2778 2779 unscheduleTraversals(); 2780 } 2781 2782 void updateConfiguration(Configuration config, boolean force) { 2783 if (DEBUG_CONFIGURATION) Log.v(TAG, 2784 "Applying new config to window " 2785 + mWindowAttributes.getTitle() 2786 + ": " + config); 2787 2788 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded(); 2789 if (ci != null) { 2790 config = new Configuration(config); 2791 ci.applyToConfiguration(mNoncompatDensity, config); 2792 } 2793 2794 synchronized (sConfigCallbacks) { 2795 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2796 sConfigCallbacks.get(i).onConfigurationChanged(config); 2797 } 2798 } 2799 if (mView != null) { 2800 // At this point the resources have been updated to 2801 // have the most recent config, whatever that is. Use 2802 // the one in them which may be newer. 2803 config = mView.getResources().getConfiguration(); 2804 if (force || mLastConfiguration.diff(config) != 0) { 2805 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection(); 2806 final int currentLayoutDirection = config.getLayoutDirection(); 2807 mLastConfiguration.setTo(config); 2808 if (lastLayoutDirection != currentLayoutDirection && 2809 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) { 2810 mView.setLayoutDirection(currentLayoutDirection); 2811 } 2812 mView.dispatchConfigurationChanged(config); 2813 } 2814 } 2815 } 2816 2817 /** 2818 * Return true if child is an ancestor of parent, (or equal to the parent). 2819 */ 2820 public static boolean isViewDescendantOf(View child, View parent) { 2821 if (child == parent) { 2822 return true; 2823 } 2824 2825 final ViewParent theParent = child.getParent(); 2826 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2827 } 2828 2829 private static void forceLayout(View view) { 2830 view.forceLayout(); 2831 if (view instanceof ViewGroup) { 2832 ViewGroup group = (ViewGroup) view; 2833 final int count = group.getChildCount(); 2834 for (int i = 0; i < count; i++) { 2835 forceLayout(group.getChildAt(i)); 2836 } 2837 } 2838 } 2839 2840 private final static int MSG_INVALIDATE = 1; 2841 private final static int MSG_INVALIDATE_RECT = 2; 2842 private final static int MSG_DIE = 3; 2843 private final static int MSG_RESIZED = 4; 2844 private final static int MSG_RESIZED_REPORT = 5; 2845 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 2846 private final static int MSG_DISPATCH_KEY = 7; 2847 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 2848 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 2849 private final static int MSG_IME_FINISHED_EVENT = 10; 2850 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 2851 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 2852 private final static int MSG_CHECK_FOCUS = 13; 2853 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 2854 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 2855 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 2856 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 2857 private final static int MSG_UPDATE_CONFIGURATION = 18; 2858 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 2859 private final static int MSG_DISPATCH_SCREEN_STATE = 20; 2860 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21; 2861 private final static int MSG_DISPATCH_DONE_ANIMATING = 22; 2862 private final static int MSG_INVALIDATE_WORLD = 23; 2863 private final static int MSG_WINDOW_MOVED = 24; 2864 2865 final class ViewRootHandler extends Handler { 2866 @Override 2867 public String getMessageName(Message message) { 2868 switch (message.what) { 2869 case MSG_INVALIDATE: 2870 return "MSG_INVALIDATE"; 2871 case MSG_INVALIDATE_RECT: 2872 return "MSG_INVALIDATE_RECT"; 2873 case MSG_DIE: 2874 return "MSG_DIE"; 2875 case MSG_RESIZED: 2876 return "MSG_RESIZED"; 2877 case MSG_RESIZED_REPORT: 2878 return "MSG_RESIZED_REPORT"; 2879 case MSG_WINDOW_FOCUS_CHANGED: 2880 return "MSG_WINDOW_FOCUS_CHANGED"; 2881 case MSG_DISPATCH_KEY: 2882 return "MSG_DISPATCH_KEY"; 2883 case MSG_DISPATCH_APP_VISIBILITY: 2884 return "MSG_DISPATCH_APP_VISIBILITY"; 2885 case MSG_DISPATCH_GET_NEW_SURFACE: 2886 return "MSG_DISPATCH_GET_NEW_SURFACE"; 2887 case MSG_IME_FINISHED_EVENT: 2888 return "MSG_IME_FINISHED_EVENT"; 2889 case MSG_DISPATCH_KEY_FROM_IME: 2890 return "MSG_DISPATCH_KEY_FROM_IME"; 2891 case MSG_FINISH_INPUT_CONNECTION: 2892 return "MSG_FINISH_INPUT_CONNECTION"; 2893 case MSG_CHECK_FOCUS: 2894 return "MSG_CHECK_FOCUS"; 2895 case MSG_CLOSE_SYSTEM_DIALOGS: 2896 return "MSG_CLOSE_SYSTEM_DIALOGS"; 2897 case MSG_DISPATCH_DRAG_EVENT: 2898 return "MSG_DISPATCH_DRAG_EVENT"; 2899 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 2900 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 2901 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 2902 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 2903 case MSG_UPDATE_CONFIGURATION: 2904 return "MSG_UPDATE_CONFIGURATION"; 2905 case MSG_PROCESS_INPUT_EVENTS: 2906 return "MSG_PROCESS_INPUT_EVENTS"; 2907 case MSG_DISPATCH_SCREEN_STATE: 2908 return "MSG_DISPATCH_SCREEN_STATE"; 2909 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 2910 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 2911 case MSG_DISPATCH_DONE_ANIMATING: 2912 return "MSG_DISPATCH_DONE_ANIMATING"; 2913 case MSG_WINDOW_MOVED: 2914 return "MSG_WINDOW_MOVED"; 2915 } 2916 return super.getMessageName(message); 2917 } 2918 2919 @Override 2920 public void handleMessage(Message msg) { 2921 switch (msg.what) { 2922 case MSG_INVALIDATE: 2923 ((View) msg.obj).invalidate(); 2924 break; 2925 case MSG_INVALIDATE_RECT: 2926 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 2927 info.target.invalidate(info.left, info.top, info.right, info.bottom); 2928 info.recycle(); 2929 break; 2930 case MSG_IME_FINISHED_EVENT: 2931 handleImeFinishedEvent(msg.arg1, msg.arg2 != 0); 2932 break; 2933 case MSG_PROCESS_INPUT_EVENTS: 2934 mProcessInputEventsScheduled = false; 2935 doProcessInputEvents(); 2936 break; 2937 case MSG_DISPATCH_APP_VISIBILITY: 2938 handleAppVisibility(msg.arg1 != 0); 2939 break; 2940 case MSG_DISPATCH_GET_NEW_SURFACE: 2941 handleGetNewSurface(); 2942 break; 2943 case MSG_RESIZED: { 2944 // Recycled in the fall through... 2945 SomeArgs args = (SomeArgs) msg.obj; 2946 if (mWinFrame.equals(args.arg1) 2947 && mPendingContentInsets.equals(args.arg2) 2948 && mPendingVisibleInsets.equals(args.arg3) 2949 && args.arg4 == null) { 2950 break; 2951 } 2952 } // fall through... 2953 case MSG_RESIZED_REPORT: 2954 if (mAdded) { 2955 SomeArgs args = (SomeArgs) msg.obj; 2956 2957 Configuration config = (Configuration) args.arg4; 2958 if (config != null) { 2959 updateConfiguration(config, false); 2960 } 2961 2962 mWinFrame.set((Rect) args.arg1); 2963 mPendingContentInsets.set((Rect) args.arg2); 2964 mPendingVisibleInsets.set((Rect) args.arg3); 2965 2966 args.recycle(); 2967 2968 if (msg.what == MSG_RESIZED_REPORT) { 2969 mReportNextDraw = true; 2970 } 2971 2972 if (mView != null) { 2973 forceLayout(mView); 2974 } 2975 2976 requestLayout(); 2977 } 2978 break; 2979 case MSG_WINDOW_MOVED: 2980 if (mAdded) { 2981 final int w = mWinFrame.width(); 2982 final int h = mWinFrame.height(); 2983 final int l = msg.arg1; 2984 final int t = msg.arg2; 2985 mWinFrame.left = l; 2986 mWinFrame.right = l + w; 2987 mWinFrame.top = t; 2988 mWinFrame.bottom = t + h; 2989 2990 if (mView != null) { 2991 forceLayout(mView); 2992 } 2993 requestLayout(); 2994 } 2995 break; 2996 case MSG_WINDOW_FOCUS_CHANGED: { 2997 if (mAdded) { 2998 boolean hasWindowFocus = msg.arg1 != 0; 2999 mAttachInfo.mHasWindowFocus = hasWindowFocus; 3000 3001 profileRendering(hasWindowFocus); 3002 3003 if (hasWindowFocus) { 3004 boolean inTouchMode = msg.arg2 != 0; 3005 ensureTouchModeLocally(inTouchMode); 3006 3007 if (mAttachInfo.mHardwareRenderer != null && 3008 mSurface != null && mSurface.isValid()) { 3009 mFullRedrawNeeded = true; 3010 try { 3011 mAttachInfo.mHardwareRenderer.initializeIfNeeded( 3012 mWidth, mHeight, mHolder.getSurface()); 3013 } catch (Surface.OutOfResourcesException e) { 3014 Log.e(TAG, "OutOfResourcesException locking surface", e); 3015 try { 3016 if (!mWindowSession.outOfMemory(mWindow)) { 3017 Slog.w(TAG, "No processes killed for memory; killing self"); 3018 Process.killProcess(Process.myPid()); 3019 } 3020 } catch (RemoteException ex) { 3021 } 3022 // Retry in a bit. 3023 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 3024 return; 3025 } 3026 } 3027 } 3028 3029 mLastWasImTarget = WindowManager.LayoutParams 3030 .mayUseInputMethod(mWindowAttributes.flags); 3031 3032 InputMethodManager imm = InputMethodManager.peekInstance(); 3033 if (mView != null) { 3034 if (hasWindowFocus && imm != null && mLastWasImTarget) { 3035 imm.startGettingWindowFocus(mView); 3036 } 3037 mAttachInfo.mKeyDispatchState.reset(); 3038 mView.dispatchWindowFocusChanged(hasWindowFocus); 3039 } 3040 3041 // Note: must be done after the focus change callbacks, 3042 // so all of the view state is set up correctly. 3043 if (hasWindowFocus) { 3044 if (imm != null && mLastWasImTarget) { 3045 imm.onWindowFocus(mView, mView.findFocus(), 3046 mWindowAttributes.softInputMode, 3047 !mHasHadWindowFocus, mWindowAttributes.flags); 3048 } 3049 // Clear the forward bit. We can just do this directly, since 3050 // the window manager doesn't care about it. 3051 mWindowAttributes.softInputMode &= 3052 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3053 ((WindowManager.LayoutParams)mView.getLayoutParams()) 3054 .softInputMode &= 3055 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 3056 mHasHadWindowFocus = true; 3057 } 3058 3059 setAccessibilityFocus(null, null); 3060 3061 if (mView != null && mAccessibilityManager.isEnabled()) { 3062 if (hasWindowFocus) { 3063 mView.sendAccessibilityEvent( 3064 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 3065 } 3066 } 3067 } 3068 } break; 3069 case MSG_DIE: 3070 doDie(); 3071 break; 3072 case MSG_DISPATCH_KEY: { 3073 KeyEvent event = (KeyEvent)msg.obj; 3074 enqueueInputEvent(event, null, 0, true); 3075 } break; 3076 case MSG_DISPATCH_KEY_FROM_IME: { 3077 if (LOCAL_LOGV) Log.v( 3078 TAG, "Dispatching key " 3079 + msg.obj + " from IME to " + mView); 3080 KeyEvent event = (KeyEvent)msg.obj; 3081 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 3082 // The IME is trying to say this event is from the 3083 // system! Bad bad bad! 3084 //noinspection UnusedAssignment 3085 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 3086 } 3087 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 3088 } break; 3089 case MSG_FINISH_INPUT_CONNECTION: { 3090 InputMethodManager imm = InputMethodManager.peekInstance(); 3091 if (imm != null) { 3092 imm.reportFinishInputConnection((InputConnection)msg.obj); 3093 } 3094 } break; 3095 case MSG_CHECK_FOCUS: { 3096 InputMethodManager imm = InputMethodManager.peekInstance(); 3097 if (imm != null) { 3098 imm.checkFocus(); 3099 } 3100 } break; 3101 case MSG_CLOSE_SYSTEM_DIALOGS: { 3102 if (mView != null) { 3103 mView.onCloseSystemDialogs((String)msg.obj); 3104 } 3105 } break; 3106 case MSG_DISPATCH_DRAG_EVENT: 3107 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 3108 DragEvent event = (DragEvent)msg.obj; 3109 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 3110 handleDragEvent(event); 3111 } break; 3112 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 3113 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); 3114 } break; 3115 case MSG_UPDATE_CONFIGURATION: { 3116 Configuration config = (Configuration)msg.obj; 3117 if (config.isOtherSeqNewer(mLastConfiguration)) { 3118 config = mLastConfiguration; 3119 } 3120 updateConfiguration(config, false); 3121 } break; 3122 case MSG_DISPATCH_SCREEN_STATE: { 3123 if (mView != null) { 3124 handleScreenStateChange(msg.arg1 == 1); 3125 } 3126 } break; 3127 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3128 setAccessibilityFocus(null, null); 3129 } break; 3130 case MSG_DISPATCH_DONE_ANIMATING: { 3131 handleDispatchDoneAnimating(); 3132 } break; 3133 case MSG_INVALIDATE_WORLD: { 3134 if (mView != null) { 3135 invalidateWorld(mView); 3136 } 3137 } break; 3138 } 3139 } 3140 } 3141 3142 final ViewRootHandler mHandler = new ViewRootHandler(); 3143 3144 /** 3145 * Something in the current window tells us we need to change the touch mode. For 3146 * example, we are not in touch mode, and the user touches the screen. 3147 * 3148 * If the touch mode has changed, tell the window manager, and handle it locally. 3149 * 3150 * @param inTouchMode Whether we want to be in touch mode. 3151 * @return True if the touch mode changed and focus changed was changed as a result 3152 */ 3153 boolean ensureTouchMode(boolean inTouchMode) { 3154 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3155 + "touch mode is " + mAttachInfo.mInTouchMode); 3156 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3157 3158 // tell the window manager 3159 try { 3160 mWindowSession.setInTouchMode(inTouchMode); 3161 } catch (RemoteException e) { 3162 throw new RuntimeException(e); 3163 } 3164 3165 // handle the change 3166 return ensureTouchModeLocally(inTouchMode); 3167 } 3168 3169 /** 3170 * Ensure that the touch mode for this window is set, and if it is changing, 3171 * take the appropriate action. 3172 * @param inTouchMode Whether we want to be in touch mode. 3173 * @return True if the touch mode changed and focus changed was changed as a result 3174 */ 3175 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3176 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3177 + "touch mode is " + mAttachInfo.mInTouchMode); 3178 3179 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3180 3181 mAttachInfo.mInTouchMode = inTouchMode; 3182 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3183 3184 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3185 } 3186 3187 private boolean enterTouchMode() { 3188 if (mView != null) { 3189 if (mView.hasFocus()) { 3190 // note: not relying on mFocusedView here because this could 3191 // be when the window is first being added, and mFocused isn't 3192 // set yet. 3193 final View focused = mView.findFocus(); 3194 if (focused != null && !focused.isFocusableInTouchMode()) { 3195 final ViewGroup ancestorToTakeFocus = 3196 findAncestorToTakeFocusInTouchMode(focused); 3197 if (ancestorToTakeFocus != null) { 3198 // there is an ancestor that wants focus after its descendants that 3199 // is focusable in touch mode.. give it focus 3200 return ancestorToTakeFocus.requestFocus(); 3201 } else { 3202 // nothing appropriate to have focus in touch mode, clear it out 3203 focused.unFocus(); 3204 return true; 3205 } 3206 } 3207 } 3208 } 3209 return false; 3210 } 3211 3212 /** 3213 * Find an ancestor of focused that wants focus after its descendants and is 3214 * focusable in touch mode. 3215 * @param focused The currently focused view. 3216 * @return An appropriate view, or null if no such view exists. 3217 */ 3218 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3219 ViewParent parent = focused.getParent(); 3220 while (parent instanceof ViewGroup) { 3221 final ViewGroup vgParent = (ViewGroup) parent; 3222 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3223 && vgParent.isFocusableInTouchMode()) { 3224 return vgParent; 3225 } 3226 if (vgParent.isRootNamespace()) { 3227 return null; 3228 } else { 3229 parent = vgParent.getParent(); 3230 } 3231 } 3232 return null; 3233 } 3234 3235 private boolean leaveTouchMode() { 3236 if (mView != null) { 3237 if (mView.hasFocus()) { 3238 View focusedView = mView.findFocus(); 3239 if (!(focusedView instanceof ViewGroup)) { 3240 // some view has focus, let it keep it 3241 return false; 3242 } else if (((ViewGroup) focusedView).getDescendantFocusability() != 3243 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3244 // some view group has focus, and doesn't prefer its children 3245 // over itself for focus, so let them keep it. 3246 return false; 3247 } 3248 } 3249 3250 // find the best view to give focus to in this brave new non-touch-mode 3251 // world 3252 final View focused = focusSearch(null, View.FOCUS_DOWN); 3253 if (focused != null) { 3254 return focused.requestFocus(View.FOCUS_DOWN); 3255 } 3256 } 3257 return false; 3258 } 3259 3260 private int deliverInputEvent(QueuedInputEvent q) { 3261 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent"); 3262 try { 3263 if (q.mEvent instanceof KeyEvent) { 3264 return deliverKeyEvent(q); 3265 } else { 3266 final int source = q.mEvent.getSource(); 3267 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3268 return deliverPointerEvent(q); 3269 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3270 return deliverTrackballEvent(q); 3271 } else { 3272 return deliverGenericMotionEvent(q); 3273 } 3274 } 3275 } finally { 3276 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 3277 } 3278 } 3279 3280 private int deliverInputEventPostIme(QueuedInputEvent q) { 3281 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEventPostIme"); 3282 try { 3283 if (q.mEvent instanceof KeyEvent) { 3284 return deliverKeyEventPostIme(q); 3285 } else { 3286 final int source = q.mEvent.getSource(); 3287 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3288 return deliverTrackballEventPostIme(q); 3289 } else { 3290 return deliverGenericMotionEventPostIme(q); 3291 } 3292 } 3293 } finally { 3294 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 3295 } 3296 } 3297 3298 private int deliverPointerEvent(QueuedInputEvent q) { 3299 final MotionEvent event = (MotionEvent)q.mEvent; 3300 final boolean isTouchEvent = event.isTouchEvent(); 3301 if (mInputEventConsistencyVerifier != null) { 3302 if (isTouchEvent) { 3303 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 3304 } else { 3305 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3306 } 3307 } 3308 3309 // If there is no view, then the event will not be handled. 3310 if (mView == null || !mAdded) { 3311 return EVENT_NOT_HANDLED; 3312 } 3313 3314 // Translate the pointer event for compatibility, if needed. 3315 if (mTranslator != null) { 3316 mTranslator.translateEventInScreenToAppWindow(event); 3317 } 3318 3319 // Enter touch mode on down or scroll. 3320 final int action = event.getAction(); 3321 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3322 ensureTouchMode(true); 3323 } 3324 3325 // Offset the scroll position. 3326 if (mCurScrollY != 0) { 3327 event.offsetLocation(0, mCurScrollY); 3328 } 3329 if (MEASURE_LATENCY) { 3330 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano()); 3331 } 3332 3333 // Remember the touch position for possible drag-initiation. 3334 if (isTouchEvent) { 3335 mLastTouchPoint.x = event.getRawX(); 3336 mLastTouchPoint.y = event.getRawY(); 3337 } 3338 3339 // Dispatch touch to view hierarchy. 3340 boolean handled = mView.dispatchPointerEvent(event); 3341 if (MEASURE_LATENCY) { 3342 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano()); 3343 } 3344 return handled ? EVENT_HANDLED : EVENT_NOT_HANDLED; 3345 } 3346 3347 private int deliverTrackballEvent(QueuedInputEvent q) { 3348 final MotionEvent event = (MotionEvent)q.mEvent; 3349 if (mInputEventConsistencyVerifier != null) { 3350 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 3351 } 3352 3353 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3354 if (LOCAL_LOGV) 3355 Log.v(TAG, "Dispatching trackball " + event + " to " + mView); 3356 3357 // Dispatch to the IME before propagating down the view hierarchy. 3358 // The IME will eventually call back into handleImeFinishedEvent. 3359 if (mLastWasImTarget) { 3360 InputMethodManager imm = InputMethodManager.peekInstance(); 3361 if (imm != null) { 3362 final int seq = event.getSequenceNumber(); 3363 if (DEBUG_IMF) 3364 Log.v(TAG, "Sending trackball event to IME: seq=" 3365 + seq + " event=" + event); 3366 int result = imm.dispatchTrackballEvent(mView.getContext(), seq, event, 3367 mInputMethodCallback); 3368 if (result != EVENT_NOT_HANDLED) { 3369 return result; 3370 } 3371 } 3372 } 3373 } 3374 3375 // Not dispatching to IME, continue with post IME actions. 3376 return deliverTrackballEventPostIme(q); 3377 } 3378 3379 private int deliverTrackballEventPostIme(QueuedInputEvent q) { 3380 final MotionEvent event = (MotionEvent) q.mEvent; 3381 3382 // If there is no view, then the event will not be handled. 3383 if (mView == null || !mAdded) { 3384 return EVENT_NOT_HANDLED; 3385 } 3386 3387 // Deliver the trackball event to the view. 3388 if (mView.dispatchTrackballEvent(event)) { 3389 // If we reach this, we delivered a trackball event to mView and 3390 // mView consumed it. Because we will not translate the trackball 3391 // event into a key event, touch mode will not exit, so we exit 3392 // touch mode here. 3393 ensureTouchMode(false); 3394 mLastTrackballTime = Integer.MIN_VALUE; 3395 return EVENT_HANDLED; 3396 } 3397 3398 // Translate the trackball event into DPAD keys and try to deliver those. 3399 final TrackballAxis x = mTrackballAxisX; 3400 final TrackballAxis y = mTrackballAxisY; 3401 3402 long curTime = SystemClock.uptimeMillis(); 3403 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) { 3404 // It has been too long since the last movement, 3405 // so restart at the beginning. 3406 x.reset(0); 3407 y.reset(0); 3408 mLastTrackballTime = curTime; 3409 } 3410 3411 final int action = event.getAction(); 3412 final int metaState = event.getMetaState(); 3413 switch (action) { 3414 case MotionEvent.ACTION_DOWN: 3415 x.reset(2); 3416 y.reset(2); 3417 enqueueInputEvent(new KeyEvent(curTime, curTime, 3418 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3419 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3420 InputDevice.SOURCE_KEYBOARD)); 3421 break; 3422 case MotionEvent.ACTION_UP: 3423 x.reset(2); 3424 y.reset(2); 3425 enqueueInputEvent(new KeyEvent(curTime, curTime, 3426 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3427 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3428 InputDevice.SOURCE_KEYBOARD)); 3429 break; 3430 } 3431 3432 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step=" 3433 + x.step + " dir=" + x.dir + " acc=" + x.acceleration 3434 + " move=" + event.getX() 3435 + " / Y=" + y.position + " step=" 3436 + y.step + " dir=" + y.dir + " acc=" + y.acceleration 3437 + " move=" + event.getY()); 3438 final float xOff = x.collect(event.getX(), event.getEventTime(), "X"); 3439 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y"); 3440 3441 // Generate DPAD events based on the trackball movement. 3442 // We pick the axis that has moved the most as the direction of 3443 // the DPAD. When we generate DPAD events for one axis, then the 3444 // other axis is reset -- we don't want to perform DPAD jumps due 3445 // to slight movements in the trackball when making major movements 3446 // along the other axis. 3447 int keycode = 0; 3448 int movement = 0; 3449 float accel = 1; 3450 if (xOff > yOff) { 3451 movement = x.generate((2/event.getXPrecision())); 3452 if (movement != 0) { 3453 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3454 : KeyEvent.KEYCODE_DPAD_LEFT; 3455 accel = x.acceleration; 3456 y.reset(2); 3457 } 3458 } else if (yOff > 0) { 3459 movement = y.generate((2/event.getYPrecision())); 3460 if (movement != 0) { 3461 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3462 : KeyEvent.KEYCODE_DPAD_UP; 3463 accel = y.acceleration; 3464 x.reset(2); 3465 } 3466 } 3467 3468 if (keycode != 0) { 3469 if (movement < 0) movement = -movement; 3470 int accelMovement = (int)(movement * accel); 3471 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 3472 + " accelMovement=" + accelMovement 3473 + " accel=" + accel); 3474 if (accelMovement > movement) { 3475 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3476 + keycode); 3477 movement--; 3478 int repeatCount = accelMovement - movement; 3479 enqueueInputEvent(new KeyEvent(curTime, curTime, 3480 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 3481 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3482 InputDevice.SOURCE_KEYBOARD)); 3483 } 3484 while (movement > 0) { 3485 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3486 + keycode); 3487 movement--; 3488 curTime = SystemClock.uptimeMillis(); 3489 enqueueInputEvent(new KeyEvent(curTime, curTime, 3490 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 3491 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3492 InputDevice.SOURCE_KEYBOARD)); 3493 enqueueInputEvent(new KeyEvent(curTime, curTime, 3494 KeyEvent.ACTION_UP, keycode, 0, metaState, 3495 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3496 InputDevice.SOURCE_KEYBOARD)); 3497 } 3498 mLastTrackballTime = curTime; 3499 } 3500 3501 // Unfortunately we can't tell whether the application consumed the keys, so 3502 // we always consider the trackball event handled. 3503 return EVENT_HANDLED; 3504 } 3505 3506 private int deliverGenericMotionEvent(QueuedInputEvent q) { 3507 final MotionEvent event = (MotionEvent)q.mEvent; 3508 if (mInputEventConsistencyVerifier != null) { 3509 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3510 } 3511 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3512 if (LOCAL_LOGV) 3513 Log.v(TAG, "Dispatching generic motion " + event + " to " + mView); 3514 3515 // Dispatch to the IME before propagating down the view hierarchy. 3516 // The IME will eventually call back into handleImeFinishedEvent. 3517 if (mLastWasImTarget) { 3518 InputMethodManager imm = InputMethodManager.peekInstance(); 3519 if (imm != null) { 3520 final int seq = event.getSequenceNumber(); 3521 if (DEBUG_IMF) 3522 Log.v(TAG, "Sending generic motion event to IME: seq=" 3523 + seq + " event=" + event); 3524 int result = imm.dispatchGenericMotionEvent(mView.getContext(), seq, event, 3525 mInputMethodCallback); 3526 if (result != EVENT_NOT_HANDLED) { 3527 return result; 3528 } 3529 } 3530 } 3531 } 3532 3533 // Not dispatching to IME, continue with post IME actions. 3534 return deliverGenericMotionEventPostIme(q); 3535 } 3536 3537 private int deliverGenericMotionEventPostIme(QueuedInputEvent q) { 3538 final MotionEvent event = (MotionEvent) q.mEvent; 3539 final int source = event.getSource(); 3540 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0; 3541 final boolean isTouchPad = (source & InputDevice.SOURCE_CLASS_POSITION) != 0; 3542 3543 // If there is no view, then the event will not be handled. 3544 if (mView == null || !mAdded) { 3545 if (isJoystick) { 3546 updateJoystickDirection(event, false); 3547 } else if (isTouchPad) { 3548 mSimulatedDpad.updateTouchPad(this, event, false); 3549 } 3550 return EVENT_NOT_HANDLED; 3551 } 3552 3553 // Deliver the event to the view. 3554 if (mView.dispatchGenericMotionEvent(event)) { 3555 if (isJoystick) { 3556 updateJoystickDirection(event, false); 3557 } else if (isTouchPad) { 3558 mSimulatedDpad.updateTouchPad(this, event, false); 3559 } 3560 return EVENT_HANDLED; 3561 } 3562 3563 if (isJoystick) { 3564 // Translate the joystick event into DPAD keys and try to deliver 3565 // those. 3566 updateJoystickDirection(event, true); 3567 return EVENT_HANDLED; 3568 } 3569 if (isTouchPad) { 3570 mSimulatedDpad.updateTouchPad(this, event, true); 3571 return EVENT_HANDLED; 3572 } 3573 return EVENT_NOT_HANDLED; 3574 } 3575 3576 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) { 3577 final long time = event.getEventTime(); 3578 final int metaState = event.getMetaState(); 3579 final int deviceId = event.getDeviceId(); 3580 final int source = event.getSource(); 3581 3582 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X)); 3583 if (xDirection == 0) { 3584 xDirection = joystickAxisValueToDirection(event.getX()); 3585 } 3586 3587 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 3588 if (yDirection == 0) { 3589 yDirection = joystickAxisValueToDirection(event.getY()); 3590 } 3591 3592 if (xDirection != mLastJoystickXDirection) { 3593 if (mLastJoystickXKeyCode != 0) { 3594 enqueueInputEvent(new KeyEvent(time, time, 3595 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState, 3596 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3597 mLastJoystickXKeyCode = 0; 3598 } 3599 3600 mLastJoystickXDirection = xDirection; 3601 3602 if (xDirection != 0 && synthesizeNewKeys) { 3603 mLastJoystickXKeyCode = xDirection > 0 3604 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 3605 enqueueInputEvent(new KeyEvent(time, time, 3606 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState, 3607 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3608 } 3609 } 3610 3611 if (yDirection != mLastJoystickYDirection) { 3612 if (mLastJoystickYKeyCode != 0) { 3613 enqueueInputEvent(new KeyEvent(time, time, 3614 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState, 3615 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3616 mLastJoystickYKeyCode = 0; 3617 } 3618 3619 mLastJoystickYDirection = yDirection; 3620 3621 if (yDirection != 0 && synthesizeNewKeys) { 3622 mLastJoystickYKeyCode = yDirection > 0 3623 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 3624 enqueueInputEvent(new KeyEvent(time, time, 3625 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState, 3626 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3627 } 3628 } 3629 } 3630 3631 private static int joystickAxisValueToDirection(float value) { 3632 if (value >= 0.5f) { 3633 return 1; 3634 } else if (value <= -0.5f) { 3635 return -1; 3636 } else { 3637 return 0; 3638 } 3639 } 3640 3641 /** 3642 * Returns true if the key is used for keyboard navigation. 3643 * @param keyEvent The key event. 3644 * @return True if the key is used for keyboard navigation. 3645 */ 3646 private static boolean isNavigationKey(KeyEvent keyEvent) { 3647 switch (keyEvent.getKeyCode()) { 3648 case KeyEvent.KEYCODE_DPAD_LEFT: 3649 case KeyEvent.KEYCODE_DPAD_RIGHT: 3650 case KeyEvent.KEYCODE_DPAD_UP: 3651 case KeyEvent.KEYCODE_DPAD_DOWN: 3652 case KeyEvent.KEYCODE_DPAD_CENTER: 3653 case KeyEvent.KEYCODE_PAGE_UP: 3654 case KeyEvent.KEYCODE_PAGE_DOWN: 3655 case KeyEvent.KEYCODE_MOVE_HOME: 3656 case KeyEvent.KEYCODE_MOVE_END: 3657 case KeyEvent.KEYCODE_TAB: 3658 case KeyEvent.KEYCODE_SPACE: 3659 case KeyEvent.KEYCODE_ENTER: 3660 return true; 3661 } 3662 return false; 3663 } 3664 3665 /** 3666 * Returns true if the key is used for typing. 3667 * @param keyEvent The key event. 3668 * @return True if the key is used for typing. 3669 */ 3670 private static boolean isTypingKey(KeyEvent keyEvent) { 3671 return keyEvent.getUnicodeChar() > 0; 3672 } 3673 3674 /** 3675 * See if the key event means we should leave touch mode (and leave touch mode if so). 3676 * @param event The key event. 3677 * @return Whether this key event should be consumed (meaning the act of 3678 * leaving touch mode alone is considered the event). 3679 */ 3680 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 3681 // Only relevant in touch mode. 3682 if (!mAttachInfo.mInTouchMode) { 3683 return false; 3684 } 3685 3686 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 3687 final int action = event.getAction(); 3688 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 3689 return false; 3690 } 3691 3692 // Don't leave touch mode if the IME told us not to. 3693 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 3694 return false; 3695 } 3696 3697 // If the key can be used for keyboard navigation then leave touch mode 3698 // and select a focused view if needed (in ensureTouchMode). 3699 // When a new focused view is selected, we consume the navigation key because 3700 // navigation doesn't make much sense unless a view already has focus so 3701 // the key's purpose is to set focus. 3702 if (isNavigationKey(event)) { 3703 return ensureTouchMode(false); 3704 } 3705 3706 // If the key can be used for typing then leave touch mode 3707 // and select a focused view if needed (in ensureTouchMode). 3708 // Always allow the view to process the typing key. 3709 if (isTypingKey(event)) { 3710 ensureTouchMode(false); 3711 return false; 3712 } 3713 3714 return false; 3715 } 3716 3717 private int deliverKeyEvent(QueuedInputEvent q) { 3718 final KeyEvent event = (KeyEvent)q.mEvent; 3719 if (mInputEventConsistencyVerifier != null) { 3720 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 3721 } 3722 3723 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3724 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView); 3725 3726 // Perform predispatching before the IME. 3727 if (mView.dispatchKeyEventPreIme(event)) { 3728 return EVENT_HANDLED; 3729 } 3730 3731 // Dispatch to the IME before propagating down the view hierarchy. 3732 // The IME will eventually call back into handleImeFinishedEvent. 3733 if (mLastWasImTarget) { 3734 InputMethodManager imm = InputMethodManager.peekInstance(); 3735 if (imm != null) { 3736 final int seq = event.getSequenceNumber(); 3737 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq=" 3738 + seq + " event=" + event); 3739 int result = imm.dispatchKeyEvent(mView.getContext(), seq, event, 3740 mInputMethodCallback); 3741 if (result != EVENT_NOT_HANDLED) { 3742 return result; 3743 } 3744 } 3745 } 3746 } 3747 3748 // Not dispatching to IME, continue with post IME actions. 3749 return deliverKeyEventPostIme(q); 3750 } 3751 3752 private int deliverKeyEventPostIme(QueuedInputEvent q) { 3753 final KeyEvent event = (KeyEvent)q.mEvent; 3754 3755 // If the view went away, then the event will not be handled. 3756 if (mView == null || !mAdded) { 3757 return EVENT_NOT_HANDLED; 3758 } 3759 3760 // If the key's purpose is to exit touch mode then we consume it and consider it handled. 3761 if (checkForLeavingTouchModeAndConsume(event)) { 3762 return EVENT_HANDLED; 3763 } 3764 3765 // Make sure the fallback event policy sees all keys that will be delivered to the 3766 // view hierarchy. 3767 mFallbackEventHandler.preDispatchKeyEvent(event); 3768 3769 // Deliver the key to the view hierarchy. 3770 if (mView.dispatchKeyEvent(event)) { 3771 return EVENT_HANDLED; 3772 } 3773 3774 // If the Control modifier is held, try to interpret the key as a shortcut. 3775 if (event.getAction() == KeyEvent.ACTION_DOWN 3776 && event.isCtrlPressed() 3777 && event.getRepeatCount() == 0 3778 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3779 if (mView.dispatchKeyShortcutEvent(event)) { 3780 return EVENT_HANDLED; 3781 } 3782 } 3783 3784 // Apply the fallback event policy. 3785 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3786 return EVENT_HANDLED; 3787 } 3788 3789 // Handle automatic focus changes. 3790 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3791 int direction = 0; 3792 switch (event.getKeyCode()) { 3793 case KeyEvent.KEYCODE_DPAD_LEFT: 3794 if (event.hasNoModifiers()) { 3795 direction = View.FOCUS_LEFT; 3796 } 3797 break; 3798 case KeyEvent.KEYCODE_DPAD_RIGHT: 3799 if (event.hasNoModifiers()) { 3800 direction = View.FOCUS_RIGHT; 3801 } 3802 break; 3803 case KeyEvent.KEYCODE_DPAD_UP: 3804 if (event.hasNoModifiers()) { 3805 direction = View.FOCUS_UP; 3806 } 3807 break; 3808 case KeyEvent.KEYCODE_DPAD_DOWN: 3809 if (event.hasNoModifiers()) { 3810 direction = View.FOCUS_DOWN; 3811 } 3812 break; 3813 case KeyEvent.KEYCODE_TAB: 3814 if (event.hasNoModifiers()) { 3815 direction = View.FOCUS_FORWARD; 3816 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3817 direction = View.FOCUS_BACKWARD; 3818 } 3819 break; 3820 } 3821 if (direction != 0) { 3822 View focused = mView.findFocus(); 3823 if (focused != null) { 3824 View v = focused.focusSearch(direction); 3825 if (v != null && v != focused) { 3826 // do the math the get the interesting rect 3827 // of previous focused into the coord system of 3828 // newly focused view 3829 focused.getFocusedRect(mTempRect); 3830 if (mView instanceof ViewGroup) { 3831 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3832 focused, mTempRect); 3833 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3834 v, mTempRect); 3835 } 3836 if (v.requestFocus(direction, mTempRect)) { 3837 playSoundEffect(SoundEffectConstants 3838 .getContantForFocusDirection(direction)); 3839 return EVENT_HANDLED; 3840 } 3841 } 3842 3843 // Give the focused view a last chance to handle the dpad key. 3844 if (mView.dispatchUnhandledMove(focused, direction)) { 3845 return EVENT_HANDLED; 3846 } 3847 } 3848 } 3849 } 3850 3851 // Key was unhandled. 3852 return EVENT_NOT_HANDLED; 3853 } 3854 3855 /* drag/drop */ 3856 void setLocalDragState(Object obj) { 3857 mLocalDragState = obj; 3858 } 3859 3860 private void handleDragEvent(DragEvent event) { 3861 // From the root, only drag start/end/location are dispatched. entered/exited 3862 // are determined and dispatched by the viewgroup hierarchy, who then report 3863 // that back here for ultimate reporting back to the framework. 3864 if (mView != null && mAdded) { 3865 final int what = event.mAction; 3866 3867 if (what == DragEvent.ACTION_DRAG_EXITED) { 3868 // A direct EXITED event means that the window manager knows we've just crossed 3869 // a window boundary, so the current drag target within this one must have 3870 // just been exited. Send it the usual notifications and then we're done 3871 // for now. 3872 mView.dispatchDragEvent(event); 3873 } else { 3874 // Cache the drag description when the operation starts, then fill it in 3875 // on subsequent calls as a convenience 3876 if (what == DragEvent.ACTION_DRAG_STARTED) { 3877 mCurrentDragView = null; // Start the current-recipient tracking 3878 mDragDescription = event.mClipDescription; 3879 } else { 3880 event.mClipDescription = mDragDescription; 3881 } 3882 3883 // For events with a [screen] location, translate into window coordinates 3884 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 3885 mDragPoint.set(event.mX, event.mY); 3886 if (mTranslator != null) { 3887 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 3888 } 3889 3890 if (mCurScrollY != 0) { 3891 mDragPoint.offset(0, mCurScrollY); 3892 } 3893 3894 event.mX = mDragPoint.x; 3895 event.mY = mDragPoint.y; 3896 } 3897 3898 // Remember who the current drag target is pre-dispatch 3899 final View prevDragView = mCurrentDragView; 3900 3901 // Now dispatch the drag/drop event 3902 boolean result = mView.dispatchDragEvent(event); 3903 3904 // If we changed apparent drag target, tell the OS about it 3905 if (prevDragView != mCurrentDragView) { 3906 try { 3907 if (prevDragView != null) { 3908 mWindowSession.dragRecipientExited(mWindow); 3909 } 3910 if (mCurrentDragView != null) { 3911 mWindowSession.dragRecipientEntered(mWindow); 3912 } 3913 } catch (RemoteException e) { 3914 Slog.e(TAG, "Unable to note drag target change"); 3915 } 3916 } 3917 3918 // Report the drop result when we're done 3919 if (what == DragEvent.ACTION_DROP) { 3920 mDragDescription = null; 3921 try { 3922 Log.i(TAG, "Reporting drop result: " + result); 3923 mWindowSession.reportDropResult(mWindow, result); 3924 } catch (RemoteException e) { 3925 Log.e(TAG, "Unable to report drop result"); 3926 } 3927 } 3928 3929 // When the drag operation ends, release any local state object 3930 // that may have been in use 3931 if (what == DragEvent.ACTION_DRAG_ENDED) { 3932 setLocalDragState(null); 3933 } 3934 } 3935 } 3936 event.recycle(); 3937 } 3938 3939 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 3940 if (mSeq != args.seq) { 3941 // The sequence has changed, so we need to update our value and make 3942 // sure to do a traversal afterward so the window manager is given our 3943 // most recent data. 3944 mSeq = args.seq; 3945 mAttachInfo.mForceReportNewAttributes = true; 3946 scheduleTraversals(); 3947 } 3948 if (mView == null) return; 3949 if (args.localChanges != 0) { 3950 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 3951 } 3952 if (mAttachInfo != null) { 3953 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 3954 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 3955 mAttachInfo.mGlobalSystemUiVisibility = visibility; 3956 mView.dispatchSystemUiVisibilityChanged(visibility); 3957 } 3958 } 3959 } 3960 3961 public void handleDispatchDoneAnimating() { 3962 if (mWindowsAnimating) { 3963 mWindowsAnimating = false; 3964 if (!mDirty.isEmpty() || mIsAnimating) { 3965 scheduleTraversals(); 3966 } 3967 } 3968 } 3969 3970 public void getLastTouchPoint(Point outLocation) { 3971 outLocation.x = (int) mLastTouchPoint.x; 3972 outLocation.y = (int) mLastTouchPoint.y; 3973 } 3974 3975 public void setDragFocus(View newDragTarget) { 3976 if (mCurrentDragView != newDragTarget) { 3977 mCurrentDragView = newDragTarget; 3978 } 3979 } 3980 3981 private AudioManager getAudioManager() { 3982 if (mView == null) { 3983 throw new IllegalStateException("getAudioManager called when there is no mView"); 3984 } 3985 if (mAudioManager == null) { 3986 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 3987 } 3988 return mAudioManager; 3989 } 3990 3991 public AccessibilityInteractionController getAccessibilityInteractionController() { 3992 if (mView == null) { 3993 throw new IllegalStateException("getAccessibilityInteractionController" 3994 + " called when there is no mView"); 3995 } 3996 if (mAccessibilityInteractionController == null) { 3997 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 3998 } 3999 return mAccessibilityInteractionController; 4000 } 4001 4002 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 4003 boolean insetsPending) throws RemoteException { 4004 4005 float appScale = mAttachInfo.mApplicationScale; 4006 boolean restore = false; 4007 if (params != null && mTranslator != null) { 4008 restore = true; 4009 params.backup(); 4010 mTranslator.translateWindowLayout(params); 4011 } 4012 if (params != null) { 4013 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 4014 } 4015 mPendingConfiguration.seq = 0; 4016 //Log.d(TAG, ">>>>>> CALLING relayout"); 4017 if (params != null && mOrigWindowType != params.type) { 4018 // For compatibility with old apps, don't crash here. 4019 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 4020 Slog.w(TAG, "Window type can not be changed after " 4021 + "the window is added; ignoring change of " + mView); 4022 params.type = mOrigWindowType; 4023 } 4024 } 4025 int relayoutResult = mWindowSession.relayout( 4026 mWindow, mSeq, params, 4027 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 4028 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 4029 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 4030 mWinFrame, mPendingContentInsets, mPendingVisibleInsets, 4031 mPendingConfiguration, mSurface); 4032 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 4033 if (restore) { 4034 params.restore(); 4035 } 4036 4037 if (mTranslator != null) { 4038 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 4039 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 4040 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 4041 } 4042 return relayoutResult; 4043 } 4044 4045 /** 4046 * {@inheritDoc} 4047 */ 4048 public void playSoundEffect(int effectId) { 4049 checkThread(); 4050 4051 try { 4052 final AudioManager audioManager = getAudioManager(); 4053 4054 switch (effectId) { 4055 case SoundEffectConstants.CLICK: 4056 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 4057 return; 4058 case SoundEffectConstants.NAVIGATION_DOWN: 4059 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 4060 return; 4061 case SoundEffectConstants.NAVIGATION_LEFT: 4062 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 4063 return; 4064 case SoundEffectConstants.NAVIGATION_RIGHT: 4065 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 4066 return; 4067 case SoundEffectConstants.NAVIGATION_UP: 4068 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 4069 return; 4070 default: 4071 throw new IllegalArgumentException("unknown effect id " + effectId + 4072 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 4073 } 4074 } catch (IllegalStateException e) { 4075 // Exception thrown by getAudioManager() when mView is null 4076 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 4077 e.printStackTrace(); 4078 } 4079 } 4080 4081 /** 4082 * {@inheritDoc} 4083 */ 4084 public boolean performHapticFeedback(int effectId, boolean always) { 4085 try { 4086 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 4087 } catch (RemoteException e) { 4088 return false; 4089 } 4090 } 4091 4092 /** 4093 * {@inheritDoc} 4094 */ 4095 public View focusSearch(View focused, int direction) { 4096 checkThread(); 4097 if (!(mView instanceof ViewGroup)) { 4098 return null; 4099 } 4100 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 4101 } 4102 4103 public void debug() { 4104 mView.debug(); 4105 } 4106 4107 public void dumpGfxInfo(int[] info) { 4108 info[0] = info[1] = 0; 4109 if (mView != null) { 4110 getGfxInfo(mView, info); 4111 } 4112 } 4113 4114 private static void getGfxInfo(View view, int[] info) { 4115 DisplayList displayList = view.mDisplayList; 4116 info[0]++; 4117 if (displayList != null) { 4118 info[1] += displayList.getSize(); 4119 } 4120 4121 if (view instanceof ViewGroup) { 4122 ViewGroup group = (ViewGroup) view; 4123 4124 int count = group.getChildCount(); 4125 for (int i = 0; i < count; i++) { 4126 getGfxInfo(group.getChildAt(i), info); 4127 } 4128 } 4129 } 4130 4131 public void die(boolean immediate) { 4132 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 4133 // done by dispatchDetachedFromWindow will cause havoc on return. 4134 if (immediate && !mIsInTraversal) { 4135 doDie(); 4136 } else { 4137 if (!mIsDrawing) { 4138 destroyHardwareRenderer(); 4139 } else { 4140 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 4141 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 4142 } 4143 mHandler.sendEmptyMessage(MSG_DIE); 4144 } 4145 } 4146 4147 void doDie() { 4148 checkThread(); 4149 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 4150 synchronized (this) { 4151 if (mAdded) { 4152 dispatchDetachedFromWindow(); 4153 } 4154 4155 if (mAdded && !mFirst) { 4156 invalidateDisplayLists(); 4157 destroyHardwareRenderer(); 4158 4159 if (mView != null) { 4160 int viewVisibility = mView.getVisibility(); 4161 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 4162 if (mWindowAttributesChanged || viewVisibilityChanged) { 4163 // If layout params have been changed, first give them 4164 // to the window manager to make sure it has the correct 4165 // animation info. 4166 try { 4167 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 4168 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 4169 mWindowSession.finishDrawing(mWindow); 4170 } 4171 } catch (RemoteException e) { 4172 } 4173 } 4174 4175 mSurface.release(); 4176 } 4177 } 4178 4179 mAdded = false; 4180 } 4181 } 4182 4183 public void requestUpdateConfiguration(Configuration config) { 4184 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 4185 mHandler.sendMessage(msg); 4186 } 4187 4188 public void loadSystemProperties() { 4189 mHandler.post(new Runnable() { 4190 @Override 4191 public void run() { 4192 // Profiling 4193 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false); 4194 profileRendering(mAttachInfo.mHasWindowFocus); 4195 4196 // Hardware rendering 4197 if (mAttachInfo.mHardwareRenderer != null) { 4198 if (mAttachInfo.mHardwareRenderer.loadSystemProperties(mHolder.getSurface())) { 4199 invalidate(); 4200 } 4201 } 4202 4203 // Layout debugging 4204 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false); 4205 if (layout != mAttachInfo.mDebugLayout) { 4206 mAttachInfo.mDebugLayout = layout; 4207 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 4208 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 4209 } 4210 } 4211 } 4212 }); 4213 } 4214 4215 private void destroyHardwareRenderer() { 4216 AttachInfo attachInfo = mAttachInfo; 4217 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 4218 4219 if (hardwareRenderer != null) { 4220 if (mView != null) { 4221 hardwareRenderer.destroyHardwareResources(mView); 4222 } 4223 hardwareRenderer.destroy(true); 4224 hardwareRenderer.setRequested(false); 4225 4226 attachInfo.mHardwareRenderer = null; 4227 attachInfo.mHardwareAccelerated = false; 4228 } 4229 } 4230 4231 void dispatchImeFinishedEvent(int seq, boolean handled) { 4232 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT); 4233 msg.arg1 = seq; 4234 msg.arg2 = handled ? 1 : 0; 4235 msg.setAsynchronous(true); 4236 mHandler.sendMessage(msg); 4237 } 4238 4239 public void dispatchFinishInputConnection(InputConnection connection) { 4240 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 4241 mHandler.sendMessage(msg); 4242 } 4243 4244 public void dispatchResized(Rect frame, Rect contentInsets, 4245 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4246 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 4247 + " contentInsets=" + contentInsets.toShortString() 4248 + " visibleInsets=" + visibleInsets.toShortString() 4249 + " reportDraw=" + reportDraw); 4250 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 4251 if (mTranslator != null) { 4252 mTranslator.translateRectInScreenToAppWindow(frame); 4253 mTranslator.translateRectInScreenToAppWindow(contentInsets); 4254 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 4255 } 4256 SomeArgs args = SomeArgs.obtain(); 4257 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 4258 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 4259 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 4260 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 4261 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 4262 msg.obj = args; 4263 mHandler.sendMessage(msg); 4264 } 4265 4266 public void dispatchMoved(int newX, int newY) { 4267 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 4268 if (mTranslator != null) { 4269 PointF point = new PointF(newX, newY); 4270 mTranslator.translatePointInScreenToAppWindow(point); 4271 newX = (int) (point.x + 0.5); 4272 newY = (int) (point.y + 0.5); 4273 } 4274 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 4275 mHandler.sendMessage(msg); 4276 } 4277 4278 /** 4279 * Represents a pending input event that is waiting in a queue. 4280 * 4281 * Input events are processed in serial order by the timestamp specified by 4282 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 4283 * one input event to the application at a time and waits for the application 4284 * to finish handling it before delivering the next one. 4285 * 4286 * However, because the application or IME can synthesize and inject multiple 4287 * key events at a time without going through the input dispatcher, we end up 4288 * needing a queue on the application's side. 4289 */ 4290 private static final class QueuedInputEvent { 4291 public static final int FLAG_DELIVER_POST_IME = 1; 4292 4293 public QueuedInputEvent mNext; 4294 4295 public InputEvent mEvent; 4296 public InputEventReceiver mReceiver; 4297 public int mFlags; 4298 } 4299 4300 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 4301 InputEventReceiver receiver, int flags) { 4302 QueuedInputEvent q = mQueuedInputEventPool; 4303 if (q != null) { 4304 mQueuedInputEventPoolSize -= 1; 4305 mQueuedInputEventPool = q.mNext; 4306 q.mNext = null; 4307 } else { 4308 q = new QueuedInputEvent(); 4309 } 4310 4311 q.mEvent = event; 4312 q.mReceiver = receiver; 4313 q.mFlags = flags; 4314 return q; 4315 } 4316 4317 private void recycleQueuedInputEvent(QueuedInputEvent q) { 4318 q.mEvent = null; 4319 q.mReceiver = null; 4320 4321 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 4322 mQueuedInputEventPoolSize += 1; 4323 q.mNext = mQueuedInputEventPool; 4324 mQueuedInputEventPool = q; 4325 } 4326 } 4327 4328 void enqueueInputEvent(InputEvent event) { 4329 enqueueInputEvent(event, null, 0, false); 4330 } 4331 4332 void enqueueInputEvent(InputEvent event, 4333 InputEventReceiver receiver, int flags, boolean processImmediately) { 4334 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 4335 4336 // Always enqueue the input event in order, regardless of its time stamp. 4337 // We do this because the application or the IME may inject key events 4338 // in response to touch events and we want to ensure that the injected keys 4339 // are processed in the order they were received and we cannot trust that 4340 // the time stamp of injected events are monotonic. 4341 QueuedInputEvent last = mFirstPendingInputEvent; 4342 if (last == null) { 4343 mFirstPendingInputEvent = q; 4344 } else { 4345 while (last.mNext != null) { 4346 last = last.mNext; 4347 } 4348 last.mNext = q; 4349 } 4350 4351 if (processImmediately) { 4352 doProcessInputEvents(); 4353 } else { 4354 scheduleProcessInputEvents(); 4355 } 4356 } 4357 4358 private void scheduleProcessInputEvents() { 4359 if (!mProcessInputEventsScheduled) { 4360 mProcessInputEventsScheduled = true; 4361 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 4362 msg.setAsynchronous(true); 4363 mHandler.sendMessage(msg); 4364 } 4365 } 4366 4367 void doProcessInputEvents() { 4368 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 4369 QueuedInputEvent q = mFirstPendingInputEvent; 4370 mFirstPendingInputEvent = q.mNext; 4371 q.mNext = null; 4372 mCurrentInputEvent = q; 4373 4374 final int result = deliverInputEvent(q); 4375 if (result != EVENT_IN_PROGRESS) { 4376 finishCurrentInputEvent(result == EVENT_HANDLED); 4377 } 4378 } 4379 4380 // We are done processing all input events that we can process right now 4381 // so we can clear the pending flag immediately. 4382 if (mProcessInputEventsScheduled) { 4383 mProcessInputEventsScheduled = false; 4384 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 4385 } 4386 } 4387 4388 void handleImeFinishedEvent(int seq, boolean handled) { 4389 final QueuedInputEvent q = mCurrentInputEvent; 4390 if (q != null && q.mEvent.getSequenceNumber() == seq) { 4391 if (DEBUG_IMF) { 4392 Log.v(TAG, "IME finished event: seq=" + seq 4393 + " handled=" + handled + " event=" + q); 4394 } 4395 4396 if (!handled) { 4397 // If the window doesn't currently have input focus, then drop 4398 // this event. This could be an event that came back from the 4399 // IME dispatch but the window has lost focus in the meantime. 4400 if (!mAttachInfo.mHasWindowFocus && !isTerminalInputEvent(q.mEvent)) { 4401 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent); 4402 } else { 4403 final int result = deliverInputEventPostIme(q); 4404 if (result == EVENT_HANDLED) { 4405 handled = true; 4406 } 4407 } 4408 } 4409 finishCurrentInputEvent(handled); 4410 4411 // Immediately start processing the next input event. 4412 doProcessInputEvents(); 4413 } else { 4414 if (DEBUG_IMF) { 4415 Log.v(TAG, "IME finished event: seq=" + seq 4416 + " handled=" + handled + ", event not found!"); 4417 } 4418 } 4419 } 4420 4421 private void finishCurrentInputEvent(boolean handled) { 4422 final QueuedInputEvent q = mCurrentInputEvent; 4423 mCurrentInputEvent = null; 4424 4425 if (q.mReceiver != null) { 4426 q.mReceiver.finishInputEvent(q.mEvent, handled); 4427 } else { 4428 q.mEvent.recycleIfNeededAfterDispatch(); 4429 } 4430 4431 recycleQueuedInputEvent(q); 4432 } 4433 4434 private static boolean isTerminalInputEvent(InputEvent event) { 4435 if (event instanceof KeyEvent) { 4436 final KeyEvent keyEvent = (KeyEvent)event; 4437 return keyEvent.getAction() == KeyEvent.ACTION_UP; 4438 } else { 4439 final MotionEvent motionEvent = (MotionEvent)event; 4440 final int action = motionEvent.getAction(); 4441 return action == MotionEvent.ACTION_UP 4442 || action == MotionEvent.ACTION_CANCEL 4443 || action == MotionEvent.ACTION_HOVER_EXIT; 4444 } 4445 } 4446 4447 void scheduleConsumeBatchedInput() { 4448 if (!mConsumeBatchedInputScheduled) { 4449 mConsumeBatchedInputScheduled = true; 4450 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 4451 mConsumedBatchedInputRunnable, null); 4452 } 4453 } 4454 4455 void unscheduleConsumeBatchedInput() { 4456 if (mConsumeBatchedInputScheduled) { 4457 mConsumeBatchedInputScheduled = false; 4458 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4459 mConsumedBatchedInputRunnable, null); 4460 } 4461 } 4462 4463 void doConsumeBatchedInput(long frameTimeNanos) { 4464 if (mConsumeBatchedInputScheduled) { 4465 mConsumeBatchedInputScheduled = false; 4466 if (mInputEventReceiver != null) { 4467 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos); 4468 } 4469 doProcessInputEvents(); 4470 } 4471 } 4472 4473 final class TraversalRunnable implements Runnable { 4474 @Override 4475 public void run() { 4476 doTraversal(); 4477 } 4478 } 4479 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 4480 4481 final class WindowInputEventReceiver extends InputEventReceiver { 4482 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 4483 super(inputChannel, looper); 4484 } 4485 4486 @Override 4487 public void onInputEvent(InputEvent event) { 4488 enqueueInputEvent(event, this, 0, true); 4489 } 4490 4491 @Override 4492 public void onBatchedInputEventPending() { 4493 scheduleConsumeBatchedInput(); 4494 } 4495 4496 @Override 4497 public void dispose() { 4498 unscheduleConsumeBatchedInput(); 4499 super.dispose(); 4500 } 4501 } 4502 WindowInputEventReceiver mInputEventReceiver; 4503 4504 final class ConsumeBatchedInputRunnable implements Runnable { 4505 @Override 4506 public void run() { 4507 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 4508 } 4509 } 4510 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 4511 new ConsumeBatchedInputRunnable(); 4512 boolean mConsumeBatchedInputScheduled; 4513 4514 final class InvalidateOnAnimationRunnable implements Runnable { 4515 private boolean mPosted; 4516 private ArrayList<View> mViews = new ArrayList<View>(); 4517 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 4518 new ArrayList<AttachInfo.InvalidateInfo>(); 4519 private View[] mTempViews; 4520 private AttachInfo.InvalidateInfo[] mTempViewRects; 4521 4522 public void addView(View view) { 4523 synchronized (this) { 4524 mViews.add(view); 4525 postIfNeededLocked(); 4526 } 4527 } 4528 4529 public void addViewRect(AttachInfo.InvalidateInfo info) { 4530 synchronized (this) { 4531 mViewRects.add(info); 4532 postIfNeededLocked(); 4533 } 4534 } 4535 4536 public void removeView(View view) { 4537 synchronized (this) { 4538 mViews.remove(view); 4539 4540 for (int i = mViewRects.size(); i-- > 0; ) { 4541 AttachInfo.InvalidateInfo info = mViewRects.get(i); 4542 if (info.target == view) { 4543 mViewRects.remove(i); 4544 info.recycle(); 4545 } 4546 } 4547 4548 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 4549 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 4550 mPosted = false; 4551 } 4552 } 4553 } 4554 4555 @Override 4556 public void run() { 4557 final int viewCount; 4558 final int viewRectCount; 4559 synchronized (this) { 4560 mPosted = false; 4561 4562 viewCount = mViews.size(); 4563 if (viewCount != 0) { 4564 mTempViews = mViews.toArray(mTempViews != null 4565 ? mTempViews : new View[viewCount]); 4566 mViews.clear(); 4567 } 4568 4569 viewRectCount = mViewRects.size(); 4570 if (viewRectCount != 0) { 4571 mTempViewRects = mViewRects.toArray(mTempViewRects != null 4572 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 4573 mViewRects.clear(); 4574 } 4575 } 4576 4577 for (int i = 0; i < viewCount; i++) { 4578 mTempViews[i].invalidate(); 4579 mTempViews[i] = null; 4580 } 4581 4582 for (int i = 0; i < viewRectCount; i++) { 4583 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 4584 info.target.invalidate(info.left, info.top, info.right, info.bottom); 4585 info.recycle(); 4586 } 4587 } 4588 4589 private void postIfNeededLocked() { 4590 if (!mPosted) { 4591 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 4592 mPosted = true; 4593 } 4594 } 4595 } 4596 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 4597 new InvalidateOnAnimationRunnable(); 4598 4599 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 4600 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 4601 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4602 } 4603 4604 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 4605 long delayMilliseconds) { 4606 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 4607 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4608 } 4609 4610 public void dispatchInvalidateOnAnimation(View view) { 4611 mInvalidateOnAnimationRunnable.addView(view); 4612 } 4613 4614 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 4615 mInvalidateOnAnimationRunnable.addViewRect(info); 4616 } 4617 4618 public void enqueueDisplayList(DisplayList displayList) { 4619 mDisplayLists.add(displayList); 4620 } 4621 4622 public void cancelInvalidate(View view) { 4623 mHandler.removeMessages(MSG_INVALIDATE, view); 4624 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 4625 // them to the pool 4626 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 4627 mInvalidateOnAnimationRunnable.removeView(view); 4628 } 4629 4630 public void dispatchKey(KeyEvent event) { 4631 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 4632 msg.setAsynchronous(true); 4633 mHandler.sendMessage(msg); 4634 } 4635 4636 public void dispatchKeyFromIme(KeyEvent event) { 4637 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 4638 msg.setAsynchronous(true); 4639 mHandler.sendMessage(msg); 4640 } 4641 4642 public void dispatchUnhandledKey(KeyEvent event) { 4643 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 4644 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 4645 final int keyCode = event.getKeyCode(); 4646 final int metaState = event.getMetaState(); 4647 4648 // Check for fallback actions specified by the key character map. 4649 KeyCharacterMap.FallbackAction fallbackAction = 4650 kcm.getFallbackAction(keyCode, metaState); 4651 if (fallbackAction != null) { 4652 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 4653 KeyEvent fallbackEvent = KeyEvent.obtain( 4654 event.getDownTime(), event.getEventTime(), 4655 event.getAction(), fallbackAction.keyCode, 4656 event.getRepeatCount(), fallbackAction.metaState, 4657 event.getDeviceId(), event.getScanCode(), 4658 flags, event.getSource(), null); 4659 fallbackAction.recycle(); 4660 4661 dispatchKey(fallbackEvent); 4662 } 4663 } 4664 } 4665 4666 public void dispatchAppVisibility(boolean visible) { 4667 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 4668 msg.arg1 = visible ? 1 : 0; 4669 mHandler.sendMessage(msg); 4670 } 4671 4672 public void dispatchScreenStateChange(boolean on) { 4673 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 4674 msg.arg1 = on ? 1 : 0; 4675 mHandler.sendMessage(msg); 4676 } 4677 4678 public void dispatchGetNewSurface() { 4679 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 4680 mHandler.sendMessage(msg); 4681 } 4682 4683 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4684 Message msg = Message.obtain(); 4685 msg.what = MSG_WINDOW_FOCUS_CHANGED; 4686 msg.arg1 = hasFocus ? 1 : 0; 4687 msg.arg2 = inTouchMode ? 1 : 0; 4688 mHandler.sendMessage(msg); 4689 } 4690 4691 public void dispatchCloseSystemDialogs(String reason) { 4692 Message msg = Message.obtain(); 4693 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 4694 msg.obj = reason; 4695 mHandler.sendMessage(msg); 4696 } 4697 4698 public void dispatchDragEvent(DragEvent event) { 4699 final int what; 4700 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 4701 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 4702 mHandler.removeMessages(what); 4703 } else { 4704 what = MSG_DISPATCH_DRAG_EVENT; 4705 } 4706 Message msg = mHandler.obtainMessage(what, event); 4707 mHandler.sendMessage(msg); 4708 } 4709 4710 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4711 int localValue, int localChanges) { 4712 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 4713 args.seq = seq; 4714 args.globalVisibility = globalVisibility; 4715 args.localValue = localValue; 4716 args.localChanges = localChanges; 4717 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 4718 } 4719 4720 public void dispatchDoneAnimating() { 4721 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 4722 } 4723 4724 public void dispatchCheckFocus() { 4725 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 4726 // This will result in a call to checkFocus() below. 4727 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 4728 } 4729 } 4730 4731 /** 4732 * Post a callback to send a 4733 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4734 * This event is send at most once every 4735 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 4736 */ 4737 private void postSendWindowContentChangedCallback(View source) { 4738 if (mSendWindowContentChangedAccessibilityEvent == null) { 4739 mSendWindowContentChangedAccessibilityEvent = 4740 new SendWindowContentChangedAccessibilityEvent(); 4741 } 4742 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource; 4743 if (oldSource == null) { 4744 mSendWindowContentChangedAccessibilityEvent.mSource = source; 4745 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 4746 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 4747 } else { 4748 mSendWindowContentChangedAccessibilityEvent.mSource = 4749 getCommonPredecessor(oldSource, source); 4750 } 4751 } 4752 4753 /** 4754 * Remove a posted callback to send a 4755 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4756 */ 4757 private void removeSendWindowContentChangedCallback() { 4758 if (mSendWindowContentChangedAccessibilityEvent != null) { 4759 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 4760 } 4761 } 4762 4763 public boolean showContextMenuForChild(View originalView) { 4764 return false; 4765 } 4766 4767 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 4768 return null; 4769 } 4770 4771 public void createContextMenu(ContextMenu menu) { 4772 } 4773 4774 public void childDrawableStateChanged(View child) { 4775 } 4776 4777 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 4778 if (mView == null) { 4779 return false; 4780 } 4781 // Intercept accessibility focus events fired by virtual nodes to keep 4782 // track of accessibility focus position in such nodes. 4783 final int eventType = event.getEventType(); 4784 switch (eventType) { 4785 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 4786 final long sourceNodeId = event.getSourceNodeId(); 4787 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 4788 sourceNodeId); 4789 View source = mView.findViewByAccessibilityId(accessibilityViewId); 4790 if (source != null) { 4791 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 4792 if (provider != null) { 4793 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo( 4794 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId)); 4795 setAccessibilityFocus(source, node); 4796 } 4797 } 4798 } break; 4799 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 4800 final long sourceNodeId = event.getSourceNodeId(); 4801 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 4802 sourceNodeId); 4803 View source = mView.findViewByAccessibilityId(accessibilityViewId); 4804 if (source != null) { 4805 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 4806 if (provider != null) { 4807 setAccessibilityFocus(null, null); 4808 } 4809 } 4810 } break; 4811 } 4812 mAccessibilityManager.sendAccessibilityEvent(event); 4813 return true; 4814 } 4815 4816 @Override 4817 public void childAccessibilityStateChanged(View child) { 4818 postSendWindowContentChangedCallback(child); 4819 } 4820 4821 private View getCommonPredecessor(View first, View second) { 4822 if (mAttachInfo != null) { 4823 if (mTempHashSet == null) { 4824 mTempHashSet = new HashSet<View>(); 4825 } 4826 HashSet<View> seen = mTempHashSet; 4827 seen.clear(); 4828 View firstCurrent = first; 4829 while (firstCurrent != null) { 4830 seen.add(firstCurrent); 4831 ViewParent firstCurrentParent = firstCurrent.mParent; 4832 if (firstCurrentParent instanceof View) { 4833 firstCurrent = (View) firstCurrentParent; 4834 } else { 4835 firstCurrent = null; 4836 } 4837 } 4838 View secondCurrent = second; 4839 while (secondCurrent != null) { 4840 if (seen.contains(secondCurrent)) { 4841 seen.clear(); 4842 return secondCurrent; 4843 } 4844 ViewParent secondCurrentParent = secondCurrent.mParent; 4845 if (secondCurrentParent instanceof View) { 4846 secondCurrent = (View) secondCurrentParent; 4847 } else { 4848 secondCurrent = null; 4849 } 4850 } 4851 seen.clear(); 4852 } 4853 return null; 4854 } 4855 4856 void checkThread() { 4857 if (mThread != Thread.currentThread()) { 4858 throw new CalledFromWrongThreadException( 4859 "Only the original thread that created a view hierarchy can touch its views."); 4860 } 4861 } 4862 4863 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4864 // ViewAncestor never intercepts touch event, so this can be a no-op 4865 } 4866 4867 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 4868 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 4869 if (rectangle != null) { 4870 mTempRect.set(rectangle); 4871 mTempRect.offset(0, -mCurScrollY); 4872 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4873 try { 4874 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate); 4875 } catch (RemoteException re) { 4876 /* ignore */ 4877 } 4878 } 4879 return scrolled; 4880 } 4881 4882 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 4883 // Do nothing. 4884 } 4885 4886 class TakenSurfaceHolder extends BaseSurfaceHolder { 4887 @Override 4888 public boolean onAllowLockCanvas() { 4889 return mDrawingAllowed; 4890 } 4891 4892 @Override 4893 public void onRelayoutContainer() { 4894 // Not currently interesting -- from changing between fixed and layout size. 4895 } 4896 4897 public void setFormat(int format) { 4898 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4899 } 4900 4901 public void setType(int type) { 4902 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4903 } 4904 4905 @Override 4906 public void onUpdateSurface() { 4907 // We take care of format and type changes on our own. 4908 throw new IllegalStateException("Shouldn't be here"); 4909 } 4910 4911 public boolean isCreating() { 4912 return mIsCreating; 4913 } 4914 4915 @Override 4916 public void setFixedSize(int width, int height) { 4917 throw new UnsupportedOperationException( 4918 "Currently only support sizing from layout"); 4919 } 4920 4921 public void setKeepScreenOn(boolean screenOn) { 4922 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4923 } 4924 } 4925 4926 static final class InputMethodCallback implements InputMethodManager.FinishedEventCallback { 4927 private WeakReference<ViewRootImpl> mViewAncestor; 4928 4929 public InputMethodCallback(ViewRootImpl viewAncestor) { 4930 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4931 } 4932 4933 @Override 4934 public void finishedEvent(int seq, boolean handled) { 4935 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4936 if (viewAncestor != null) { 4937 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4938 } 4939 } 4940 } 4941 4942 static class W extends IWindow.Stub { 4943 private final WeakReference<ViewRootImpl> mViewAncestor; 4944 private final IWindowSession mWindowSession; 4945 4946 W(ViewRootImpl viewAncestor) { 4947 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4948 mWindowSession = viewAncestor.mWindowSession; 4949 } 4950 4951 public void resized(Rect frame, Rect contentInsets, 4952 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4953 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4954 if (viewAncestor != null) { 4955 viewAncestor.dispatchResized(frame, contentInsets, 4956 visibleInsets, reportDraw, newConfig); 4957 } 4958 } 4959 4960 @Override 4961 public void moved(int newX, int newY) { 4962 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4963 if (viewAncestor != null) { 4964 viewAncestor.dispatchMoved(newX, newY); 4965 } 4966 } 4967 4968 public void dispatchAppVisibility(boolean visible) { 4969 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4970 if (viewAncestor != null) { 4971 viewAncestor.dispatchAppVisibility(visible); 4972 } 4973 } 4974 4975 public void dispatchScreenState(boolean on) { 4976 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4977 if (viewAncestor != null) { 4978 viewAncestor.dispatchScreenStateChange(on); 4979 } 4980 } 4981 4982 public void dispatchGetNewSurface() { 4983 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4984 if (viewAncestor != null) { 4985 viewAncestor.dispatchGetNewSurface(); 4986 } 4987 } 4988 4989 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4990 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4991 if (viewAncestor != null) { 4992 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4993 } 4994 } 4995 4996 private static int checkCallingPermission(String permission) { 4997 try { 4998 return ActivityManagerNative.getDefault().checkPermission( 4999 permission, Binder.getCallingPid(), Binder.getCallingUid()); 5000 } catch (RemoteException e) { 5001 return PackageManager.PERMISSION_DENIED; 5002 } 5003 } 5004 5005 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 5006 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5007 if (viewAncestor != null) { 5008 final View view = viewAncestor.mView; 5009 if (view != null) { 5010 if (checkCallingPermission(Manifest.permission.DUMP) != 5011 PackageManager.PERMISSION_GRANTED) { 5012 throw new SecurityException("Insufficient permissions to invoke" 5013 + " executeCommand() from pid=" + Binder.getCallingPid() 5014 + ", uid=" + Binder.getCallingUid()); 5015 } 5016 5017 OutputStream clientStream = null; 5018 try { 5019 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 5020 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 5021 } catch (IOException e) { 5022 e.printStackTrace(); 5023 } finally { 5024 if (clientStream != null) { 5025 try { 5026 clientStream.close(); 5027 } catch (IOException e) { 5028 e.printStackTrace(); 5029 } 5030 } 5031 } 5032 } 5033 } 5034 } 5035 5036 public void closeSystemDialogs(String reason) { 5037 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5038 if (viewAncestor != null) { 5039 viewAncestor.dispatchCloseSystemDialogs(reason); 5040 } 5041 } 5042 5043 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 5044 boolean sync) { 5045 if (sync) { 5046 try { 5047 mWindowSession.wallpaperOffsetsComplete(asBinder()); 5048 } catch (RemoteException e) { 5049 } 5050 } 5051 } 5052 5053 public void dispatchWallpaperCommand(String action, int x, int y, 5054 int z, Bundle extras, boolean sync) { 5055 if (sync) { 5056 try { 5057 mWindowSession.wallpaperCommandComplete(asBinder(), null); 5058 } catch (RemoteException e) { 5059 } 5060 } 5061 } 5062 5063 /* Drag/drop */ 5064 public void dispatchDragEvent(DragEvent event) { 5065 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5066 if (viewAncestor != null) { 5067 viewAncestor.dispatchDragEvent(event); 5068 } 5069 } 5070 5071 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 5072 int localValue, int localChanges) { 5073 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5074 if (viewAncestor != null) { 5075 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 5076 localValue, localChanges); 5077 } 5078 } 5079 5080 public void doneAnimating() { 5081 final ViewRootImpl viewAncestor = mViewAncestor.get(); 5082 if (viewAncestor != null) { 5083 viewAncestor.dispatchDoneAnimating(); 5084 } 5085 } 5086 } 5087 5088 /** 5089 * Maintains state information for a single trackball axis, generating 5090 * discrete (DPAD) movements based on raw trackball motion. 5091 */ 5092 static final class TrackballAxis { 5093 /** 5094 * The maximum amount of acceleration we will apply. 5095 */ 5096 static final float MAX_ACCELERATION = 20; 5097 5098 /** 5099 * The maximum amount of time (in milliseconds) between events in order 5100 * for us to consider the user to be doing fast trackball movements, 5101 * and thus apply an acceleration. 5102 */ 5103 static final long FAST_MOVE_TIME = 150; 5104 5105 /** 5106 * Scaling factor to the time (in milliseconds) between events to how 5107 * much to multiple/divide the current acceleration. When movement 5108 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 5109 * FAST_MOVE_TIME it divides it. 5110 */ 5111 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 5112 5113 float position; 5114 float absPosition; 5115 float acceleration = 1; 5116 long lastMoveTime = 0; 5117 int step; 5118 int dir; 5119 int nonAccelMovement; 5120 5121 void reset(int _step) { 5122 position = 0; 5123 acceleration = 1; 5124 lastMoveTime = 0; 5125 step = _step; 5126 dir = 0; 5127 } 5128 5129 /** 5130 * Add trackball movement into the state. If the direction of movement 5131 * has been reversed, the state is reset before adding the 5132 * movement (so that you don't have to compensate for any previously 5133 * collected movement before see the result of the movement in the 5134 * new direction). 5135 * 5136 * @return Returns the absolute value of the amount of movement 5137 * collected so far. 5138 */ 5139 float collect(float off, long time, String axis) { 5140 long normTime; 5141 if (off > 0) { 5142 normTime = (long)(off * FAST_MOVE_TIME); 5143 if (dir < 0) { 5144 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 5145 position = 0; 5146 step = 0; 5147 acceleration = 1; 5148 lastMoveTime = 0; 5149 } 5150 dir = 1; 5151 } else if (off < 0) { 5152 normTime = (long)((-off) * FAST_MOVE_TIME); 5153 if (dir > 0) { 5154 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 5155 position = 0; 5156 step = 0; 5157 acceleration = 1; 5158 lastMoveTime = 0; 5159 } 5160 dir = -1; 5161 } else { 5162 normTime = 0; 5163 } 5164 5165 // The number of milliseconds between each movement that is 5166 // considered "normal" and will not result in any acceleration 5167 // or deceleration, scaled by the offset we have here. 5168 if (normTime > 0) { 5169 long delta = time - lastMoveTime; 5170 lastMoveTime = time; 5171 float acc = acceleration; 5172 if (delta < normTime) { 5173 // The user is scrolling rapidly, so increase acceleration. 5174 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 5175 if (scale > 1) acc *= scale; 5176 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 5177 + off + " normTime=" + normTime + " delta=" + delta 5178 + " scale=" + scale + " acc=" + acc); 5179 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 5180 } else { 5181 // The user is scrolling slowly, so decrease acceleration. 5182 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 5183 if (scale > 1) acc /= scale; 5184 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 5185 + off + " normTime=" + normTime + " delta=" + delta 5186 + " scale=" + scale + " acc=" + acc); 5187 acceleration = acc > 1 ? acc : 1; 5188 } 5189 } 5190 position += off; 5191 return (absPosition = Math.abs(position)); 5192 } 5193 5194 /** 5195 * Generate the number of discrete movement events appropriate for 5196 * the currently collected trackball movement. 5197 * 5198 * @param precision The minimum movement required to generate the 5199 * first discrete movement. 5200 * 5201 * @return Returns the number of discrete movements, either positive 5202 * or negative, or 0 if there is not enough trackball movement yet 5203 * for a discrete movement. 5204 */ 5205 int generate(float precision) { 5206 int movement = 0; 5207 nonAccelMovement = 0; 5208 do { 5209 final int dir = position >= 0 ? 1 : -1; 5210 switch (step) { 5211 // If we are going to execute the first step, then we want 5212 // to do this as soon as possible instead of waiting for 5213 // a full movement, in order to make things look responsive. 5214 case 0: 5215 if (absPosition < precision) { 5216 return movement; 5217 } 5218 movement += dir; 5219 nonAccelMovement += dir; 5220 step = 1; 5221 break; 5222 // If we have generated the first movement, then we need 5223 // to wait for the second complete trackball motion before 5224 // generating the second discrete movement. 5225 case 1: 5226 if (absPosition < 2) { 5227 return movement; 5228 } 5229 movement += dir; 5230 nonAccelMovement += dir; 5231 position += dir > 0 ? -2 : 2; 5232 absPosition = Math.abs(position); 5233 step = 2; 5234 break; 5235 // After the first two, we generate discrete movements 5236 // consistently with the trackball, applying an acceleration 5237 // if the trackball is moving quickly. This is a simple 5238 // acceleration on top of what we already compute based 5239 // on how quickly the wheel is being turned, to apply 5240 // a longer increasing acceleration to continuous movement 5241 // in one direction. 5242 default: 5243 if (absPosition < 1) { 5244 return movement; 5245 } 5246 movement += dir; 5247 position += dir >= 0 ? -1 : 1; 5248 absPosition = Math.abs(position); 5249 float acc = acceleration; 5250 acc *= 1.1f; 5251 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 5252 break; 5253 } 5254 } while (true); 5255 } 5256 } 5257 5258 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 5259 public CalledFromWrongThreadException(String msg) { 5260 super(msg); 5261 } 5262 } 5263 5264 private SurfaceHolder mHolder = new SurfaceHolder() { 5265 // we only need a SurfaceHolder for opengl. it would be nice 5266 // to implement everything else though, especially the callback 5267 // support (opengl doesn't make use of it right now, but eventually 5268 // will). 5269 public Surface getSurface() { 5270 return mSurface; 5271 } 5272 5273 public boolean isCreating() { 5274 return false; 5275 } 5276 5277 public void addCallback(Callback callback) { 5278 } 5279 5280 public void removeCallback(Callback callback) { 5281 } 5282 5283 public void setFixedSize(int width, int height) { 5284 } 5285 5286 public void setSizeFromLayout() { 5287 } 5288 5289 public void setFormat(int format) { 5290 } 5291 5292 public void setType(int type) { 5293 } 5294 5295 public void setKeepScreenOn(boolean screenOn) { 5296 } 5297 5298 public Canvas lockCanvas() { 5299 return null; 5300 } 5301 5302 public Canvas lockCanvas(Rect dirty) { 5303 return null; 5304 } 5305 5306 public void unlockCanvasAndPost(Canvas canvas) { 5307 } 5308 public Rect getSurfaceFrame() { 5309 return null; 5310 } 5311 }; 5312 5313 static RunQueue getRunQueue() { 5314 RunQueue rq = sRunQueues.get(); 5315 if (rq != null) { 5316 return rq; 5317 } 5318 rq = new RunQueue(); 5319 sRunQueues.set(rq); 5320 return rq; 5321 } 5322 5323 /** 5324 * The run queue is used to enqueue pending work from Views when no Handler is 5325 * attached. The work is executed during the next call to performTraversals on 5326 * the thread. 5327 * @hide 5328 */ 5329 static final class RunQueue { 5330 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 5331 5332 void post(Runnable action) { 5333 postDelayed(action, 0); 5334 } 5335 5336 void postDelayed(Runnable action, long delayMillis) { 5337 HandlerAction handlerAction = new HandlerAction(); 5338 handlerAction.action = action; 5339 handlerAction.delay = delayMillis; 5340 5341 synchronized (mActions) { 5342 mActions.add(handlerAction); 5343 } 5344 } 5345 5346 void removeCallbacks(Runnable action) { 5347 final HandlerAction handlerAction = new HandlerAction(); 5348 handlerAction.action = action; 5349 5350 synchronized (mActions) { 5351 final ArrayList<HandlerAction> actions = mActions; 5352 5353 while (actions.remove(handlerAction)) { 5354 // Keep going 5355 } 5356 } 5357 } 5358 5359 void executeActions(Handler handler) { 5360 synchronized (mActions) { 5361 final ArrayList<HandlerAction> actions = mActions; 5362 final int count = actions.size(); 5363 5364 for (int i = 0; i < count; i++) { 5365 final HandlerAction handlerAction = actions.get(i); 5366 handler.postDelayed(handlerAction.action, handlerAction.delay); 5367 } 5368 5369 actions.clear(); 5370 } 5371 } 5372 5373 private static class HandlerAction { 5374 Runnable action; 5375 long delay; 5376 5377 @Override 5378 public boolean equals(Object o) { 5379 if (this == o) return true; 5380 if (o == null || getClass() != o.getClass()) return false; 5381 5382 HandlerAction that = (HandlerAction) o; 5383 return !(action != null ? !action.equals(that.action) : that.action != null); 5384 5385 } 5386 5387 @Override 5388 public int hashCode() { 5389 int result = action != null ? action.hashCode() : 0; 5390 result = 31 * result + (int) (delay ^ (delay >>> 32)); 5391 return result; 5392 } 5393 } 5394 } 5395 5396 /** 5397 * Class for managing the accessibility interaction connection 5398 * based on the global accessibility state. 5399 */ 5400 final class AccessibilityInteractionConnectionManager 5401 implements AccessibilityStateChangeListener { 5402 public void onAccessibilityStateChanged(boolean enabled) { 5403 if (enabled) { 5404 ensureConnection(); 5405 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 5406 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 5407 View focusedView = mView.findFocus(); 5408 if (focusedView != null && focusedView != mView) { 5409 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5410 } 5411 } 5412 } else { 5413 ensureNoConnection(); 5414 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 5415 } 5416 } 5417 5418 public void ensureConnection() { 5419 if (mAttachInfo != null) { 5420 final boolean registered = 5421 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5422 if (!registered) { 5423 mAttachInfo.mAccessibilityWindowId = 5424 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 5425 new AccessibilityInteractionConnection(ViewRootImpl.this)); 5426 } 5427 } 5428 } 5429 5430 public void ensureNoConnection() { 5431 final boolean registered = 5432 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5433 if (registered) { 5434 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 5435 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 5436 } 5437 } 5438 } 5439 5440 /** 5441 * This class is an interface this ViewAncestor provides to the 5442 * AccessibilityManagerService to the latter can interact with 5443 * the view hierarchy in this ViewAncestor. 5444 */ 5445 static final class AccessibilityInteractionConnection 5446 extends IAccessibilityInteractionConnection.Stub { 5447 private final WeakReference<ViewRootImpl> mViewRootImpl; 5448 5449 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 5450 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 5451 } 5452 5453 @Override 5454 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 5455 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5456 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 5457 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5458 if (viewRootImpl != null && viewRootImpl.mView != null) { 5459 viewRootImpl.getAccessibilityInteractionController() 5460 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 5461 interactionId, callback, flags, interrogatingPid, interrogatingTid, 5462 spec); 5463 } else { 5464 // We cannot make the call and notify the caller so it does not wait. 5465 try { 5466 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5467 } catch (RemoteException re) { 5468 /* best effort - ignore */ 5469 } 5470 } 5471 } 5472 5473 @Override 5474 public void performAccessibilityAction(long accessibilityNodeId, int action, 5475 Bundle arguments, int interactionId, 5476 IAccessibilityInteractionConnectionCallback callback, int flags, 5477 int interogatingPid, long interrogatingTid) { 5478 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5479 if (viewRootImpl != null && viewRootImpl.mView != null) { 5480 viewRootImpl.getAccessibilityInteractionController() 5481 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 5482 interactionId, callback, flags, interogatingPid, interrogatingTid); 5483 } else { 5484 // We cannot make the call and notify the caller so it does not wait. 5485 try { 5486 callback.setPerformAccessibilityActionResult(false, interactionId); 5487 } catch (RemoteException re) { 5488 /* best effort - ignore */ 5489 } 5490 } 5491 } 5492 5493 @Override 5494 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId, 5495 String viewId, int interactionId, 5496 IAccessibilityInteractionConnectionCallback callback, int flags, 5497 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 5498 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5499 if (viewRootImpl != null && viewRootImpl.mView != null) { 5500 viewRootImpl.getAccessibilityInteractionController() 5501 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId, 5502 viewId, interactionId, callback, flags, interrogatingPid, 5503 interrogatingTid, spec); 5504 } else { 5505 // We cannot make the call and notify the caller so it does not wait. 5506 try { 5507 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5508 } catch (RemoteException re) { 5509 /* best effort - ignore */ 5510 } 5511 } 5512 } 5513 5514 @Override 5515 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 5516 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5517 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 5518 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5519 if (viewRootImpl != null && viewRootImpl.mView != null) { 5520 viewRootImpl.getAccessibilityInteractionController() 5521 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 5522 interactionId, callback, flags, interrogatingPid, interrogatingTid, 5523 spec); 5524 } else { 5525 // We cannot make the call and notify the caller so it does not wait. 5526 try { 5527 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5528 } catch (RemoteException re) { 5529 /* best effort - ignore */ 5530 } 5531 } 5532 } 5533 5534 @Override 5535 public void findFocus(long accessibilityNodeId, int focusType, int interactionId, 5536 IAccessibilityInteractionConnectionCallback callback, int flags, 5537 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 5538 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5539 if (viewRootImpl != null && viewRootImpl.mView != null) { 5540 viewRootImpl.getAccessibilityInteractionController() 5541 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback, 5542 flags, interrogatingPid, interrogatingTid, spec); 5543 } else { 5544 // We cannot make the call and notify the caller so it does not wait. 5545 try { 5546 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5547 } catch (RemoteException re) { 5548 /* best effort - ignore */ 5549 } 5550 } 5551 } 5552 5553 @Override 5554 public void focusSearch(long accessibilityNodeId, int direction, int interactionId, 5555 IAccessibilityInteractionConnectionCallback callback, int flags, 5556 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) { 5557 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5558 if (viewRootImpl != null && viewRootImpl.mView != null) { 5559 viewRootImpl.getAccessibilityInteractionController() 5560 .focusSearchClientThread(accessibilityNodeId, direction, interactionId, 5561 callback, flags, interrogatingPid, interrogatingTid, spec); 5562 } else { 5563 // We cannot make the call and notify the caller so it does not wait. 5564 try { 5565 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5566 } catch (RemoteException re) { 5567 /* best effort - ignore */ 5568 } 5569 } 5570 } 5571 } 5572 5573 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 5574 public View mSource; 5575 5576 public void run() { 5577 if (mSource != null) { 5578 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 5579 mSource.resetAccessibilityStateChanged(); 5580 mSource = null; 5581 } 5582 } 5583 } 5584} 5585