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