ViewRootImpl.java revision a611a53292049e070f39f5d98092a06415f4e6ec
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.Manifest; 20import android.animation.LayoutTransition; 21import android.app.ActivityManagerNative; 22import android.content.ClipDescription; 23import android.content.ComponentCallbacks; 24import android.content.ComponentCallbacks2; 25import android.content.Context; 26import android.content.pm.ApplicationInfo; 27import android.content.pm.PackageManager; 28import android.content.res.CompatibilityInfo; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.graphics.Canvas; 32import android.graphics.Paint; 33import android.graphics.PixelFormat; 34import android.graphics.Point; 35import android.graphics.PointF; 36import android.graphics.PorterDuff; 37import android.graphics.Rect; 38import android.graphics.Region; 39import android.graphics.drawable.Drawable; 40import android.media.AudioManager; 41import android.os.Binder; 42import android.os.Bundle; 43import android.os.Debug; 44import android.os.Handler; 45import android.os.LatencyTimer; 46import android.os.Looper; 47import android.os.Message; 48import android.os.ParcelFileDescriptor; 49import android.os.PowerManager; 50import android.os.Process; 51import android.os.RemoteException; 52import android.os.SystemClock; 53import android.os.SystemProperties; 54import android.os.Trace; 55import android.os.UserHandle; 56import android.util.AndroidRuntimeException; 57import android.util.DisplayMetrics; 58import android.util.Log; 59import android.util.Slog; 60import android.util.TypedValue; 61import android.view.View.AttachInfo; 62import android.view.View.MeasureSpec; 63import android.view.accessibility.AccessibilityEvent; 64import android.view.accessibility.AccessibilityManager; 65import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener; 66import android.view.accessibility.AccessibilityNodeInfo; 67import android.view.accessibility.AccessibilityNodeProvider; 68import android.view.accessibility.IAccessibilityInteractionConnection; 69import android.view.accessibility.IAccessibilityInteractionConnectionCallback; 70import android.view.animation.AccelerateDecelerateInterpolator; 71import android.view.animation.Interpolator; 72import android.view.inputmethod.InputConnection; 73import android.view.inputmethod.InputMethodManager; 74import android.widget.Scroller; 75 76import com.android.internal.R; 77import com.android.internal.os.SomeArgs; 78import com.android.internal.policy.PolicyManager; 79import com.android.internal.view.BaseSurfaceHolder; 80import com.android.internal.view.RootViewSurfaceTaker; 81 82import java.io.IOException; 83import java.io.OutputStream; 84import java.lang.ref.WeakReference; 85import java.util.ArrayList; 86import java.util.HashSet; 87 88/** 89 * The top of a view hierarchy, implementing the needed protocol between View 90 * and the WindowManager. This is for the most part an internal implementation 91 * detail of {@link WindowManagerGlobal}. 92 * 93 * {@hide} 94 */ 95@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"}) 96public final class ViewRootImpl implements ViewParent, 97 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks { 98 private static final String TAG = "ViewRootImpl"; 99 private static final boolean DBG = false; 100 private static final boolean LOCAL_LOGV = false; 101 /** @noinspection PointlessBooleanExpression*/ 102 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV; 103 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV; 104 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV; 105 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV; 106 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV; 107 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV; 108 private static final boolean DEBUG_IMF = false || LOCAL_LOGV; 109 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV; 110 private static final boolean DEBUG_FPS = false; 111 112 private static final boolean USE_RENDER_THREAD = false; 113 114 /** 115 * Set this system property to true to force the view hierarchy to render 116 * at 60 Hz. This can be used to measure the potential framerate. 117 */ 118 private static final String PROPERTY_PROFILE_RENDERING = "viewancestor.profile_rendering"; 119 120 private static final boolean MEASURE_LATENCY = false; 121 private static LatencyTimer lt; 122 123 /** 124 * Maximum time we allow the user to roll the trackball enough to generate 125 * a key event, before resetting the counters. 126 */ 127 static final int MAX_TRACKBALL_DELAY = 250; 128 129 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>(); 130 131 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>(); 132 static boolean sFirstDrawComplete = false; 133 134 static final ArrayList<ComponentCallbacks> sConfigCallbacks 135 = new ArrayList<ComponentCallbacks>(); 136 137 private static boolean sUseRenderThread = false; 138 private static boolean sRenderThreadQueried = false; 139 private static final Object[] sRenderThreadQueryLock = new Object[0]; 140 141 final IWindowSession mWindowSession; 142 final Display mDisplay; 143 144 long mLastTrackballTime = 0; 145 final TrackballAxis mTrackballAxisX = new TrackballAxis(); 146 final TrackballAxis mTrackballAxisY = new TrackballAxis(); 147 148 final SimulatedTrackball mSimulatedTrackball = new SimulatedTrackball(); 149 150 int mLastJoystickXDirection; 151 int mLastJoystickYDirection; 152 int mLastJoystickXKeyCode; 153 int mLastJoystickYKeyCode; 154 155 final int[] mTmpLocation = new int[2]; 156 157 final TypedValue mTmpValue = new TypedValue(); 158 159 final InputMethodCallback mInputMethodCallback; 160 final Thread mThread; 161 162 final WindowLeaked mLocation; 163 164 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams(); 165 166 final W mWindow; 167 168 final int mTargetSdkVersion; 169 170 int mSeq; 171 172 View mView; 173 View mFocusedView; 174 View mRealFocusedView; // this is not set to null in touch mode 175 View mOldFocusedView; 176 177 View mAccessibilityFocusedHost; 178 AccessibilityNodeInfo mAccessibilityFocusedVirtualView; 179 180 int mViewVisibility; 181 boolean mAppVisible = true; 182 int mOrigWindowType = -1; 183 184 // Set to true if the owner of this window is in the stopped state, 185 // so the window should no longer be active. 186 boolean mStopped = false; 187 188 boolean mLastInCompatMode = false; 189 190 SurfaceHolder.Callback2 mSurfaceHolderCallback; 191 BaseSurfaceHolder mSurfaceHolder; 192 boolean mIsCreating; 193 boolean mDrawingAllowed; 194 195 final Region mTransparentRegion; 196 final Region mPreviousTransparentRegion; 197 198 int mWidth; 199 int mHeight; 200 Rect mDirty; 201 final Rect mCurrentDirty = new Rect(); 202 final Rect mPreviousDirty = new Rect(); 203 boolean mIsAnimating; 204 205 CompatibilityInfo.Translator mTranslator; 206 207 final View.AttachInfo mAttachInfo; 208 InputChannel mInputChannel; 209 InputQueue.Callback mInputQueueCallback; 210 InputQueue mInputQueue; 211 FallbackEventHandler mFallbackEventHandler; 212 Choreographer mChoreographer; 213 214 final Rect mTempRect; // used in the transaction to not thrash the heap. 215 final Rect mVisRect; // used to retrieve visible rect of focused view. 216 217 boolean mTraversalScheduled; 218 int mTraversalBarrier; 219 boolean mWillDrawSoon; 220 /** Set to true while in performTraversals for detecting when die(true) is called from internal 221 * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */ 222 boolean mIsInTraversal; 223 boolean mFitSystemWindowsRequested; 224 boolean mLayoutRequested; 225 boolean mFirst; 226 boolean mReportNextDraw; 227 boolean mFullRedrawNeeded; 228 boolean mNewSurfaceNeeded; 229 boolean mHasHadWindowFocus; 230 boolean mLastWasImTarget; 231 boolean mWindowsAnimating; 232 boolean mIsDrawing; 233 int mLastSystemUiVisibility; 234 int mClientWindowLayoutFlags; 235 236 // Pool of queued input events. 237 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10; 238 private QueuedInputEvent mQueuedInputEventPool; 239 private int mQueuedInputEventPoolSize; 240 241 // Input event queue. 242 QueuedInputEvent mFirstPendingInputEvent; 243 QueuedInputEvent mCurrentInputEvent; 244 boolean mProcessInputEventsScheduled; 245 246 boolean mWindowAttributesChanged = false; 247 int mWindowAttributesChangesFlag = 0; 248 249 // These can be accessed by any thread, must be protected with a lock. 250 // Surface can never be reassigned or cleared (use Surface.clear()). 251 private final Surface mSurface = new Surface(); 252 253 boolean mAdded; 254 boolean mAddedTouchMode; 255 256 final CompatibilityInfoHolder mCompatibilityInfo; 257 258 // These are accessed by multiple threads. 259 final Rect mWinFrame; // frame given by window manager. 260 261 final Rect mPendingVisibleInsets = new Rect(); 262 final Rect mPendingContentInsets = new Rect(); 263 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets 264 = new ViewTreeObserver.InternalInsetsInfo(); 265 266 final Rect mFitSystemWindowsInsets = new Rect(); 267 268 final Configuration mLastConfiguration = new Configuration(); 269 final Configuration mPendingConfiguration = new Configuration(); 270 271 boolean mScrollMayChange; 272 int mSoftInputMode; 273 View mLastScrolledFocus; 274 int mScrollY; 275 int mCurScrollY; 276 Scroller mScroller; 277 HardwareLayer mResizeBuffer; 278 long mResizeBufferStartTime; 279 int mResizeBufferDuration; 280 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator(); 281 private ArrayList<LayoutTransition> mPendingTransitions; 282 283 final ViewConfiguration mViewConfiguration; 284 285 /* Drag/drop */ 286 ClipDescription mDragDescription; 287 View mCurrentDragView; 288 volatile Object mLocalDragState; 289 final PointF mDragPoint = new PointF(); 290 final PointF mLastTouchPoint = new PointF(); 291 292 private boolean mProfileRendering; 293 private Thread mRenderProfiler; 294 private volatile boolean mRenderProfilingEnabled; 295 296 // Variables to track frames per second, enabled via DEBUG_FPS flag 297 private long mFpsStartTime = -1; 298 private long mFpsPrevTime = -1; 299 private int mFpsNumFrames; 300 301 private final ArrayList<DisplayList> mDisplayLists = new ArrayList<DisplayList>(24); 302 303 /** 304 * see {@link #playSoundEffect(int)} 305 */ 306 AudioManager mAudioManager; 307 308 final AccessibilityManager mAccessibilityManager; 309 310 AccessibilityInteractionController mAccessibilityInteractionController; 311 312 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager; 313 314 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent; 315 316 HashSet<View> mTempHashSet; 317 318 private final int mDensity; 319 private final int mNoncompatDensity; 320 321 /** 322 * Consistency verifier for debugging purposes. 323 */ 324 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 325 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 326 new InputEventConsistencyVerifier(this, 0) : null; 327 328 static final class SystemUiVisibilityInfo { 329 int seq; 330 int globalVisibility; 331 int localValue; 332 int localChanges; 333 } 334 335 public ViewRootImpl(Context context, Display display) { 336 super(); 337 338 if (MEASURE_LATENCY) { 339 if (lt == null) { 340 lt = new LatencyTimer(100, 1000); 341 } 342 } 343 344 // Initialize the statics when this class is first instantiated. This is 345 // done here instead of in the static block because Zygote does not 346 // allow the spawning of threads. 347 mWindowSession = WindowManagerGlobal.getWindowSession(context.getMainLooper()); 348 mDisplay = display; 349 350 CompatibilityInfoHolder cih = display.getCompatibilityInfo(); 351 mCompatibilityInfo = cih != null ? cih : new CompatibilityInfoHolder(); 352 353 mThread = Thread.currentThread(); 354 mLocation = new WindowLeaked(null); 355 mLocation.fillInStackTrace(); 356 mWidth = -1; 357 mHeight = -1; 358 mDirty = new Rect(); 359 mTempRect = new Rect(); 360 mVisRect = new Rect(); 361 mWinFrame = new Rect(); 362 mWindow = new W(this); 363 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion; 364 mInputMethodCallback = new InputMethodCallback(this); 365 mViewVisibility = View.GONE; 366 mTransparentRegion = new Region(); 367 mPreviousTransparentRegion = new Region(); 368 mFirst = true; // true for the first time the view is added 369 mAdded = false; 370 mAccessibilityManager = AccessibilityManager.getInstance(context); 371 mAccessibilityInteractionConnectionManager = 372 new AccessibilityInteractionConnectionManager(); 373 mAccessibilityManager.addAccessibilityStateChangeListener( 374 mAccessibilityInteractionConnectionManager); 375 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this); 376 mViewConfiguration = ViewConfiguration.get(context); 377 mDensity = context.getResources().getDisplayMetrics().densityDpi; 378 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi; 379 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context); 380 mProfileRendering = Boolean.parseBoolean( 381 SystemProperties.get(PROPERTY_PROFILE_RENDERING, "false")); 382 mChoreographer = Choreographer.getInstance(); 383 384 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 385 mAttachInfo.mScreenOn = powerManager.isScreenOn(); 386 loadSystemProperties(); 387 } 388 389 /** 390 * @return True if the application requests the use of a separate render thread, 391 * false otherwise 392 */ 393 private static boolean isRenderThreadRequested(Context context) { 394 if (USE_RENDER_THREAD) { 395 synchronized (sRenderThreadQueryLock) { 396 if (!sRenderThreadQueried) { 397 final PackageManager packageManager = context.getPackageManager(); 398 final String packageName = context.getApplicationInfo().packageName; 399 try { 400 ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 401 PackageManager.GET_META_DATA); 402 if (applicationInfo.metaData != null) { 403 sUseRenderThread = applicationInfo.metaData.getBoolean( 404 "android.graphics.renderThread", false); 405 } 406 } catch (PackageManager.NameNotFoundException e) { 407 } finally { 408 sRenderThreadQueried = true; 409 } 410 } 411 return sUseRenderThread; 412 } 413 } else { 414 return false; 415 } 416 } 417 418 public static void addFirstDrawHandler(Runnable callback) { 419 synchronized (sFirstDrawHandlers) { 420 if (!sFirstDrawComplete) { 421 sFirstDrawHandlers.add(callback); 422 } 423 } 424 } 425 426 public static void addConfigCallback(ComponentCallbacks callback) { 427 synchronized (sConfigCallbacks) { 428 sConfigCallbacks.add(callback); 429 } 430 } 431 432 // FIXME for perf testing only 433 private boolean mProfile = false; 434 435 /** 436 * Call this to profile the next traversal call. 437 * FIXME for perf testing only. Remove eventually 438 */ 439 public void profile() { 440 mProfile = true; 441 } 442 443 /** 444 * Indicates whether we are in touch mode. Calling this method triggers an IPC 445 * call and should be avoided whenever possible. 446 * 447 * @return True, if the device is in touch mode, false otherwise. 448 * 449 * @hide 450 */ 451 static boolean isInTouchMode() { 452 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession(); 453 if (windowSession != null) { 454 try { 455 return windowSession.getInTouchMode(); 456 } catch (RemoteException e) { 457 } 458 } 459 return false; 460 } 461 462 /** 463 * We have one child 464 */ 465 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) { 466 synchronized (this) { 467 if (mView == null) { 468 mView = view; 469 mFallbackEventHandler.setView(view); 470 mWindowAttributes.copyFrom(attrs); 471 attrs = mWindowAttributes; 472 // Keep track of the actual window flags supplied by the client. 473 mClientWindowLayoutFlags = attrs.flags; 474 475 setAccessibilityFocus(null, null); 476 477 if (view instanceof RootViewSurfaceTaker) { 478 mSurfaceHolderCallback = 479 ((RootViewSurfaceTaker)view).willYouTakeTheSurface(); 480 if (mSurfaceHolderCallback != null) { 481 mSurfaceHolder = new TakenSurfaceHolder(); 482 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN); 483 } 484 } 485 486 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 487 mTranslator = compatibilityInfo.getTranslator(); 488 489 // If the application owns the surface, don't enable hardware acceleration 490 if (mSurfaceHolder == null) { 491 enableHardwareAcceleration(mView.getContext(), attrs); 492 } 493 494 boolean restore = false; 495 if (mTranslator != null) { 496 mSurface.setCompatibilityTranslator(mTranslator); 497 restore = true; 498 attrs.backup(); 499 mTranslator.translateWindowLayout(attrs); 500 } 501 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs); 502 503 if (!compatibilityInfo.supportsScreen()) { 504 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 505 mLastInCompatMode = true; 506 } 507 508 mSoftInputMode = attrs.softInputMode; 509 mWindowAttributesChanged = true; 510 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED; 511 mAttachInfo.mRootView = view; 512 mAttachInfo.mScalingRequired = mTranslator != null; 513 mAttachInfo.mApplicationScale = 514 mTranslator == null ? 1.0f : mTranslator.applicationScale; 515 if (panelParentView != null) { 516 mAttachInfo.mPanelParentWindowToken 517 = panelParentView.getApplicationWindowToken(); 518 } 519 mAdded = true; 520 int res; /* = WindowManagerImpl.ADD_OKAY; */ 521 522 // Schedule the first layout -before- adding to the window 523 // manager, to make sure we do the relayout before receiving 524 // any other events from the system. 525 requestLayout(); 526 if ((mWindowAttributes.inputFeatures 527 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { 528 mInputChannel = new InputChannel(); 529 } 530 try { 531 mOrigWindowType = mWindowAttributes.type; 532 mAttachInfo.mRecomputeGlobalAttributes = true; 533 collectViewAttributes(); 534 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes, 535 getHostVisibility(), mDisplay.getDisplayId(), 536 mAttachInfo.mContentInsets, mInputChannel); 537 } catch (RemoteException e) { 538 mAdded = false; 539 mView = null; 540 mAttachInfo.mRootView = null; 541 mInputChannel = null; 542 mFallbackEventHandler.setView(null); 543 unscheduleTraversals(); 544 setAccessibilityFocus(null, null); 545 throw new RuntimeException("Adding window failed", e); 546 } finally { 547 if (restore) { 548 attrs.restore(); 549 } 550 } 551 552 if (mTranslator != null) { 553 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets); 554 } 555 mPendingContentInsets.set(mAttachInfo.mContentInsets); 556 mPendingVisibleInsets.set(0, 0, 0, 0); 557 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow); 558 if (res < WindowManagerGlobal.ADD_OKAY) { 559 mView = null; 560 mAttachInfo.mRootView = null; 561 mAdded = false; 562 mFallbackEventHandler.setView(null); 563 unscheduleTraversals(); 564 setAccessibilityFocus(null, null); 565 switch (res) { 566 case WindowManagerGlobal.ADD_BAD_APP_TOKEN: 567 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN: 568 throw new WindowManager.BadTokenException( 569 "Unable to add window -- token " + attrs.token 570 + " is not valid; is your activity running?"); 571 case WindowManagerGlobal.ADD_NOT_APP_TOKEN: 572 throw new WindowManager.BadTokenException( 573 "Unable to add window -- token " + attrs.token 574 + " is not for an application"); 575 case WindowManagerGlobal.ADD_APP_EXITING: 576 throw new WindowManager.BadTokenException( 577 "Unable to add window -- app for token " + attrs.token 578 + " is exiting"); 579 case WindowManagerGlobal.ADD_DUPLICATE_ADD: 580 throw new WindowManager.BadTokenException( 581 "Unable to add window -- window " + mWindow 582 + " has already been added"); 583 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED: 584 // Silently ignore -- we would have just removed it 585 // right away, anyway. 586 return; 587 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON: 588 throw new WindowManager.BadTokenException( 589 "Unable to add window " + mWindow + 590 " -- another window of this type already exists"); 591 case WindowManagerGlobal.ADD_PERMISSION_DENIED: 592 throw new WindowManager.BadTokenException( 593 "Unable to add window " + mWindow + 594 " -- permission denied for this window type"); 595 } 596 throw new RuntimeException( 597 "Unable to add window -- unknown error code " + res); 598 } 599 600 if (view instanceof RootViewSurfaceTaker) { 601 mInputQueueCallback = 602 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue(); 603 } 604 if (mInputChannel != null) { 605 if (mInputQueueCallback != null) { 606 mInputQueue = new InputQueue(mInputChannel); 607 mInputQueueCallback.onInputQueueCreated(mInputQueue); 608 } else { 609 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel, 610 Looper.myLooper()); 611 } 612 } 613 614 view.assignParent(this); 615 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0; 616 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0; 617 618 if (mAccessibilityManager.isEnabled()) { 619 mAccessibilityInteractionConnectionManager.ensureConnection(); 620 } 621 622 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 623 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES); 624 } 625 } 626 } 627 } 628 629 void destroyHardwareResources() { 630 if (mAttachInfo.mHardwareRenderer != null) { 631 if (mAttachInfo.mHardwareRenderer.isEnabled()) { 632 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 633 } 634 mAttachInfo.mHardwareRenderer.destroy(false); 635 } 636 } 637 638 void terminateHardwareResources() { 639 if (mAttachInfo.mHardwareRenderer != null) { 640 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView); 641 mAttachInfo.mHardwareRenderer.destroy(false); 642 } 643 } 644 645 void destroyHardwareLayers() { 646 if (mThread != Thread.currentThread()) { 647 if (mAttachInfo.mHardwareRenderer != null && 648 mAttachInfo.mHardwareRenderer.isEnabled()) { 649 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE); 650 } 651 } else { 652 if (mAttachInfo.mHardwareRenderer != null && 653 mAttachInfo.mHardwareRenderer.isEnabled()) { 654 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 655 } 656 } 657 } 658 659 void pushHardwareLayerUpdate(HardwareLayer layer) { 660 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 661 mAttachInfo.mHardwareRenderer.pushLayerUpdate(layer); 662 } 663 } 664 665 public boolean attachFunctor(int functor) { 666 //noinspection SimplifiableIfStatement 667 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 668 return mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor); 669 } 670 return false; 671 } 672 673 public void detachFunctor(int functor) { 674 if (mAttachInfo.mHardwareRenderer != null) { 675 mAttachInfo.mHardwareRenderer.detachFunctor(functor); 676 } 677 } 678 679 private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) { 680 mAttachInfo.mHardwareAccelerated = false; 681 mAttachInfo.mHardwareAccelerationRequested = false; 682 683 // Don't enable hardware acceleration when the application is in compatibility mode 684 if (mTranslator != null) return; 685 686 // Try to enable hardware acceleration if requested 687 final boolean hardwareAccelerated = 688 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0; 689 690 if (hardwareAccelerated) { 691 if (!HardwareRenderer.isAvailable()) { 692 return; 693 } 694 695 // Persistent processes (including the system) should not do 696 // accelerated rendering on low-end devices. In that case, 697 // sRendererDisabled will be set. In addition, the system process 698 // itself should never do accelerated rendering. In that case, both 699 // sRendererDisabled and sSystemRendererDisabled are set. When 700 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED 701 // can be used by code on the system process to escape that and enable 702 // HW accelerated drawing. (This is basically for the lock screen.) 703 704 final boolean fakeHwAccelerated = (attrs.privateFlags & 705 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0; 706 final boolean forceHwAccelerated = (attrs.privateFlags & 707 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0; 708 709 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled 710 && forceHwAccelerated)) { 711 // Don't enable hardware acceleration when we're not on the main thread 712 if (!HardwareRenderer.sSystemRendererDisabled && 713 Looper.getMainLooper() != Looper.myLooper()) { 714 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware " 715 + "acceleration outside of the main thread, aborting"); 716 return; 717 } 718 719 final boolean renderThread = isRenderThreadRequested(context); 720 if (renderThread) { 721 Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated"); 722 } 723 724 if (mAttachInfo.mHardwareRenderer != null) { 725 mAttachInfo.mHardwareRenderer.destroy(true); 726 } 727 728 final boolean translucent = attrs.format != PixelFormat.OPAQUE; 729 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent); 730 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested 731 = mAttachInfo.mHardwareRenderer != null; 732 733 } else if (fakeHwAccelerated) { 734 // The window had wanted to use hardware acceleration, but this 735 // is not allowed in its process. By setting this flag, it can 736 // still render as if it was accelerated. This is basically for 737 // the preview windows the window manager shows for launching 738 // applications, so they will look more like the app being launched. 739 mAttachInfo.mHardwareAccelerationRequested = true; 740 } 741 } 742 } 743 744 public View getView() { 745 return mView; 746 } 747 748 final WindowLeaked getLocation() { 749 return mLocation; 750 } 751 752 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) { 753 synchronized (this) { 754 int oldSoftInputMode = mWindowAttributes.softInputMode; 755 // Keep track of the actual window flags supplied by the client. 756 mClientWindowLayoutFlags = attrs.flags; 757 // preserve compatible window flag if exists. 758 int compatibleWindowFlag = 759 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 760 // transfer over system UI visibility values as they carry current state. 761 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility; 762 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility; 763 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs); 764 mWindowAttributes.flags |= compatibleWindowFlag; 765 766 applyKeepScreenOnFlag(mWindowAttributes); 767 768 if (newView) { 769 mSoftInputMode = attrs.softInputMode; 770 requestLayout(); 771 } 772 // Don't lose the mode we last auto-computed. 773 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 774 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 775 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode 776 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 777 | (oldSoftInputMode 778 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST); 779 } 780 mWindowAttributesChanged = true; 781 scheduleTraversals(); 782 } 783 } 784 785 void handleAppVisibility(boolean visible) { 786 if (mAppVisible != visible) { 787 mAppVisible = visible; 788 scheduleTraversals(); 789 } 790 } 791 792 void handleGetNewSurface() { 793 mNewSurfaceNeeded = true; 794 mFullRedrawNeeded = true; 795 scheduleTraversals(); 796 } 797 798 void handleScreenStateChange(boolean on) { 799 if (on != mAttachInfo.mScreenOn) { 800 mAttachInfo.mScreenOn = on; 801 if (mView != null) { 802 mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF); 803 } 804 if (on) { 805 mFullRedrawNeeded = true; 806 scheduleTraversals(); 807 } 808 } 809 } 810 811 /** 812 * {@inheritDoc} 813 */ 814 public void requestFitSystemWindows() { 815 checkThread(); 816 mFitSystemWindowsRequested = true; 817 scheduleTraversals(); 818 } 819 820 /** 821 * {@inheritDoc} 822 */ 823 public void requestLayout() { 824 checkThread(); 825 mLayoutRequested = true; 826 scheduleTraversals(); 827 } 828 829 /** 830 * {@inheritDoc} 831 */ 832 public boolean isLayoutRequested() { 833 return mLayoutRequested; 834 } 835 836 void invalidate() { 837 mDirty.set(0, 0, mWidth, mHeight); 838 scheduleTraversals(); 839 } 840 841 void invalidateWorld(View view) { 842 view.invalidate(); 843 if (view instanceof ViewGroup) { 844 ViewGroup parent = (ViewGroup) view; 845 for (int i = 0; i < parent.getChildCount(); i++) { 846 invalidateWorld(parent.getChildAt(i)); 847 } 848 } 849 } 850 851 public void invalidateChild(View child, Rect dirty) { 852 invalidateChildInParent(null, dirty); 853 } 854 855 public ViewParent invalidateChildInParent(int[] location, Rect dirty) { 856 checkThread(); 857 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty); 858 859 if (dirty == null) { 860 invalidate(); 861 return null; 862 } else if (dirty.isEmpty()) { 863 return null; 864 } 865 866 if (mCurScrollY != 0 || mTranslator != null) { 867 mTempRect.set(dirty); 868 dirty = mTempRect; 869 if (mCurScrollY != 0) { 870 dirty.offset(0, -mCurScrollY); 871 } 872 if (mTranslator != null) { 873 mTranslator.translateRectInAppWindowToScreen(dirty); 874 } 875 if (mAttachInfo.mScalingRequired) { 876 dirty.inset(-1, -1); 877 } 878 } 879 880 final Rect localDirty = mDirty; 881 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) { 882 mAttachInfo.mSetIgnoreDirtyState = true; 883 mAttachInfo.mIgnoreDirtyState = true; 884 } 885 886 // Add the new dirty rect to the current one 887 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom); 888 // Intersect with the bounds of the window to skip 889 // updates that lie outside of the visible region 890 final float appScale = mAttachInfo.mApplicationScale; 891 localDirty.intersect(0, 0, 892 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 893 894 if (!mWillDrawSoon) { 895 scheduleTraversals(); 896 } 897 898 return null; 899 } 900 901 void setStopped(boolean stopped) { 902 if (mStopped != stopped) { 903 mStopped = stopped; 904 if (!stopped) { 905 scheduleTraversals(); 906 } 907 } 908 } 909 910 public ViewParent getParent() { 911 return null; 912 } 913 914 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 915 if (child != mView) { 916 throw new RuntimeException("child is not mine, honest!"); 917 } 918 // Note: don't apply scroll offset, because we want to know its 919 // visibility in the virtual canvas being given to the view hierarchy. 920 return r.intersect(0, 0, mWidth, mHeight); 921 } 922 923 public void bringChildToFront(View child) { 924 } 925 926 int getHostVisibility() { 927 return mAppVisible ? mView.getVisibility() : View.GONE; 928 } 929 930 void disposeResizeBuffer() { 931 if (mResizeBuffer != null) { 932 mResizeBuffer.destroy(); 933 mResizeBuffer = null; 934 } 935 } 936 937 /** 938 * Add LayoutTransition to the list of transitions to be started in the next traversal. 939 * This list will be cleared after the transitions on the list are start()'ed. These 940 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup 941 * happens during the layout phase of traversal, which we want to complete before any of the 942 * animations are started (because those animations may side-effect properties that layout 943 * depends upon, like the bounding rectangles of the affected views). So we add the transition 944 * to the list and it is started just prior to starting the drawing phase of traversal. 945 * 946 * @param transition The LayoutTransition to be started on the next traversal. 947 * 948 * @hide 949 */ 950 public void requestTransitionStart(LayoutTransition transition) { 951 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) { 952 if (mPendingTransitions == null) { 953 mPendingTransitions = new ArrayList<LayoutTransition>(); 954 } 955 mPendingTransitions.add(transition); 956 } 957 } 958 959 void scheduleTraversals() { 960 if (!mTraversalScheduled) { 961 mTraversalScheduled = true; 962 mTraversalBarrier = mHandler.getLooper().postSyncBarrier(); 963 mChoreographer.postCallback( 964 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 965 scheduleConsumeBatchedInput(); 966 } 967 } 968 969 void unscheduleTraversals() { 970 if (mTraversalScheduled) { 971 mTraversalScheduled = false; 972 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 973 mChoreographer.removeCallbacks( 974 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 975 } 976 } 977 978 void doTraversal() { 979 if (mTraversalScheduled) { 980 mTraversalScheduled = false; 981 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 982 983 if (mProfile) { 984 Debug.startMethodTracing("ViewAncestor"); 985 } 986 987 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals"); 988 try { 989 performTraversals(); 990 } finally { 991 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 992 } 993 994 if (mProfile) { 995 Debug.stopMethodTracing(); 996 mProfile = false; 997 } 998 } 999 } 1000 1001 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) { 1002 // Update window's global keep screen on flag: if a view has requested 1003 // that the screen be kept on, then it is always set; otherwise, it is 1004 // set to whatever the client last requested for the global state. 1005 if (mAttachInfo.mKeepScreenOn) { 1006 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 1007 } else { 1008 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) 1009 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1010 } 1011 } 1012 1013 private boolean collectViewAttributes() { 1014 final View.AttachInfo attachInfo = mAttachInfo; 1015 if (attachInfo.mRecomputeGlobalAttributes) { 1016 //Log.i(TAG, "Computing view hierarchy attributes!"); 1017 attachInfo.mRecomputeGlobalAttributes = false; 1018 boolean oldScreenOn = attachInfo.mKeepScreenOn; 1019 attachInfo.mKeepScreenOn = false; 1020 attachInfo.mSystemUiVisibility = 0; 1021 attachInfo.mHasSystemUiListeners = false; 1022 mView.dispatchCollectViewAttributes(attachInfo, 0); 1023 attachInfo.mSystemUiVisibility &= ~attachInfo.mDisabledSystemUiVisibility; 1024 WindowManager.LayoutParams params = mWindowAttributes; 1025 if (attachInfo.mKeepScreenOn != oldScreenOn 1026 || attachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility 1027 || attachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) { 1028 applyKeepScreenOnFlag(params); 1029 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility; 1030 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners; 1031 mView.dispatchWindowSystemUiVisiblityChanged(attachInfo.mSystemUiVisibility); 1032 return true; 1033 } 1034 } 1035 return false; 1036 } 1037 1038 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp, 1039 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) { 1040 int childWidthMeasureSpec; 1041 int childHeightMeasureSpec; 1042 boolean windowSizeMayChange = false; 1043 1044 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG, 1045 "Measuring " + host + " in display " + desiredWindowWidth 1046 + "x" + desiredWindowHeight + "..."); 1047 1048 boolean goodMeasure = false; 1049 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) { 1050 // On large screens, we don't want to allow dialogs to just 1051 // stretch to fill the entire width of the screen to display 1052 // one line of text. First try doing the layout at a smaller 1053 // size to see if it will fit. 1054 final DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1055 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true); 1056 int baseSize = 0; 1057 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) { 1058 baseSize = (int)mTmpValue.getDimension(packageMetrics); 1059 } 1060 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize); 1061 if (baseSize != 0 && desiredWindowWidth > baseSize) { 1062 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1063 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1064 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1065 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1066 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1067 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1068 goodMeasure = true; 1069 } else { 1070 // Didn't fit in that size... try expanding a bit. 1071 baseSize = (baseSize+desiredWindowWidth)/2; 1072 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize=" 1073 + baseSize); 1074 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1075 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1076 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1077 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1078 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1079 if (DEBUG_DIALOG) Log.v(TAG, "Good!"); 1080 goodMeasure = true; 1081 } 1082 } 1083 } 1084 } 1085 1086 if (!goodMeasure) { 1087 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); 1088 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1089 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1090 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) { 1091 windowSizeMayChange = true; 1092 } 1093 } 1094 1095 if (DBG) { 1096 System.out.println("======================================"); 1097 System.out.println("performTraversals -- after measure"); 1098 host.debug(); 1099 } 1100 1101 return windowSizeMayChange; 1102 } 1103 1104 private void performTraversals() { 1105 // cache mView since it is used so much below... 1106 final View host = mView; 1107 1108 if (DBG) { 1109 System.out.println("======================================"); 1110 System.out.println("performTraversals"); 1111 host.debug(); 1112 } 1113 1114 if (host == null || !mAdded) 1115 return; 1116 1117 mIsInTraversal = true; 1118 mWillDrawSoon = true; 1119 boolean windowSizeMayChange = false; 1120 boolean newSurface = false; 1121 boolean surfaceChanged = false; 1122 WindowManager.LayoutParams lp = mWindowAttributes; 1123 1124 int desiredWindowWidth; 1125 int desiredWindowHeight; 1126 1127 final View.AttachInfo attachInfo = mAttachInfo; 1128 1129 final int viewVisibility = getHostVisibility(); 1130 boolean viewVisibilityChanged = mViewVisibility != viewVisibility 1131 || mNewSurfaceNeeded; 1132 1133 WindowManager.LayoutParams params = null; 1134 if (mWindowAttributesChanged) { 1135 mWindowAttributesChanged = false; 1136 surfaceChanged = true; 1137 params = lp; 1138 } 1139 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 1140 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) { 1141 params = lp; 1142 mFullRedrawNeeded = true; 1143 mLayoutRequested = true; 1144 if (mLastInCompatMode) { 1145 params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1146 mLastInCompatMode = false; 1147 } else { 1148 params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1149 mLastInCompatMode = true; 1150 } 1151 } 1152 1153 mWindowAttributesChangesFlag = 0; 1154 1155 Rect frame = mWinFrame; 1156 if (mFirst) { 1157 mFullRedrawNeeded = true; 1158 mLayoutRequested = true; 1159 1160 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1161 // NOTE -- system code, won't try to do compat mode. 1162 Point size = new Point(); 1163 mDisplay.getRealSize(size); 1164 desiredWindowWidth = size.x; 1165 desiredWindowHeight = size.y; 1166 } else { 1167 DisplayMetrics packageMetrics = 1168 mView.getContext().getResources().getDisplayMetrics(); 1169 desiredWindowWidth = packageMetrics.widthPixels; 1170 desiredWindowHeight = packageMetrics.heightPixels; 1171 } 1172 1173 // For the very first time, tell the view hierarchy that it 1174 // is attached to the window. Note that at this point the surface 1175 // object is not initialized to its backing store, but soon it 1176 // will be (assuming the window is visible). 1177 attachInfo.mSurface = mSurface; 1178 // We used to use the following condition to choose 32 bits drawing caches: 1179 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888 1180 // However, windows are now always 32 bits by default, so choose 32 bits 1181 attachInfo.mUse32BitDrawingCache = true; 1182 attachInfo.mHasWindowFocus = false; 1183 attachInfo.mWindowVisibility = viewVisibility; 1184 attachInfo.mRecomputeGlobalAttributes = false; 1185 viewVisibilityChanged = false; 1186 mLastConfiguration.setTo(host.getResources().getConfiguration()); 1187 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 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 } 1622 } 1623 } 1624 1625 if (!mStopped) { 1626 boolean focusChangedDueToTouchMode = ensureTouchModeLocally( 1627 (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0); 1628 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth() 1629 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) { 1630 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); 1631 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height); 1632 1633 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth=" 1634 + mWidth + " measuredWidth=" + host.getMeasuredWidth() 1635 + " mHeight=" + mHeight 1636 + " measuredHeight=" + host.getMeasuredHeight() 1637 + " coveredInsetsChanged=" + contentInsetsChanged); 1638 1639 // Ask host how big it wants to be 1640 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1641 1642 // Implementation of weights from WindowManager.LayoutParams 1643 // We just grow the dimensions as needed and re-measure if 1644 // needs be 1645 int width = host.getMeasuredWidth(); 1646 int height = host.getMeasuredHeight(); 1647 boolean measureAgain = false; 1648 1649 if (lp.horizontalWeight > 0.0f) { 1650 width += (int) ((mWidth - width) * lp.horizontalWeight); 1651 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, 1652 MeasureSpec.EXACTLY); 1653 measureAgain = true; 1654 } 1655 if (lp.verticalWeight > 0.0f) { 1656 height += (int) ((mHeight - height) * lp.verticalWeight); 1657 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, 1658 MeasureSpec.EXACTLY); 1659 measureAgain = true; 1660 } 1661 1662 if (measureAgain) { 1663 if (DEBUG_LAYOUT) Log.v(TAG, 1664 "And hey let's measure once more: width=" + width 1665 + " height=" + height); 1666 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1667 } 1668 1669 layoutRequested = true; 1670 } 1671 } 1672 } else { 1673 // Not the first pass and no window/insets/visibility change but the window 1674 // may have moved and we need check that and if so to update the left and right 1675 // in the attach info. We translate only the window frame since on window move 1676 // the window manager tells us only for the new frame but the insets are the 1677 // same and we do not want to translate them more than once. 1678 1679 // TODO: Well, we are checking whether the frame has changed similarly 1680 // to how this is done for the insets. This is however incorrect since 1681 // the insets and the frame are translated. For example, the old frame 1682 // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new 1683 // reported frame is (2, 2 - 2, 2) which implies no change but this is not 1684 // true since we are comparing a not translated value to a translated one. 1685 // This scenario is rare but we may want to fix that. 1686 1687 final boolean windowMoved = (attachInfo.mWindowLeft != frame.left 1688 || attachInfo.mWindowTop != frame.top); 1689 if (windowMoved) { 1690 if (mTranslator != null) { 1691 mTranslator.translateRectInScreenToAppWinFrame(frame); 1692 } 1693 attachInfo.mWindowLeft = frame.left; 1694 attachInfo.mWindowTop = frame.top; 1695 } 1696 } 1697 1698 final boolean didLayout = layoutRequested && !mStopped; 1699 boolean triggerGlobalLayoutListener = didLayout 1700 || attachInfo.mRecomputeGlobalAttributes; 1701 if (didLayout) { 1702 performLayout(); 1703 1704 // By this point all views have been sized and positionned 1705 // We can compute the transparent area 1706 1707 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 1708 // start out transparent 1709 // TODO: AVOID THAT CALL BY CACHING THE RESULT? 1710 host.getLocationInWindow(mTmpLocation); 1711 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1], 1712 mTmpLocation[0] + host.mRight - host.mLeft, 1713 mTmpLocation[1] + host.mBottom - host.mTop); 1714 1715 host.gatherTransparentRegion(mTransparentRegion); 1716 if (mTranslator != null) { 1717 mTranslator.translateRegionInWindowToScreen(mTransparentRegion); 1718 } 1719 1720 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) { 1721 mPreviousTransparentRegion.set(mTransparentRegion); 1722 // reconfigure window manager 1723 try { 1724 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion); 1725 } catch (RemoteException e) { 1726 } 1727 } 1728 } 1729 1730 if (DBG) { 1731 System.out.println("======================================"); 1732 System.out.println("performTraversals -- after setFrame"); 1733 host.debug(); 1734 } 1735 } 1736 1737 if (triggerGlobalLayoutListener) { 1738 attachInfo.mRecomputeGlobalAttributes = false; 1739 attachInfo.mTreeObserver.dispatchOnGlobalLayout(); 1740 1741 if (AccessibilityManager.getInstance(host.mContext).isEnabled()) { 1742 postSendWindowContentChangedCallback(mView); 1743 } 1744 } 1745 1746 if (computesInternalInsets) { 1747 // Clear the original insets. 1748 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets; 1749 insets.reset(); 1750 1751 // Compute new insets in place. 1752 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets); 1753 1754 // Tell the window manager. 1755 if (insetsPending || !mLastGivenInsets.equals(insets)) { 1756 mLastGivenInsets.set(insets); 1757 1758 // Translate insets to screen coordinates if needed. 1759 final Rect contentInsets; 1760 final Rect visibleInsets; 1761 final Region touchableRegion; 1762 if (mTranslator != null) { 1763 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets); 1764 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets); 1765 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion); 1766 } else { 1767 contentInsets = insets.contentInsets; 1768 visibleInsets = insets.visibleInsets; 1769 touchableRegion = insets.touchableRegion; 1770 } 1771 1772 try { 1773 mWindowSession.setInsets(mWindow, insets.mTouchableInsets, 1774 contentInsets, visibleInsets, touchableRegion); 1775 } catch (RemoteException e) { 1776 } 1777 } 1778 } 1779 1780 boolean skipDraw = false; 1781 1782 if (mFirst) { 1783 // handle first focus request 1784 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()=" 1785 + mView.hasFocus()); 1786 if (mView != null) { 1787 if (!mView.hasFocus()) { 1788 mView.requestFocus(View.FOCUS_FORWARD); 1789 mFocusedView = mRealFocusedView = mView.findFocus(); 1790 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view=" 1791 + mFocusedView); 1792 } else { 1793 mRealFocusedView = mView.findFocus(); 1794 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view=" 1795 + mRealFocusedView); 1796 } 1797 } 1798 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_ANIMATING) != 0) { 1799 // The first time we relayout the window, if the system is 1800 // doing window animations, we want to hold of on any future 1801 // draws until the animation is done. 1802 mWindowsAnimating = true; 1803 } 1804 } else if (mWindowsAnimating) { 1805 skipDraw = true; 1806 } 1807 1808 mFirst = false; 1809 mWillDrawSoon = false; 1810 mNewSurfaceNeeded = false; 1811 mViewVisibility = viewVisibility; 1812 1813 if (mAttachInfo.mHasWindowFocus) { 1814 final boolean imTarget = WindowManager.LayoutParams 1815 .mayUseInputMethod(mWindowAttributes.flags); 1816 if (imTarget != mLastWasImTarget) { 1817 mLastWasImTarget = imTarget; 1818 InputMethodManager imm = InputMethodManager.peekInstance(); 1819 if (imm != null && imTarget) { 1820 imm.startGettingWindowFocus(mView); 1821 imm.onWindowFocus(mView, mView.findFocus(), 1822 mWindowAttributes.softInputMode, 1823 !mHasHadWindowFocus, mWindowAttributes.flags); 1824 } 1825 } 1826 } 1827 1828 // Remember if we must report the next draw. 1829 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 1830 mReportNextDraw = true; 1831 } 1832 1833 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw() || 1834 viewVisibility != View.VISIBLE; 1835 1836 if (!cancelDraw && !newSurface) { 1837 if (!skipDraw || mReportNextDraw) { 1838 if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1839 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1840 mPendingTransitions.get(i).startChangingAnimations(); 1841 } 1842 mPendingTransitions.clear(); 1843 } 1844 1845 performDraw(); 1846 } 1847 } else { 1848 if (viewVisibility == View.VISIBLE) { 1849 // Try again 1850 scheduleTraversals(); 1851 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) { 1852 for (int i = 0; i < mPendingTransitions.size(); ++i) { 1853 mPendingTransitions.get(i).endChangingAnimations(); 1854 } 1855 mPendingTransitions.clear(); 1856 } 1857 } 1858 1859 mIsInTraversal = false; 1860 } 1861 1862 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) { 1863 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure"); 1864 try { 1865 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); 1866 } finally { 1867 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 1868 } 1869 } 1870 1871 private void performLayout() { 1872 mLayoutRequested = false; 1873 mScrollMayChange = true; 1874 1875 final View host = mView; 1876 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) { 1877 Log.v(TAG, "Laying out " + host + " to (" + 1878 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")"); 1879 } 1880 1881 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout"); 1882 try { 1883 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); 1884 } finally { 1885 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 1886 } 1887 } 1888 1889 public void requestTransparentRegion(View child) { 1890 // the test below should not fail unless someone is messing with us 1891 checkThread(); 1892 if (mView == child) { 1893 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS; 1894 // Need to make sure we re-evaluate the window attributes next 1895 // time around, to ensure the window has the correct format. 1896 mWindowAttributesChanged = true; 1897 mWindowAttributesChangesFlag = 0; 1898 requestLayout(); 1899 } 1900 } 1901 1902 /** 1903 * Figures out the measure spec for the root view in a window based on it's 1904 * layout params. 1905 * 1906 * @param windowSize 1907 * The available width or height of the window 1908 * 1909 * @param rootDimension 1910 * The layout params for one dimension (width or height) of the 1911 * window. 1912 * 1913 * @return The measure spec to use to measure the root view. 1914 */ 1915 private static int getRootMeasureSpec(int windowSize, int rootDimension) { 1916 int measureSpec; 1917 switch (rootDimension) { 1918 1919 case ViewGroup.LayoutParams.MATCH_PARENT: 1920 // Window can't resize. Force root view to be windowSize. 1921 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); 1922 break; 1923 case ViewGroup.LayoutParams.WRAP_CONTENT: 1924 // Window can resize. Set max size for root view. 1925 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST); 1926 break; 1927 default: 1928 // Window wants to be an exact size. Force root view to be that size. 1929 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY); 1930 break; 1931 } 1932 return measureSpec; 1933 } 1934 1935 int mHardwareYOffset; 1936 int mResizeAlpha; 1937 final Paint mResizePaint = new Paint(); 1938 1939 public void onHardwarePreDraw(HardwareCanvas canvas) { 1940 canvas.translate(0, -mHardwareYOffset); 1941 } 1942 1943 public void onHardwarePostDraw(HardwareCanvas canvas) { 1944 if (mResizeBuffer != null) { 1945 mResizePaint.setAlpha(mResizeAlpha); 1946 canvas.drawHardwareLayer(mResizeBuffer, 0.0f, mHardwareYOffset, mResizePaint); 1947 } 1948 drawAccessibilityFocusedDrawableIfNeeded(canvas); 1949 } 1950 1951 /** 1952 * @hide 1953 */ 1954 void outputDisplayList(View view) { 1955 if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) { 1956 DisplayList displayList = view.getDisplayList(); 1957 if (displayList != null) { 1958 mAttachInfo.mHardwareCanvas.outputDisplayList(displayList); 1959 } 1960 } 1961 } 1962 1963 /** 1964 * @see #PROPERTY_PROFILE_RENDERING 1965 */ 1966 private void profileRendering(boolean enabled) { 1967 if (mProfileRendering) { 1968 mRenderProfilingEnabled = enabled; 1969 if (mRenderProfiler == null) { 1970 mRenderProfiler = new Thread(new Runnable() { 1971 @Override 1972 public void run() { 1973 Log.d(TAG, "Starting profiling thread"); 1974 while (mRenderProfilingEnabled) { 1975 mAttachInfo.mHandler.post(new Runnable() { 1976 @Override 1977 public void run() { 1978 mDirty.set(0, 0, mWidth, mHeight); 1979 scheduleTraversals(); 1980 } 1981 }); 1982 try { 1983 // TODO: This should use vsync when we get an API 1984 Thread.sleep(15); 1985 } catch (InterruptedException e) { 1986 Log.d(TAG, "Exiting profiling thread"); 1987 } 1988 } 1989 } 1990 }, "Rendering Profiler"); 1991 mRenderProfiler.start(); 1992 } else { 1993 mRenderProfiler.interrupt(); 1994 mRenderProfiler = null; 1995 } 1996 } 1997 } 1998 1999 /** 2000 * Called from draw() when DEBUG_FPS is enabled 2001 */ 2002 private void trackFPS() { 2003 // Tracks frames per second drawn. First value in a series of draws may be bogus 2004 // because it down not account for the intervening idle time 2005 long nowTime = System.currentTimeMillis(); 2006 if (mFpsStartTime < 0) { 2007 mFpsStartTime = mFpsPrevTime = nowTime; 2008 mFpsNumFrames = 0; 2009 } else { 2010 ++mFpsNumFrames; 2011 String thisHash = Integer.toHexString(System.identityHashCode(this)); 2012 long frameTime = nowTime - mFpsPrevTime; 2013 long totalTime = nowTime - mFpsStartTime; 2014 Log.v(TAG, "0x" + thisHash + "\tFrame time:\t" + frameTime); 2015 mFpsPrevTime = nowTime; 2016 if (totalTime > 1000) { 2017 float fps = (float) mFpsNumFrames * 1000 / totalTime; 2018 Log.v(TAG, "0x" + thisHash + "\tFPS:\t" + fps); 2019 mFpsStartTime = nowTime; 2020 mFpsNumFrames = 0; 2021 } 2022 } 2023 } 2024 2025 private void performDraw() { 2026 if (!mAttachInfo.mScreenOn && !mReportNextDraw) { 2027 return; 2028 } 2029 2030 final boolean fullRedrawNeeded = mFullRedrawNeeded; 2031 mFullRedrawNeeded = false; 2032 2033 mIsDrawing = true; 2034 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw"); 2035 try { 2036 draw(fullRedrawNeeded); 2037 } finally { 2038 mIsDrawing = false; 2039 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 2040 } 2041 2042 if (mReportNextDraw) { 2043 mReportNextDraw = false; 2044 2045 if (LOCAL_LOGV) { 2046 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle()); 2047 } 2048 if (mSurfaceHolder != null && mSurface.isValid()) { 2049 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder); 2050 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 2051 if (callbacks != null) { 2052 for (SurfaceHolder.Callback c : callbacks) { 2053 if (c instanceof SurfaceHolder.Callback2) { 2054 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded( 2055 mSurfaceHolder); 2056 } 2057 } 2058 } 2059 } 2060 try { 2061 mWindowSession.finishDrawing(mWindow); 2062 } catch (RemoteException e) { 2063 } 2064 } 2065 } 2066 2067 private void draw(boolean fullRedrawNeeded) { 2068 Surface surface = mSurface; 2069 if (surface == null || !surface.isValid()) { 2070 return; 2071 } 2072 2073 if (DEBUG_FPS) { 2074 trackFPS(); 2075 } 2076 2077 if (!sFirstDrawComplete) { 2078 synchronized (sFirstDrawHandlers) { 2079 sFirstDrawComplete = true; 2080 final int count = sFirstDrawHandlers.size(); 2081 for (int i = 0; i< count; i++) { 2082 mHandler.post(sFirstDrawHandlers.get(i)); 2083 } 2084 } 2085 } 2086 2087 scrollToRectOrFocus(null, false); 2088 2089 final AttachInfo attachInfo = mAttachInfo; 2090 if (attachInfo.mViewScrollChanged) { 2091 attachInfo.mViewScrollChanged = false; 2092 attachInfo.mTreeObserver.dispatchOnScrollChanged(); 2093 } 2094 2095 int yoff; 2096 boolean animating = mScroller != null && mScroller.computeScrollOffset(); 2097 if (animating) { 2098 yoff = mScroller.getCurrY(); 2099 } else { 2100 yoff = mScrollY; 2101 } 2102 if (mCurScrollY != yoff) { 2103 mCurScrollY = yoff; 2104 fullRedrawNeeded = true; 2105 } 2106 2107 final float appScale = attachInfo.mApplicationScale; 2108 final boolean scalingRequired = attachInfo.mScalingRequired; 2109 2110 int resizeAlpha = 0; 2111 if (mResizeBuffer != null) { 2112 long deltaTime = SystemClock.uptimeMillis() - mResizeBufferStartTime; 2113 if (deltaTime < mResizeBufferDuration) { 2114 float amt = deltaTime/(float) mResizeBufferDuration; 2115 amt = mResizeInterpolator.getInterpolation(amt); 2116 animating = true; 2117 resizeAlpha = 255 - (int)(amt*255); 2118 } else { 2119 disposeResizeBuffer(); 2120 } 2121 } 2122 2123 final Rect dirty = mDirty; 2124 if (mSurfaceHolder != null) { 2125 // The app owns the surface, we won't draw. 2126 dirty.setEmpty(); 2127 if (animating) { 2128 if (mScroller != null) { 2129 mScroller.abortAnimation(); 2130 } 2131 disposeResizeBuffer(); 2132 } 2133 return; 2134 } 2135 2136 if (fullRedrawNeeded) { 2137 attachInfo.mIgnoreDirtyState = true; 2138 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 2139 } 2140 2141 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2142 Log.v(TAG, "Draw " + mView + "/" 2143 + mWindowAttributes.getTitle() 2144 + ": dirty={" + dirty.left + "," + dirty.top 2145 + "," + dirty.right + "," + dirty.bottom + "} surface=" 2146 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" + 2147 appScale + ", width=" + mWidth + ", height=" + mHeight); 2148 } 2149 2150 attachInfo.mTreeObserver.dispatchOnDraw(); 2151 2152 if (!dirty.isEmpty() || mIsAnimating) { 2153 if (attachInfo.mHardwareRenderer != null && attachInfo.mHardwareRenderer.isEnabled()) { 2154 // Draw with hardware renderer. 2155 mIsAnimating = false; 2156 mHardwareYOffset = yoff; 2157 mResizeAlpha = resizeAlpha; 2158 2159 mCurrentDirty.set(dirty); 2160 mCurrentDirty.union(mPreviousDirty); 2161 mPreviousDirty.set(dirty); 2162 dirty.setEmpty(); 2163 2164 if (attachInfo.mHardwareRenderer.draw(mView, attachInfo, this, 2165 animating ? null : mCurrentDirty)) { 2166 mPreviousDirty.set(0, 0, mWidth, mHeight); 2167 } 2168 } else if (!drawSoftware(surface, attachInfo, yoff, scalingRequired, dirty)) { 2169 return; 2170 } 2171 } 2172 2173 if (animating) { 2174 mFullRedrawNeeded = true; 2175 scheduleTraversals(); 2176 } 2177 } 2178 2179 /** 2180 * @return true if drawing was succesfull, false if an error occurred 2181 */ 2182 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int yoff, 2183 boolean scalingRequired, Rect dirty) { 2184 2185 // If we get here with a disabled & requested hardware renderer, something went 2186 // wrong (an invalidate posted right before we destroyed the hardware surface 2187 // for instance) so we should just bail out. Locking the surface with software 2188 // rendering at this point would lock it forever and prevent hardware renderer 2189 // from doing its job when it comes back. 2190 if (attachInfo.mHardwareRenderer != null && !attachInfo.mHardwareRenderer.isEnabled() && 2191 attachInfo.mHardwareRenderer.isRequested()) { 2192 mFullRedrawNeeded = true; 2193 scheduleTraversals(); 2194 return false; 2195 } 2196 2197 // Draw with software renderer. 2198 Canvas canvas; 2199 try { 2200 int left = dirty.left; 2201 int top = dirty.top; 2202 int right = dirty.right; 2203 int bottom = dirty.bottom; 2204 2205 canvas = mSurface.lockCanvas(dirty); 2206 2207 if (left != dirty.left || top != dirty.top || right != dirty.right || 2208 bottom != dirty.bottom) { 2209 attachInfo.mIgnoreDirtyState = true; 2210 } 2211 2212 // TODO: Do this in native 2213 canvas.setDensity(mDensity); 2214 } catch (Surface.OutOfResourcesException e) { 2215 Log.e(TAG, "OutOfResourcesException locking surface", e); 2216 try { 2217 if (!mWindowSession.outOfMemory(mWindow)) { 2218 Slog.w(TAG, "No processes killed for memory; killing self"); 2219 Process.killProcess(Process.myPid()); 2220 } 2221 } catch (RemoteException ex) { 2222 } 2223 mLayoutRequested = true; // ask wm for a new surface next time. 2224 return false; 2225 } catch (IllegalArgumentException e) { 2226 Log.e(TAG, "Could not lock surface", e); 2227 // Don't assume this is due to out of memory, it could be 2228 // something else, and if it is something else then we could 2229 // kill stuff (or ourself) for no reason. 2230 mLayoutRequested = true; // ask wm for a new surface next time. 2231 return false; 2232 } 2233 2234 try { 2235 if (DEBUG_ORIENTATION || DEBUG_DRAW) { 2236 Log.v(TAG, "Surface " + surface + " drawing to bitmap w=" 2237 + canvas.getWidth() + ", h=" + canvas.getHeight()); 2238 //canvas.drawARGB(255, 255, 0, 0); 2239 } 2240 2241 // If this bitmap's format includes an alpha channel, we 2242 // need to clear it before drawing so that the child will 2243 // properly re-composite its drawing on a transparent 2244 // background. This automatically respects the clip/dirty region 2245 // or 2246 // If we are applying an offset, we need to clear the area 2247 // where the offset doesn't appear to avoid having garbage 2248 // left in the blank areas. 2249 if (!canvas.isOpaque() || yoff != 0) { 2250 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 2251 } 2252 2253 dirty.setEmpty(); 2254 mIsAnimating = false; 2255 attachInfo.mDrawingTime = SystemClock.uptimeMillis(); 2256 mView.mPrivateFlags |= View.PFLAG_DRAWN; 2257 2258 if (DEBUG_DRAW) { 2259 Context cxt = mView.getContext(); 2260 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() + 2261 ", metrics=" + cxt.getResources().getDisplayMetrics() + 2262 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo()); 2263 } 2264 try { 2265 canvas.translate(0, -yoff); 2266 if (mTranslator != null) { 2267 mTranslator.translateCanvas(canvas); 2268 } 2269 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0); 2270 attachInfo.mSetIgnoreDirtyState = false; 2271 2272 mView.draw(canvas); 2273 2274 drawAccessibilityFocusedDrawableIfNeeded(canvas); 2275 } finally { 2276 if (!attachInfo.mSetIgnoreDirtyState) { 2277 // Only clear the flag if it was not set during the mView.draw() call 2278 attachInfo.mIgnoreDirtyState = false; 2279 } 2280 } 2281 } finally { 2282 try { 2283 surface.unlockCanvasAndPost(canvas); 2284 } catch (IllegalArgumentException e) { 2285 Log.e(TAG, "Could not unlock surface", e); 2286 mLayoutRequested = true; // ask wm for a new surface next time. 2287 //noinspection ReturnInsideFinallyBlock 2288 return false; 2289 } 2290 2291 if (LOCAL_LOGV) { 2292 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost"); 2293 } 2294 } 2295 return true; 2296 } 2297 2298 /** 2299 * We want to draw a highlight around the current accessibility focused. 2300 * Since adding a style for all possible view is not a viable option we 2301 * have this specialized drawing method. 2302 * 2303 * Note: We are doing this here to be able to draw the highlight for 2304 * virtual views in addition to real ones. 2305 * 2306 * @param canvas The canvas on which to draw. 2307 */ 2308 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) { 2309 AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext); 2310 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 2311 return; 2312 } 2313 if (mAccessibilityFocusedHost == null || mAccessibilityFocusedHost.mAttachInfo == null) { 2314 return; 2315 } 2316 Drawable drawable = getAccessibilityFocusedDrawable(); 2317 if (drawable == null) { 2318 return; 2319 } 2320 AccessibilityNodeProvider provider = 2321 mAccessibilityFocusedHost.getAccessibilityNodeProvider(); 2322 Rect bounds = mView.mAttachInfo.mTmpInvalRect; 2323 if (provider == null) { 2324 mAccessibilityFocusedHost.getDrawingRect(bounds); 2325 if (mView instanceof ViewGroup) { 2326 ViewGroup viewGroup = (ViewGroup) mView; 2327 viewGroup.offsetDescendantRectToMyCoords(mAccessibilityFocusedHost, bounds); 2328 } 2329 } else { 2330 if (mAccessibilityFocusedVirtualView == null) { 2331 return; 2332 } 2333 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds); 2334 bounds.offset(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop); 2335 } 2336 drawable.setBounds(bounds); 2337 drawable.draw(canvas); 2338 } 2339 2340 private Drawable getAccessibilityFocusedDrawable() { 2341 if (mAttachInfo != null) { 2342 // Lazily load the accessibility focus drawable. 2343 if (mAttachInfo.mAccessibilityFocusDrawable == null) { 2344 TypedValue value = new TypedValue(); 2345 final boolean resolved = mView.mContext.getTheme().resolveAttribute( 2346 R.attr.accessibilityFocusedDrawable, value, true); 2347 if (resolved) { 2348 mAttachInfo.mAccessibilityFocusDrawable = 2349 mView.mContext.getResources().getDrawable(value.resourceId); 2350 } 2351 } 2352 return mAttachInfo.mAccessibilityFocusDrawable; 2353 } 2354 return null; 2355 } 2356 2357 void invalidateDisplayLists() { 2358 final ArrayList<DisplayList> displayLists = mDisplayLists; 2359 final int count = displayLists.size(); 2360 2361 for (int i = 0; i < count; i++) { 2362 final DisplayList displayList = displayLists.get(i); 2363 displayList.invalidate(); 2364 displayList.clear(); 2365 } 2366 2367 displayLists.clear(); 2368 } 2369 2370 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) { 2371 final View.AttachInfo attachInfo = mAttachInfo; 2372 final Rect ci = attachInfo.mContentInsets; 2373 final Rect vi = attachInfo.mVisibleInsets; 2374 int scrollY = 0; 2375 boolean handled = false; 2376 2377 if (vi.left > ci.left || vi.top > ci.top 2378 || vi.right > ci.right || vi.bottom > ci.bottom) { 2379 // We'll assume that we aren't going to change the scroll 2380 // offset, since we want to avoid that unless it is actually 2381 // going to make the focus visible... otherwise we scroll 2382 // all over the place. 2383 scrollY = mScrollY; 2384 // We can be called for two different situations: during a draw, 2385 // to update the scroll position if the focus has changed (in which 2386 // case 'rectangle' is null), or in response to a 2387 // requestChildRectangleOnScreen() call (in which case 'rectangle' 2388 // is non-null and we just want to scroll to whatever that 2389 // rectangle is). 2390 View focus = mRealFocusedView; 2391 2392 // When in touch mode, focus points to the previously focused view, 2393 // which may have been removed from the view hierarchy. The following 2394 // line checks whether the view is still in our hierarchy. 2395 if (focus == null || focus.mAttachInfo != mAttachInfo) { 2396 mRealFocusedView = null; 2397 return false; 2398 } 2399 2400 if (focus != mLastScrolledFocus) { 2401 // If the focus has changed, then ignore any requests to scroll 2402 // to a rectangle; first we want to make sure the entire focus 2403 // view is visible. 2404 rectangle = null; 2405 } 2406 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus 2407 + " rectangle=" + rectangle + " ci=" + ci 2408 + " vi=" + vi); 2409 if (focus == mLastScrolledFocus && !mScrollMayChange 2410 && rectangle == null) { 2411 // Optimization: if the focus hasn't changed since last 2412 // time, and no layout has happened, then just leave things 2413 // as they are. 2414 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y=" 2415 + mScrollY + " vi=" + vi.toShortString()); 2416 } else if (focus != null) { 2417 // We need to determine if the currently focused view is 2418 // within the visible part of the window and, if not, apply 2419 // a pan so it can be seen. 2420 mLastScrolledFocus = focus; 2421 mScrollMayChange = false; 2422 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?"); 2423 // Try to find the rectangle from the focus view. 2424 if (focus.getGlobalVisibleRect(mVisRect, null)) { 2425 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w=" 2426 + mView.getWidth() + " h=" + mView.getHeight() 2427 + " ci=" + ci.toShortString() 2428 + " vi=" + vi.toShortString()); 2429 if (rectangle == null) { 2430 focus.getFocusedRect(mTempRect); 2431 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus 2432 + ": focusRect=" + mTempRect.toShortString()); 2433 if (mView instanceof ViewGroup) { 2434 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 2435 focus, mTempRect); 2436 } 2437 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2438 "Focus in window: focusRect=" 2439 + mTempRect.toShortString() 2440 + " visRect=" + mVisRect.toShortString()); 2441 } else { 2442 mTempRect.set(rectangle); 2443 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2444 "Request scroll to rect: " 2445 + mTempRect.toShortString() 2446 + " visRect=" + mVisRect.toShortString()); 2447 } 2448 if (mTempRect.intersect(mVisRect)) { 2449 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2450 "Focus window visible rect: " 2451 + mTempRect.toShortString()); 2452 if (mTempRect.height() > 2453 (mView.getHeight()-vi.top-vi.bottom)) { 2454 // If the focus simply is not going to fit, then 2455 // best is probably just to leave things as-is. 2456 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2457 "Too tall; leaving scrollY=" + scrollY); 2458 } else if ((mTempRect.top-scrollY) < vi.top) { 2459 scrollY -= vi.top - (mTempRect.top-scrollY); 2460 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2461 "Top covered; scrollY=" + scrollY); 2462 } else if ((mTempRect.bottom-scrollY) 2463 > (mView.getHeight()-vi.bottom)) { 2464 scrollY += (mTempRect.bottom-scrollY) 2465 - (mView.getHeight()-vi.bottom); 2466 if (DEBUG_INPUT_RESIZE) Log.v(TAG, 2467 "Bottom covered; scrollY=" + scrollY); 2468 } 2469 handled = true; 2470 } 2471 } 2472 } 2473 } 2474 2475 if (scrollY != mScrollY) { 2476 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old=" 2477 + mScrollY + " , new=" + scrollY); 2478 if (!immediate && mResizeBuffer == null) { 2479 if (mScroller == null) { 2480 mScroller = new Scroller(mView.getContext()); 2481 } 2482 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY); 2483 } else if (mScroller != null) { 2484 mScroller.abortAnimation(); 2485 } 2486 mScrollY = scrollY; 2487 } 2488 2489 return handled; 2490 } 2491 2492 /** 2493 * @hide 2494 */ 2495 public View getAccessibilityFocusedHost() { 2496 return mAccessibilityFocusedHost; 2497 } 2498 2499 /** 2500 * @hide 2501 */ 2502 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() { 2503 return mAccessibilityFocusedVirtualView; 2504 } 2505 2506 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) { 2507 // If we have a virtual view with accessibility focus we need 2508 // to clear the focus and invalidate the virtual view bounds. 2509 if (mAccessibilityFocusedVirtualView != null) { 2510 2511 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView; 2512 View focusHost = mAccessibilityFocusedHost; 2513 focusHost.clearAccessibilityFocusNoCallbacks(); 2514 2515 // Wipe the state of the current accessibility focus since 2516 // the call into the provider to clear accessibility focus 2517 // will fire an accessibility event which will end up calling 2518 // this method and we want to have clean state when this 2519 // invocation happens. 2520 mAccessibilityFocusedHost = null; 2521 mAccessibilityFocusedVirtualView = null; 2522 2523 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider(); 2524 if (provider != null) { 2525 // Invalidate the area of the cleared accessibility focus. 2526 focusNode.getBoundsInParent(mTempRect); 2527 focusHost.invalidate(mTempRect); 2528 // Clear accessibility focus in the virtual node. 2529 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId( 2530 focusNode.getSourceNodeId()); 2531 provider.performAction(virtualNodeId, 2532 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null); 2533 } 2534 focusNode.recycle(); 2535 } 2536 if (mAccessibilityFocusedHost != null) { 2537 // Clear accessibility focus in the view. 2538 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(); 2539 } 2540 2541 // Set the new focus host and node. 2542 mAccessibilityFocusedHost = view; 2543 mAccessibilityFocusedVirtualView = node; 2544 } 2545 2546 public void requestChildFocus(View child, View focused) { 2547 checkThread(); 2548 2549 if (DEBUG_INPUT_RESIZE) { 2550 Log.v(TAG, "Request child focus: focus now " + focused); 2551 } 2552 2553 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, focused); 2554 scheduleTraversals(); 2555 2556 mFocusedView = mRealFocusedView = focused; 2557 } 2558 2559 public void clearChildFocus(View child) { 2560 checkThread(); 2561 2562 if (DEBUG_INPUT_RESIZE) { 2563 Log.v(TAG, "Clearing child focus"); 2564 } 2565 2566 mOldFocusedView = mFocusedView; 2567 2568 // Invoke the listener only if there is no view to take focus 2569 if (focusSearch(null, View.FOCUS_FORWARD) == null) { 2570 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mOldFocusedView, null); 2571 } 2572 2573 mFocusedView = mRealFocusedView = null; 2574 } 2575 2576 @Override 2577 public ViewParent getParentForAccessibility() { 2578 return null; 2579 } 2580 2581 public void focusableViewAvailable(View v) { 2582 checkThread(); 2583 if (mView != null) { 2584 if (!mView.hasFocus()) { 2585 v.requestFocus(); 2586 } else { 2587 // the one case where will transfer focus away from the current one 2588 // is if the current view is a view group that prefers to give focus 2589 // to its children first AND the view is a descendant of it. 2590 mFocusedView = mView.findFocus(); 2591 boolean descendantsHaveDibsOnFocus = 2592 (mFocusedView instanceof ViewGroup) && 2593 (((ViewGroup) mFocusedView).getDescendantFocusability() == 2594 ViewGroup.FOCUS_AFTER_DESCENDANTS); 2595 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) { 2596 // If a view gets the focus, the listener will be invoked from requestChildFocus() 2597 v.requestFocus(); 2598 } 2599 } 2600 } 2601 } 2602 2603 public void recomputeViewAttributes(View child) { 2604 checkThread(); 2605 if (mView == child) { 2606 mAttachInfo.mRecomputeGlobalAttributes = true; 2607 if (!mWillDrawSoon) { 2608 scheduleTraversals(); 2609 } 2610 } 2611 } 2612 2613 void dispatchDetachedFromWindow() { 2614 if (mView != null && mView.mAttachInfo != null) { 2615 if (mAttachInfo.mHardwareRenderer != null && 2616 mAttachInfo.mHardwareRenderer.isEnabled()) { 2617 mAttachInfo.mHardwareRenderer.validate(); 2618 } 2619 mView.dispatchDetachedFromWindow(); 2620 } 2621 2622 mAccessibilityInteractionConnectionManager.ensureNoConnection(); 2623 mAccessibilityManager.removeAccessibilityStateChangeListener( 2624 mAccessibilityInteractionConnectionManager); 2625 removeSendWindowContentChangedCallback(); 2626 2627 destroyHardwareRenderer(); 2628 2629 setAccessibilityFocus(null, null); 2630 2631 mView = null; 2632 mAttachInfo.mRootView = null; 2633 mAttachInfo.mSurface = null; 2634 2635 mSurface.release(); 2636 2637 if (mInputQueueCallback != null && mInputQueue != null) { 2638 mInputQueueCallback.onInputQueueDestroyed(mInputQueue); 2639 mInputQueueCallback = null; 2640 mInputQueue = null; 2641 } else if (mInputEventReceiver != null) { 2642 mInputEventReceiver.dispose(); 2643 mInputEventReceiver = null; 2644 } 2645 try { 2646 mWindowSession.remove(mWindow); 2647 } catch (RemoteException e) { 2648 } 2649 2650 // Dispose the input channel after removing the window so the Window Manager 2651 // doesn't interpret the input channel being closed as an abnormal termination. 2652 if (mInputChannel != null) { 2653 mInputChannel.dispose(); 2654 mInputChannel = null; 2655 } 2656 2657 unscheduleTraversals(); 2658 } 2659 2660 void updateConfiguration(Configuration config, boolean force) { 2661 if (DEBUG_CONFIGURATION) Log.v(TAG, 2662 "Applying new config to window " 2663 + mWindowAttributes.getTitle() 2664 + ": " + config); 2665 2666 CompatibilityInfo ci = mCompatibilityInfo.getIfNeeded(); 2667 if (ci != null) { 2668 config = new Configuration(config); 2669 ci.applyToConfiguration(mNoncompatDensity, config); 2670 } 2671 2672 synchronized (sConfigCallbacks) { 2673 for (int i=sConfigCallbacks.size()-1; i>=0; i--) { 2674 sConfigCallbacks.get(i).onConfigurationChanged(config); 2675 } 2676 } 2677 if (mView != null) { 2678 // At this point the resources have been updated to 2679 // have the most recent config, whatever that is. Use 2680 // the one in them which may be newer. 2681 config = mView.getResources().getConfiguration(); 2682 if (force || mLastConfiguration.diff(config) != 0) { 2683 mLastConfiguration.setTo(config); 2684 mView.dispatchConfigurationChanged(config); 2685 } 2686 } 2687 } 2688 2689 /** 2690 * Return true if child is an ancestor of parent, (or equal to the parent). 2691 */ 2692 public static boolean isViewDescendantOf(View child, View parent) { 2693 if (child == parent) { 2694 return true; 2695 } 2696 2697 final ViewParent theParent = child.getParent(); 2698 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); 2699 } 2700 2701 private static void forceLayout(View view) { 2702 view.forceLayout(); 2703 if (view instanceof ViewGroup) { 2704 ViewGroup group = (ViewGroup) view; 2705 final int count = group.getChildCount(); 2706 for (int i = 0; i < count; i++) { 2707 forceLayout(group.getChildAt(i)); 2708 } 2709 } 2710 } 2711 2712 private final static int MSG_INVALIDATE = 1; 2713 private final static int MSG_INVALIDATE_RECT = 2; 2714 private final static int MSG_DIE = 3; 2715 private final static int MSG_RESIZED = 4; 2716 private final static int MSG_RESIZED_REPORT = 5; 2717 private final static int MSG_WINDOW_FOCUS_CHANGED = 6; 2718 private final static int MSG_DISPATCH_KEY = 7; 2719 private final static int MSG_DISPATCH_APP_VISIBILITY = 8; 2720 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9; 2721 private final static int MSG_IME_FINISHED_EVENT = 10; 2722 private final static int MSG_DISPATCH_KEY_FROM_IME = 11; 2723 private final static int MSG_FINISH_INPUT_CONNECTION = 12; 2724 private final static int MSG_CHECK_FOCUS = 13; 2725 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14; 2726 private final static int MSG_DISPATCH_DRAG_EVENT = 15; 2727 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16; 2728 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17; 2729 private final static int MSG_UPDATE_CONFIGURATION = 18; 2730 private final static int MSG_PROCESS_INPUT_EVENTS = 19; 2731 private final static int MSG_DISPATCH_SCREEN_STATE = 20; 2732 private final static int MSG_INVALIDATE_DISPLAY_LIST = 21; 2733 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 22; 2734 private final static int MSG_DISPATCH_DONE_ANIMATING = 23; 2735 private final static int MSG_INVALIDATE_WORLD = 24; 2736 private final static int MSG_WINDOW_MOVED = 25; 2737 2738 final class ViewRootHandler extends Handler { 2739 @Override 2740 public String getMessageName(Message message) { 2741 switch (message.what) { 2742 case MSG_INVALIDATE: 2743 return "MSG_INVALIDATE"; 2744 case MSG_INVALIDATE_RECT: 2745 return "MSG_INVALIDATE_RECT"; 2746 case MSG_DIE: 2747 return "MSG_DIE"; 2748 case MSG_RESIZED: 2749 return "MSG_RESIZED"; 2750 case MSG_RESIZED_REPORT: 2751 return "MSG_RESIZED_REPORT"; 2752 case MSG_WINDOW_FOCUS_CHANGED: 2753 return "MSG_WINDOW_FOCUS_CHANGED"; 2754 case MSG_DISPATCH_KEY: 2755 return "MSG_DISPATCH_KEY"; 2756 case MSG_DISPATCH_APP_VISIBILITY: 2757 return "MSG_DISPATCH_APP_VISIBILITY"; 2758 case MSG_DISPATCH_GET_NEW_SURFACE: 2759 return "MSG_DISPATCH_GET_NEW_SURFACE"; 2760 case MSG_IME_FINISHED_EVENT: 2761 return "MSG_IME_FINISHED_EVENT"; 2762 case MSG_DISPATCH_KEY_FROM_IME: 2763 return "MSG_DISPATCH_KEY_FROM_IME"; 2764 case MSG_FINISH_INPUT_CONNECTION: 2765 return "MSG_FINISH_INPUT_CONNECTION"; 2766 case MSG_CHECK_FOCUS: 2767 return "MSG_CHECK_FOCUS"; 2768 case MSG_CLOSE_SYSTEM_DIALOGS: 2769 return "MSG_CLOSE_SYSTEM_DIALOGS"; 2770 case MSG_DISPATCH_DRAG_EVENT: 2771 return "MSG_DISPATCH_DRAG_EVENT"; 2772 case MSG_DISPATCH_DRAG_LOCATION_EVENT: 2773 return "MSG_DISPATCH_DRAG_LOCATION_EVENT"; 2774 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: 2775 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY"; 2776 case MSG_UPDATE_CONFIGURATION: 2777 return "MSG_UPDATE_CONFIGURATION"; 2778 case MSG_PROCESS_INPUT_EVENTS: 2779 return "MSG_PROCESS_INPUT_EVENTS"; 2780 case MSG_DISPATCH_SCREEN_STATE: 2781 return "MSG_DISPATCH_SCREEN_STATE"; 2782 case MSG_INVALIDATE_DISPLAY_LIST: 2783 return "MSG_INVALIDATE_DISPLAY_LIST"; 2784 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: 2785 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST"; 2786 case MSG_DISPATCH_DONE_ANIMATING: 2787 return "MSG_DISPATCH_DONE_ANIMATING"; 2788 case MSG_WINDOW_MOVED: 2789 return "MSG_WINDOW_MOVED"; 2790 } 2791 return super.getMessageName(message); 2792 } 2793 2794 @Override 2795 public void handleMessage(Message msg) { 2796 switch (msg.what) { 2797 case MSG_INVALIDATE: 2798 ((View) msg.obj).invalidate(); 2799 break; 2800 case MSG_INVALIDATE_RECT: 2801 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; 2802 info.target.invalidate(info.left, info.top, info.right, info.bottom); 2803 info.release(); 2804 break; 2805 case MSG_IME_FINISHED_EVENT: 2806 handleImeFinishedEvent(msg.arg1, msg.arg2 != 0); 2807 break; 2808 case MSG_PROCESS_INPUT_EVENTS: 2809 mProcessInputEventsScheduled = false; 2810 doProcessInputEvents(); 2811 break; 2812 case MSG_DISPATCH_APP_VISIBILITY: 2813 handleAppVisibility(msg.arg1 != 0); 2814 break; 2815 case MSG_DISPATCH_GET_NEW_SURFACE: 2816 handleGetNewSurface(); 2817 break; 2818 case MSG_RESIZED: { 2819 // Recycled in the fall through... 2820 SomeArgs args = (SomeArgs) msg.obj; 2821 if (mWinFrame.equals((Rect) args.arg1) 2822 && mPendingContentInsets.equals((Rect) args.arg2) 2823 && mPendingVisibleInsets.equals((Rect) args.arg3) 2824 && ((Configuration) args.arg4 == null)) { 2825 break; 2826 } 2827 } // fall through... 2828 case MSG_RESIZED_REPORT: 2829 if (mAdded) { 2830 SomeArgs args = (SomeArgs) msg.obj; 2831 2832 Configuration config = (Configuration) args.arg4; 2833 if (config != null) { 2834 updateConfiguration(config, false); 2835 } 2836 2837 mWinFrame.set((Rect) args.arg1); 2838 mPendingContentInsets.set((Rect) args.arg2); 2839 mPendingVisibleInsets.set((Rect) args.arg3); 2840 2841 args.recycle(); 2842 2843 if (msg.what == MSG_RESIZED_REPORT) { 2844 mReportNextDraw = true; 2845 } 2846 2847 if (mView != null) { 2848 forceLayout(mView); 2849 } 2850 2851 requestLayout(); 2852 } 2853 break; 2854 case MSG_WINDOW_MOVED: 2855 if (mAdded) { 2856 final int w = mWinFrame.width(); 2857 final int h = mWinFrame.height(); 2858 final int l = msg.arg1; 2859 final int t = msg.arg2; 2860 mWinFrame.left = l; 2861 mWinFrame.right = l + w; 2862 mWinFrame.top = t; 2863 mWinFrame.bottom = t + h; 2864 2865 if (mView != null) { 2866 forceLayout(mView); 2867 } 2868 requestLayout(); 2869 } 2870 break; 2871 case MSG_WINDOW_FOCUS_CHANGED: { 2872 if (mAdded) { 2873 boolean hasWindowFocus = msg.arg1 != 0; 2874 mAttachInfo.mHasWindowFocus = hasWindowFocus; 2875 2876 profileRendering(hasWindowFocus); 2877 2878 if (hasWindowFocus) { 2879 boolean inTouchMode = msg.arg2 != 0; 2880 ensureTouchModeLocally(inTouchMode); 2881 2882 if (mAttachInfo.mHardwareRenderer != null && 2883 mSurface != null && mSurface.isValid()) { 2884 mFullRedrawNeeded = true; 2885 try { 2886 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2887 mHolder.getSurface()); 2888 } catch (Surface.OutOfResourcesException e) { 2889 Log.e(TAG, "OutOfResourcesException locking surface", e); 2890 try { 2891 if (!mWindowSession.outOfMemory(mWindow)) { 2892 Slog.w(TAG, "No processes killed for memory; killing self"); 2893 Process.killProcess(Process.myPid()); 2894 } 2895 } catch (RemoteException ex) { 2896 } 2897 // Retry in a bit. 2898 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 2899 return; 2900 } 2901 } 2902 } 2903 2904 mLastWasImTarget = WindowManager.LayoutParams 2905 .mayUseInputMethod(mWindowAttributes.flags); 2906 2907 InputMethodManager imm = InputMethodManager.peekInstance(); 2908 if (mView != null) { 2909 if (hasWindowFocus && imm != null && mLastWasImTarget) { 2910 imm.startGettingWindowFocus(mView); 2911 } 2912 mAttachInfo.mKeyDispatchState.reset(); 2913 mView.dispatchWindowFocusChanged(hasWindowFocus); 2914 } 2915 2916 // Note: must be done after the focus change callbacks, 2917 // so all of the view state is set up correctly. 2918 if (hasWindowFocus) { 2919 if (imm != null && mLastWasImTarget) { 2920 imm.onWindowFocus(mView, mView.findFocus(), 2921 mWindowAttributes.softInputMode, 2922 !mHasHadWindowFocus, mWindowAttributes.flags); 2923 } 2924 // Clear the forward bit. We can just do this directly, since 2925 // the window manager doesn't care about it. 2926 mWindowAttributes.softInputMode &= 2927 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2928 ((WindowManager.LayoutParams)mView.getLayoutParams()) 2929 .softInputMode &= 2930 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2931 mHasHadWindowFocus = true; 2932 } 2933 2934 setAccessibilityFocus(null, null); 2935 2936 if (mView != null && mAccessibilityManager.isEnabled()) { 2937 if (hasWindowFocus) { 2938 mView.sendAccessibilityEvent( 2939 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 2940 } 2941 } 2942 } 2943 } break; 2944 case MSG_DIE: 2945 doDie(); 2946 break; 2947 case MSG_DISPATCH_KEY: { 2948 KeyEvent event = (KeyEvent)msg.obj; 2949 enqueueInputEvent(event, null, 0, true); 2950 } break; 2951 case MSG_DISPATCH_KEY_FROM_IME: { 2952 if (LOCAL_LOGV) Log.v( 2953 TAG, "Dispatching key " 2954 + msg.obj + " from IME to " + mView); 2955 KeyEvent event = (KeyEvent)msg.obj; 2956 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 2957 // The IME is trying to say this event is from the 2958 // system! Bad bad bad! 2959 //noinspection UnusedAssignment 2960 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 2961 } 2962 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 2963 } break; 2964 case MSG_FINISH_INPUT_CONNECTION: { 2965 InputMethodManager imm = InputMethodManager.peekInstance(); 2966 if (imm != null) { 2967 imm.reportFinishInputConnection((InputConnection)msg.obj); 2968 } 2969 } break; 2970 case MSG_CHECK_FOCUS: { 2971 InputMethodManager imm = InputMethodManager.peekInstance(); 2972 if (imm != null) { 2973 imm.checkFocus(); 2974 } 2975 } break; 2976 case MSG_CLOSE_SYSTEM_DIALOGS: { 2977 if (mView != null) { 2978 mView.onCloseSystemDialogs((String)msg.obj); 2979 } 2980 } break; 2981 case MSG_DISPATCH_DRAG_EVENT: 2982 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 2983 DragEvent event = (DragEvent)msg.obj; 2984 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 2985 handleDragEvent(event); 2986 } break; 2987 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 2988 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj); 2989 } break; 2990 case MSG_UPDATE_CONFIGURATION: { 2991 Configuration config = (Configuration)msg.obj; 2992 if (config.isOtherSeqNewer(mLastConfiguration)) { 2993 config = mLastConfiguration; 2994 } 2995 updateConfiguration(config, false); 2996 } break; 2997 case MSG_DISPATCH_SCREEN_STATE: { 2998 if (mView != null) { 2999 handleScreenStateChange(msg.arg1 == 1); 3000 } 3001 } break; 3002 case MSG_INVALIDATE_DISPLAY_LIST: { 3003 invalidateDisplayLists(); 3004 } break; 3005 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3006 setAccessibilityFocus(null, null); 3007 } break; 3008 case MSG_DISPATCH_DONE_ANIMATING: { 3009 handleDispatchDoneAnimating(); 3010 } break; 3011 case MSG_INVALIDATE_WORLD: { 3012 if (mView != null) { 3013 invalidateWorld(mView); 3014 } 3015 } break; 3016 } 3017 } 3018 } 3019 3020 final ViewRootHandler mHandler = new ViewRootHandler(); 3021 3022 /** 3023 * Something in the current window tells us we need to change the touch mode. For 3024 * example, we are not in touch mode, and the user touches the screen. 3025 * 3026 * If the touch mode has changed, tell the window manager, and handle it locally. 3027 * 3028 * @param inTouchMode Whether we want to be in touch mode. 3029 * @return True if the touch mode changed and focus changed was changed as a result 3030 */ 3031 boolean ensureTouchMode(boolean inTouchMode) { 3032 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3033 + "touch mode is " + mAttachInfo.mInTouchMode); 3034 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3035 3036 // tell the window manager 3037 try { 3038 mWindowSession.setInTouchMode(inTouchMode); 3039 } catch (RemoteException e) { 3040 throw new RuntimeException(e); 3041 } 3042 3043 // handle the change 3044 return ensureTouchModeLocally(inTouchMode); 3045 } 3046 3047 /** 3048 * Ensure that the touch mode for this window is set, and if it is changing, 3049 * take the appropriate action. 3050 * @param inTouchMode Whether we want to be in touch mode. 3051 * @return True if the touch mode changed and focus changed was changed as a result 3052 */ 3053 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3054 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3055 + "touch mode is " + mAttachInfo.mInTouchMode); 3056 3057 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3058 3059 mAttachInfo.mInTouchMode = inTouchMode; 3060 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3061 3062 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3063 } 3064 3065 private boolean enterTouchMode() { 3066 if (mView != null) { 3067 if (mView.hasFocus()) { 3068 // note: not relying on mFocusedView here because this could 3069 // be when the window is first being added, and mFocused isn't 3070 // set yet. 3071 final View focused = mView.findFocus(); 3072 if (focused != null && !focused.isFocusableInTouchMode()) { 3073 3074 final ViewGroup ancestorToTakeFocus = 3075 findAncestorToTakeFocusInTouchMode(focused); 3076 if (ancestorToTakeFocus != null) { 3077 // there is an ancestor that wants focus after its descendants that 3078 // is focusable in touch mode.. give it focus 3079 return ancestorToTakeFocus.requestFocus(); 3080 } else { 3081 // nothing appropriate to have focus in touch mode, clear it out 3082 mView.unFocus(); 3083 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null); 3084 mFocusedView = null; 3085 mOldFocusedView = null; 3086 return true; 3087 } 3088 } 3089 } 3090 } 3091 return false; 3092 } 3093 3094 /** 3095 * Find an ancestor of focused that wants focus after its descendants and is 3096 * focusable in touch mode. 3097 * @param focused The currently focused view. 3098 * @return An appropriate view, or null if no such view exists. 3099 */ 3100 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3101 ViewParent parent = focused.getParent(); 3102 while (parent instanceof ViewGroup) { 3103 final ViewGroup vgParent = (ViewGroup) parent; 3104 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3105 && vgParent.isFocusableInTouchMode()) { 3106 return vgParent; 3107 } 3108 if (vgParent.isRootNamespace()) { 3109 return null; 3110 } else { 3111 parent = vgParent.getParent(); 3112 } 3113 } 3114 return null; 3115 } 3116 3117 private boolean leaveTouchMode() { 3118 if (mView != null) { 3119 if (mView.hasFocus()) { 3120 // i learned the hard way to not trust mFocusedView :) 3121 mFocusedView = mView.findFocus(); 3122 if (!(mFocusedView instanceof ViewGroup)) { 3123 // some view has focus, let it keep it 3124 return false; 3125 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() != 3126 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3127 // some view group has focus, and doesn't prefer its children 3128 // over itself for focus, so let them keep it. 3129 return false; 3130 } 3131 } 3132 3133 // find the best view to give focus to in this brave new non-touch-mode 3134 // world 3135 final View focused = focusSearch(null, View.FOCUS_DOWN); 3136 if (focused != null) { 3137 return focused.requestFocus(View.FOCUS_DOWN); 3138 } 3139 } 3140 return false; 3141 } 3142 3143 private void deliverInputEvent(QueuedInputEvent q) { 3144 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent"); 3145 try { 3146 if (q.mEvent instanceof KeyEvent) { 3147 deliverKeyEvent(q); 3148 } else { 3149 final int source = q.mEvent.getSource(); 3150 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3151 deliverPointerEvent(q); 3152 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3153 deliverTrackballEvent(q); 3154 } else { 3155 deliverGenericMotionEvent(q); 3156 } 3157 } 3158 } finally { 3159 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 3160 } 3161 } 3162 3163 private void deliverPointerEvent(QueuedInputEvent q) { 3164 final MotionEvent event = (MotionEvent)q.mEvent; 3165 final boolean isTouchEvent = event.isTouchEvent(); 3166 if (mInputEventConsistencyVerifier != null) { 3167 if (isTouchEvent) { 3168 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 3169 } else { 3170 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3171 } 3172 } 3173 3174 // If there is no view, then the event will not be handled. 3175 if (mView == null || !mAdded) { 3176 finishInputEvent(q, false); 3177 return; 3178 } 3179 3180 // Translate the pointer event for compatibility, if needed. 3181 if (mTranslator != null) { 3182 mTranslator.translateEventInScreenToAppWindow(event); 3183 } 3184 3185 // Enter touch mode on down or scroll. 3186 final int action = event.getAction(); 3187 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3188 ensureTouchMode(true); 3189 } 3190 3191 // Offset the scroll position. 3192 if (mCurScrollY != 0) { 3193 event.offsetLocation(0, mCurScrollY); 3194 } 3195 if (MEASURE_LATENCY) { 3196 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano()); 3197 } 3198 3199 // Remember the touch position for possible drag-initiation. 3200 if (isTouchEvent) { 3201 mLastTouchPoint.x = event.getRawX(); 3202 mLastTouchPoint.y = event.getRawY(); 3203 } 3204 3205 // Dispatch touch to view hierarchy. 3206 boolean handled = mView.dispatchPointerEvent(event); 3207 if (MEASURE_LATENCY) { 3208 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano()); 3209 } 3210 if (handled) { 3211 finishInputEvent(q, true); 3212 return; 3213 } 3214 3215 // Pointer event was unhandled. 3216 finishInputEvent(q, false); 3217 } 3218 3219 private void deliverTrackballEvent(QueuedInputEvent q) { 3220 final MotionEvent event = (MotionEvent)q.mEvent; 3221 if (mInputEventConsistencyVerifier != null) { 3222 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 3223 } 3224 3225 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3226 if (LOCAL_LOGV) 3227 Log.v(TAG, "Dispatching trackball " + event + " to " + mView); 3228 3229 // Dispatch to the IME before propagating down the view hierarchy. 3230 // The IME will eventually call back into handleImeFinishedEvent. 3231 if (mLastWasImTarget) { 3232 InputMethodManager imm = InputMethodManager.peekInstance(); 3233 if (imm != null) { 3234 final int seq = event.getSequenceNumber(); 3235 if (DEBUG_IMF) 3236 Log.v(TAG, "Sending trackball event to IME: seq=" 3237 + seq + " event=" + event); 3238 imm.dispatchTrackballEvent(mView.getContext(), seq, event, 3239 mInputMethodCallback); 3240 return; 3241 } 3242 } 3243 } 3244 3245 // Not dispatching to IME, continue with post IME actions. 3246 deliverTrackballEventPostIme(q); 3247 } 3248 3249 private void deliverTrackballEventPostIme(QueuedInputEvent q) { 3250 final MotionEvent event = (MotionEvent) q.mEvent; 3251 3252 // If there is no view, then the event will not be handled. 3253 if (mView == null || !mAdded) { 3254 finishInputEvent(q, false); 3255 return; 3256 } 3257 3258 // Deliver the trackball event to the view. 3259 if (mView.dispatchTrackballEvent(event)) { 3260 // If we reach this, we delivered a trackball event to mView and 3261 // mView consumed it. Because we will not translate the trackball 3262 // event into a key event, touch mode will not exit, so we exit 3263 // touch mode here. 3264 ensureTouchMode(false); 3265 3266 finishInputEvent(q, true); 3267 mLastTrackballTime = Integer.MIN_VALUE; 3268 return; 3269 } 3270 3271 // Translate the trackball event into DPAD keys and try to deliver those. 3272 final TrackballAxis x = mTrackballAxisX; 3273 final TrackballAxis y = mTrackballAxisY; 3274 3275 long curTime = SystemClock.uptimeMillis(); 3276 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) { 3277 // It has been too long since the last movement, 3278 // so restart at the beginning. 3279 x.reset(0); 3280 y.reset(0); 3281 mLastTrackballTime = curTime; 3282 } 3283 3284 final int action = event.getAction(); 3285 final int metaState = event.getMetaState(); 3286 switch (action) { 3287 case MotionEvent.ACTION_DOWN: 3288 x.reset(2); 3289 y.reset(2); 3290 enqueueInputEvent(new KeyEvent(curTime, curTime, 3291 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3292 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3293 InputDevice.SOURCE_KEYBOARD)); 3294 break; 3295 case MotionEvent.ACTION_UP: 3296 x.reset(2); 3297 y.reset(2); 3298 enqueueInputEvent(new KeyEvent(curTime, curTime, 3299 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3300 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3301 InputDevice.SOURCE_KEYBOARD)); 3302 break; 3303 } 3304 3305 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step=" 3306 + x.step + " dir=" + x.dir + " acc=" + x.acceleration 3307 + " move=" + event.getX() 3308 + " / Y=" + y.position + " step=" 3309 + y.step + " dir=" + y.dir + " acc=" + y.acceleration 3310 + " move=" + event.getY()); 3311 final float xOff = x.collect(event.getX(), event.getEventTime(), "X"); 3312 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y"); 3313 3314 // Generate DPAD events based on the trackball movement. 3315 // We pick the axis that has moved the most as the direction of 3316 // the DPAD. When we generate DPAD events for one axis, then the 3317 // other axis is reset -- we don't want to perform DPAD jumps due 3318 // to slight movements in the trackball when making major movements 3319 // along the other axis. 3320 int keycode = 0; 3321 int movement = 0; 3322 float accel = 1; 3323 if (xOff > yOff) { 3324 movement = x.generate((2/event.getXPrecision())); 3325 if (movement != 0) { 3326 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3327 : KeyEvent.KEYCODE_DPAD_LEFT; 3328 accel = x.acceleration; 3329 y.reset(2); 3330 } 3331 } else if (yOff > 0) { 3332 movement = y.generate((2/event.getYPrecision())); 3333 if (movement != 0) { 3334 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3335 : KeyEvent.KEYCODE_DPAD_UP; 3336 accel = y.acceleration; 3337 x.reset(2); 3338 } 3339 } 3340 3341 if (keycode != 0) { 3342 if (movement < 0) movement = -movement; 3343 int accelMovement = (int)(movement * accel); 3344 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 3345 + " accelMovement=" + accelMovement 3346 + " accel=" + accel); 3347 if (accelMovement > movement) { 3348 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3349 + keycode); 3350 movement--; 3351 int repeatCount = accelMovement - movement; 3352 enqueueInputEvent(new KeyEvent(curTime, curTime, 3353 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 3354 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3355 InputDevice.SOURCE_KEYBOARD)); 3356 } 3357 while (movement > 0) { 3358 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3359 + keycode); 3360 movement--; 3361 curTime = SystemClock.uptimeMillis(); 3362 enqueueInputEvent(new KeyEvent(curTime, curTime, 3363 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 3364 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3365 InputDevice.SOURCE_KEYBOARD)); 3366 enqueueInputEvent(new KeyEvent(curTime, curTime, 3367 KeyEvent.ACTION_UP, keycode, 0, metaState, 3368 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3369 InputDevice.SOURCE_KEYBOARD)); 3370 } 3371 mLastTrackballTime = curTime; 3372 } 3373 3374 // Unfortunately we can't tell whether the application consumed the keys, so 3375 // we always consider the trackball event handled. 3376 finishInputEvent(q, true); 3377 } 3378 3379 private void deliverGenericMotionEvent(QueuedInputEvent q) { 3380 final MotionEvent event = (MotionEvent)q.mEvent; 3381 if (mInputEventConsistencyVerifier != null) { 3382 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3383 } 3384 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3385 if (LOCAL_LOGV) 3386 Log.v(TAG, "Dispatching generic motion " + event + " to " + mView); 3387 3388 // Dispatch to the IME before propagating down the view hierarchy. 3389 // The IME will eventually call back into handleImeFinishedEvent. 3390 if (mLastWasImTarget) { 3391 InputMethodManager imm = InputMethodManager.peekInstance(); 3392 if (imm != null) { 3393 final int seq = event.getSequenceNumber(); 3394 if (DEBUG_IMF) 3395 Log.v(TAG, "Sending generic motion event to IME: seq=" 3396 + seq + " event=" + event); 3397 imm.dispatchGenericMotionEvent(mView.getContext(), seq, event, 3398 mInputMethodCallback); 3399 return; 3400 } 3401 } 3402 } 3403 3404 // Not dispatching to IME, continue with post IME actions. 3405 deliverGenericMotionEventPostIme(q); 3406 } 3407 3408 private void deliverGenericMotionEventPostIme(QueuedInputEvent q) { 3409 final MotionEvent event = (MotionEvent) q.mEvent; 3410 final int source = event.getSource(); 3411 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0; 3412 final boolean isTouchPad = (source & InputDevice.SOURCE_CLASS_POSITION) != 0; 3413 if (isTouchPad) { 3414 //Convert TouchPad motion into a TrackBall event 3415 mSimulatedTrackball.updateTrackballDirection(this, event); 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