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