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