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