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