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