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