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