ViewRootImpl.java revision 5971d03f233c52d697e55ee83d8e514adac21527
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.Manifest; 20import android.animation.LayoutTransition; 21import android.app.ActivityManagerNative; 22import android.content.ClipDescription; 23import android.content.ComponentCallbacks; 24import android.content.ComponentCallbacks2; 25import android.content.Context; 26import android.content.pm.ApplicationInfo; 27import android.content.pm.PackageManager; 28import android.content.res.CompatibilityInfo; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.graphics.Canvas; 32import android.graphics.Paint; 33import android.graphics.PixelFormat; 34import android.graphics.Point; 35import android.graphics.PointF; 36import android.graphics.PorterDuff; 37import android.graphics.Rect; 38import android.graphics.Region; 39import android.graphics.drawable.Drawable; 40import android.media.AudioManager; 41import android.os.Binder; 42import android.os.Bundle; 43import android.os.Debug; 44import android.os.Handler; 45import android.os.LatencyTimer; 46import android.os.Looper; 47import android.os.Message; 48import android.os.ParcelFileDescriptor; 49import android.os.PowerManager; 50import android.os.Process; 51import android.os.RemoteException; 52import android.os.SystemClock; 53import android.os.SystemProperties; 54import android.os.Trace; 55import android.util.AndroidRuntimeException; 56import android.util.DisplayMetrics; 57import android.util.Log; 58import android.util.Slog; 59import android.util.TypedValue; 60import android.view.View.AttachInfo; 61import android.view.View.MeasureSpec; 62import android.view.accessibility.AccessibilityEvent; 63import android.view.accessibility.AccessibilityManager; 64import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener; 65import android.view.accessibility.AccessibilityNodeInfo; 66import android.view.accessibility.AccessibilityNodeProvider; 67import android.view.accessibility.IAccessibilityInteractionConnection; 68import android.view.accessibility.IAccessibilityInteractionConnectionCallback; 69import android.view.animation.AccelerateDecelerateInterpolator; 70import android.view.animation.Interpolator; 71import android.view.inputmethod.InputConnection; 72import android.view.inputmethod.InputMethodManager; 73import android.widget.Scroller; 74 75import com.android.internal.R; 76import com.android.internal.os.SomeArgs; 77import com.android.internal.policy.PolicyManager; 78import com.android.internal.view.BaseSurfaceHolder; 79import com.android.internal.view.RootViewSurfaceTaker; 80 81import java.io.IOException; 82import java.io.OutputStream; 83import java.lang.ref.WeakReference; 84import java.util.ArrayList; 85import java.util.HashSet; 86 87/** 88 * The top of a view hierarchy, implementing the needed protocol between View 89 * and the WindowManager. This is for the most part an internal implementation 90 * detail of {@link WindowManagerGlobal}. 91 * 92 * {@hide} 93 */ 94@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"}) 95public final class ViewRootImpl implements ViewParent, 96 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks { 97 private static final String TAG = "ViewRootImpl"; 98 private static final boolean DBG = false; 99 private static final boolean LOCAL_LOGV = false; 100 /** @noinspection PointlessBooleanExpression*/ 101 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV; 102 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV; 103 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV; 104 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV; 105 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV; 106 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV; 107 private static final boolean DEBUG_IMF = false || LOCAL_LOGV; 108 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV; 109 private static final boolean DEBUG_FPS = false; 110 111 private static final boolean USE_RENDER_THREAD = false; 112 113 /** 114 * Set this system property to true to force the view hierarchy to render 115 * at 60 Hz. This can be used to measure the potential framerate. 116 */ 117 private static final String PROPERTY_PROFILE_RENDERING = "viewancestor.profile_rendering"; 118 119 private static final boolean MEASURE_LATENCY = false; 120 private static LatencyTimer lt; 121 122 /** 123 * Maximum time we allow the user to roll the trackball enough to generate 124 * a key event, before resetting the counters. 125 */ 126 static final int MAX_TRACKBALL_DELAY = 250; 127 128 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>(); 129 130 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>(); 131 static boolean sFirstDrawComplete = false; 132 133 static final ArrayList<ComponentCallbacks> sConfigCallbacks 134 = new ArrayList<ComponentCallbacks>(); 135 136 private static boolean sUseRenderThread = false; 137 private static boolean sRenderThreadQueried = false; 138 private static final Object[] sRenderThreadQueryLock = new Object[0]; 139 140 final IWindowSession mWindowSession; 141 final Display mDisplay; 142 143 long mLastTrackballTime = 0; 144 final TrackballAxis mTrackballAxisX = new TrackballAxis(); 145 final TrackballAxis mTrackballAxisY = new TrackballAxis(); 146 147 final SimulatedTrackball mSimulatedTrackball = new SimulatedTrackball(); 148 149 int mLastJoystickXDirection; 150 int mLastJoystickYDirection; 151 int mLastJoystickXKeyCode; 152 int mLastJoystickYKeyCode; 153 154 final int[] mTmpLocation = new int[2]; 155 156 final TypedValue mTmpValue = new TypedValue(); 157 158 final InputMethodCallback mInputMethodCallback; 159 final Thread mThread; 160 161 final WindowLeaked mLocation; 162 163 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams(); 164 165 final W mWindow; 166 167 final int mTargetSdkVersion; 168 169 int mSeq; 170 171 View mView; 172 View mFocusedView; 173 View mRealFocusedView; // this is not set to null in touch mode 174 View mOldFocusedView; 175 176 View mAccessibilityFocusedHost; 177 AccessibilityNodeInfo mAccessibilityFocusedVirtualView; 178 179 int mViewVisibility; 180 boolean mAppVisible = true; 181 int mOrigWindowType = -1; 182 183 // Set to true if the owner of this window is in the stopped state, 184 // so the window should no longer be active. 185 boolean mStopped = false; 186 187 boolean mLastInCompatMode = false; 188 189 SurfaceHolder.Callback2 mSurfaceHolderCallback; 190 BaseSurfaceHolder mSurfaceHolder; 191 boolean mIsCreating; 192 boolean mDrawingAllowed; 193 194 final Region mTransparentRegion; 195 final Region mPreviousTransparentRegion; 196 197 int mWidth; 198 int mHeight; 199 Rect mDirty; 200 final Rect mCurrentDirty = new Rect(); 201 final Rect mPreviousDirty = new Rect(); 202 boolean mIsAnimating; 203 204 CompatibilityInfo.Translator mTranslator; 205 206 final View.AttachInfo mAttachInfo; 207 InputChannel mInputChannel; 208 InputQueue.Callback mInputQueueCallback; 209 InputQueue mInputQueue; 210 FallbackEventHandler mFallbackEventHandler; 211 Choreographer mChoreographer; 212 213 final Rect mTempRect; // used in the transaction to not thrash the heap. 214 final Rect mVisRect; // used to retrieve visible rect of focused view. 215 216 boolean mTraversalScheduled; 217 int mTraversalBarrier; 218 boolean mWillDrawSoon; 219 /** Set to true while in performTraversals for detecting when die(true) is called from internal 220 * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */ 221 boolean mIsInTraversal; 222 boolean mFitSystemWindowsRequested; 223 boolean mLayoutRequested; 224 boolean mFirst; 225 boolean mReportNextDraw; 226 boolean mFullRedrawNeeded; 227 boolean mNewSurfaceNeeded; 228 boolean mHasHadWindowFocus; 229 boolean mLastWasImTarget; 230 boolean mWindowsAnimating; 231 boolean mIsDrawing; 232 int mLastSystemUiVisibility; 233 int mClientWindowLayoutFlags; 234 235 // Pool of queued input events. 236 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10; 237 private QueuedInputEvent mQueuedInputEventPool; 238 private int mQueuedInputEventPoolSize; 239 240 // Input event queue. 241 QueuedInputEvent mFirstPendingInputEvent; 242 QueuedInputEvent mCurrentInputEvent; 243 boolean mProcessInputEventsScheduled; 244 245 boolean mWindowAttributesChanged = false; 246 int mWindowAttributesChangesFlag = 0; 247 248 // These can be accessed by any thread, must be protected with a lock. 249 // Surface can never be reassigned or cleared (use Surface.clear()). 250 private final Surface mSurface = new Surface(); 251 252 boolean mAdded; 253 boolean mAddedTouchMode; 254 255 final CompatibilityInfoHolder mCompatibilityInfo; 256 257 // These are accessed by multiple threads. 258 final Rect mWinFrame; // frame given by window manager. 259 260 final Rect mPendingVisibleInsets = new Rect(); 261 final Rect mPendingContentInsets = new Rect(); 262 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets 263 = new ViewTreeObserver.InternalInsetsInfo(); 264 265 final Rect mFitSystemWindowsInsets = new Rect(); 266 267 final Configuration mLastConfiguration = new Configuration(); 268 final Configuration mPendingConfiguration = new Configuration(); 269 270 boolean mScrollMayChange; 271 int mSoftInputMode; 272 View mLastScrolledFocus; 273 int mScrollY; 274 int mCurScrollY; 275 Scroller mScroller; 276 HardwareLayer mResizeBuffer; 277 long mResizeBufferStartTime; 278 int mResizeBufferDuration; 279 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator(); 280 private ArrayList<LayoutTransition> mPendingTransitions; 281 282 final ViewConfiguration mViewConfiguration; 283 284 /* Drag/drop */ 285 ClipDescription mDragDescription; 286 View mCurrentDragView; 287 volatile Object mLocalDragState; 288 final PointF mDragPoint = new PointF(); 289 final PointF mLastTouchPoint = new PointF(); 290 291 private boolean mProfileRendering; 292 private Thread mRenderProfiler; 293 private volatile boolean mRenderProfilingEnabled; 294 295 // Variables to track frames per second, enabled via DEBUG_FPS flag 296 private long mFpsStartTime = -1; 297 private long mFpsPrevTime = -1; 298 private int mFpsNumFrames; 299 300 private final ArrayList<DisplayList> mDisplayLists = new ArrayList<DisplayList>(24); 301 302 /** 303 * see {@link #playSoundEffect(int)} 304 */ 305 AudioManager mAudioManager; 306 307 final AccessibilityManager mAccessibilityManager; 308 309 AccessibilityInteractionController mAccessibilityInteractionController; 310 311 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager; 312 313 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent; 314 315 HashSet<View> mTempHashSet; 316 317 private final int mDensity; 318 private final int mNoncompatDensity; 319 320 /** 321 * Consistency verifier for debugging purposes. 322 */ 323 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 324 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 325 new InputEventConsistencyVerifier(this, 0) : null; 326 327 static final class SystemUiVisibilityInfo { 328 int seq; 329 int globalVisibility; 330 int localValue; 331 int localChanges; 332 } 333 334 public ViewRootImpl(Context context, Display display) { 335 super(); 336 337 if (MEASURE_LATENCY) { 338 if (lt == null) { 339 lt = new LatencyTimer(100, 1000); 340 } 341 } 342 343 // Initialize the statics when this class is first instantiated. This is 344 // done here instead of in the static block because Zygote does not 345 // allow the spawning of threads. 346 mWindowSession = WindowManagerGlobal.getWindowSession(context.getMainLooper()); 347 mDisplay = display; 348 349 CompatibilityInfoHolder cih = display.getCompatibilityInfo(); 350 mCompatibilityInfo = cih != null ? cih : new CompatibilityInfoHolder(); 351 352 mThread = Thread.currentThread(); 353 mLocation = new WindowLeaked(null); 354 mLocation.fillInStackTrace(); 355 mWidth = -1; 356 mHeight = -1; 357 mDirty = new Rect(); 358 mTempRect = new Rect(); 359 mVisRect = new Rect(); 360 mWinFrame = new Rect(); 361 mWindow = new W(this); 362 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion; 363 mInputMethodCallback = new InputMethodCallback(this); 364 mViewVisibility = View.GONE; 365 mTransparentRegion = new Region(); 366 mPreviousTransparentRegion = new Region(); 367 mFirst = true; // true for the first time the view is added 368 mAdded = false; 369 mAccessibilityManager = AccessibilityManager.getInstance(context); 370 mAccessibilityInteractionConnectionManager = 371 new AccessibilityInteractionConnectionManager(); 372 mAccessibilityManager.addAccessibilityStateChangeListener( 373 mAccessibilityInteractionConnectionManager); 374 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this); 375 mViewConfiguration = ViewConfiguration.get(context); 376 mDensity = context.getResources().getDisplayMetrics().densityDpi; 377 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi; 378 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context); 379 mProfileRendering = Boolean.parseBoolean( 380 SystemProperties.get(PROPERTY_PROFILE_RENDERING, "false")); 381 mChoreographer = Choreographer.getInstance(); 382 383 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 384 mAttachInfo.mScreenOn = powerManager.isScreenOn(); 385 loadSystemProperties(); 386 } 387 388 /** 389 * @return True if the application requests the use of a separate render thread, 390 * false otherwise 391 */ 392 private static boolean isRenderThreadRequested(Context context) { 393 if (USE_RENDER_THREAD) { 394 synchronized (sRenderThreadQueryLock) { 395 if (!sRenderThreadQueried) { 396 final PackageManager packageManager = context.getPackageManager(); 397 final String packageName = context.getApplicationInfo().packageName; 398 try { 399 ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 400 PackageManager.GET_META_DATA); 401 if (applicationInfo.metaData != null) { 402 sUseRenderThread = applicationInfo.metaData.getBoolean( 403 "android.graphics.renderThread", false); 404 } 405 } catch (PackageManager.NameNotFoundException e) { 406 } finally { 407 sRenderThreadQueried = true; 408 } 409 } 410 return sUseRenderThread; 411 } 412 } else { 413 return false; 414 } 415 } 416 417 public static void addFirstDrawHandler(Runnable callback) { 418 synchronized (sFirstDrawHandlers) { 419 if (!sFirstDrawComplete) { 420 sFirstDrawHandlers.add(callback); 421 } 422 } 423 } 424 425 public static void addConfigCallback(ComponentCallbacks callback) { 426 synchronized (sConfigCallbacks) { 427 sConfigCallbacks.add(callback); 428 } 429 } 430 431 // FIXME for perf testing only 432 private boolean mProfile = false; 433 434 /** 435 * Call this to profile the next traversal call. 436 * FIXME for perf testing only. Remove eventually 437 */ 438 public void profile() { 439 mProfile = true; 440 } 441 442 /** 443 * Indicates whether we are in touch mode. Calling this method triggers an IPC 444 * call and should be avoided whenever possible. 445 * 446 * @return True, if the device is in touch mode, false otherwise. 447 * 448 * @hide 449 */ 450 static boolean isInTouchMode() { 451 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession(); 452 if (windowSession != null) { 453 try { 454 return windowSession.getInTouchMode(); 455 } catch (RemoteException e) { 456 } 457 } 458 return false; 459 } 460 461 /** 462 * We have one child 463 */ 464 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) { 465 synchronized (this) { 466 if (mView == null) { 467 mView = view; 468 mFallbackEventHandler.setView(view); 469 mWindowAttributes.copyFrom(attrs); 470 attrs = mWindowAttributes; 471 // Keep track of the actual window flags supplied by the client. 472 mClientWindowLayoutFlags = attrs.flags; 473 474 setAccessibilityFocus(null, null); 475 476 if (view instanceof RootViewSurfaceTaker) { 477 mSurfaceHolderCallback = 478 ((RootViewSurfaceTaker)view).willYouTakeTheSurface(); 479 if (mSurfaceHolderCallback != null) { 480 mSurfaceHolder = new TakenSurfaceHolder(); 481 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN); 482 } 483 } 484 485 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 486 mTranslator = compatibilityInfo.getTranslator(); 487 488 // If the application owns the surface, don't enable hardware acceleration 489 if (mSurfaceHolder == null) { 490 enableHardwareAcceleration(mView.getContext(), attrs); 491 } 492 493 boolean restore = false; 494 if (mTranslator != null) { 495 mSurface.setCompatibilityTranslator(mTranslator); 496 restore = true; 497 attrs.backup(); 498 mTranslator.translateWindowLayout(attrs); 499 } 500 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs); 501 502 if (!compatibilityInfo.supportsScreen()) { 503 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 504 mLastInCompatMode = true; 505 } 506 507 mSoftInputMode = attrs.softInputMode; 508 mWindowAttributesChanged = true; 509 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED; 510 mAttachInfo.mRootView = view; 511 mAttachInfo.mScalingRequired = mTranslator != null; 512 mAttachInfo.mApplicationScale = 513 mTranslator == null ? 1.0f : mTranslator.applicationScale; 514 if (panelParentView != null) { 515 mAttachInfo.mPanelParentWindowToken 516 = panelParentView.getApplicationWindowToken(); 517 } 518 mAdded = true; 519 int res; /* = WindowManagerImpl.ADD_OKAY; */ 520 521 // Schedule the first layout -before- adding to the window 522 // manager, to make sure we do the relayout before receiving 523 // any other events from the system. 524 requestLayout(); 525 if ((mWindowAttributes.inputFeatures 526 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { 527 mInputChannel = new InputChannel(); 528 } 529 try { 530 mOrigWindowType = mWindowAttributes.type; 531 mAttachInfo.mRecomputeGlobalAttributes = true; 532 collectViewAttributes(); 533 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes, 534 getHostVisibility(), mDisplay.getDisplayId(), 535 mAttachInfo.mContentInsets, mInputChannel); 536 } catch (RemoteException e) { 537 mAdded = false; 538 mView = null; 539 mAttachInfo.mRootView = null; 540 mInputChannel = null; 541 mFallbackEventHandler.setView(null); 542 unscheduleTraversals(); 543 setAccessibilityFocus(null, null); 544 throw new RuntimeException("Adding window failed", e); 545 } finally { 546 if (restore) { 547 attrs.restore(); 548 } 549 } 550 551 if (mTranslator != null) { 552 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets); 553 } 554 mPendingContentInsets.set(mAttachInfo.mContentInsets); 555 mPendingVisibleInsets.set(0, 0, 0, 0); 556 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow); 557 if (res < WindowManagerGlobal.ADD_OKAY) { 558 mView = null; 559 mAttachInfo.mRootView = null; 560 mAdded = false; 561 mFallbackEventHandler.setView(null); 562 unscheduleTraversals(); 563 setAccessibilityFocus(null, null); 564 switch (res) { 565 case WindowManagerGlobal.ADD_BAD_APP_TOKEN: 566 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN: 567 throw new WindowManager.BadTokenException( 568 "Unable to add window -- token " + attrs.token 569 + " is not valid; is your activity running?"); 570 case WindowManagerGlobal.ADD_NOT_APP_TOKEN: 571 throw new WindowManager.BadTokenException( 572 "Unable to add window -- token " + attrs.token 573 + " is not for an application"); 574 case WindowManagerGlobal.ADD_APP_EXITING: 575 throw new WindowManager.BadTokenException( 576 "Unable to add window -- app for token " + attrs.token 577 + " is exiting"); 578 case WindowManagerGlobal.ADD_DUPLICATE_ADD: 579 throw new WindowManager.BadTokenException( 580 "Unable to add window -- window " + mWindow 581 + " has already been added"); 582 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED: 583 // Silently ignore -- we would have just removed it 584 // right away, anyway. 585 return; 586 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON: 587 throw new WindowManager.BadTokenException( 588 "Unable to add window " + mWindow + 589 " -- another window of this type already exists"); 590 case WindowManagerGlobal.ADD_PERMISSION_DENIED: 591 throw new WindowManager.BadTokenException( 592 "Unable to add window " + mWindow + 593 " -- permission denied for this window type"); 594 } 595 throw new RuntimeException( 596 "Unable to add window -- unknown error code " + res); 597 } 598 599 if (view instanceof RootViewSurfaceTaker) { 600 mInputQueueCallback = 601 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue(); 602 } 603 if (mInputChannel != null) { 604 if (mInputQueueCallback != null) { 605 mInputQueue = new InputQueue(mInputChannel); 606 mInputQueueCallback.onInputQueueCreated(mInputQueue); 607 } else { 608 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel, 609 Looper.myLooper()); 610 } 611 } 612 613 view.assignParent(this); 614 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0; 615 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0; 616 617 if (mAccessibilityManager.isEnabled()) { 618 mAccessibilityInteractionConnectionManager.ensureConnection(); 619 } 620 621 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 622 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES); 623 } 624 } 625 } 626 } 627 628 void destroyHardwareResources() { 629 if (mAttachInfo.mHardwareRenderer != null) { 630 if (mAttachInfo.mHardwareRenderer.isEnabled()) { 631 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 632 } 633 mAttachInfo.mHardwareRenderer.destroy(false); 634 } 635 } 636 637 void terminateHardwareResources() { 638 if (mAttachInfo.mHardwareRenderer != null) { 639 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView); 640 mAttachInfo.mHardwareRenderer.destroy(false); 641 } 642 } 643 644 void destroyHardwareLayers() { 645 if (mThread != Thread.currentThread()) { 646 if (mAttachInfo.mHardwareRenderer != null && 647 mAttachInfo.mHardwareRenderer.isEnabled()) { 648 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE); 649 } 650 } else { 651 if (mAttachInfo.mHardwareRenderer != null && 652 mAttachInfo.mHardwareRenderer.isEnabled()) { 653 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 654 } 655 } 656 } 657 658 void pushHardwareLayerUpdate(HardwareLayer layer) { 659 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 660 mAttachInfo.mHardwareRenderer.pushLayerUpdate(layer); 661 } 662 } 663 664 public boolean attachFunctor(int functor) { 665 //noinspection SimplifiableIfStatement 666 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 667 return mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor); 668 } 669 return false; 670 } 671 672 public void detachFunctor(int functor) { 673 if (mAttachInfo.mHardwareRenderer != null) { 674 mAttachInfo.mHardwareRenderer.detachFunctor(functor); 675 } 676 } 677 678 private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) { 679 mAttachInfo.mHardwareAccelerated = false; 680 mAttachInfo.mHardwareAccelerationRequested = false; 681 682 // Don't enable hardware acceleration when the application is in compatibility mode 683 if (mTranslator != null) return; 684 685 // Try to enable hardware acceleration if requested 686 final boolean hardwareAccelerated = 687 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0; 688 689 if (hardwareAccelerated) { 690 if (!HardwareRenderer.isAvailable()) { 691 return; 692 } 693 694 // Persistent processes (including the system) should not do 695 // accelerated rendering on low-end devices. In that case, 696 // sRendererDisabled will be set. In addition, the system process 697 // itself should never do accelerated rendering. In that case, both 698 // sRendererDisabled and sSystemRendererDisabled are set. When 699 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED 700 // can be used by code on the system process to escape that and enable 701 // HW accelerated drawing. (This is basically for the lock screen.) 702 703 final boolean fakeHwAccelerated = (attrs.privateFlags & 704 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0; 705 final boolean forceHwAccelerated = (attrs.privateFlags & 706 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0; 707 708 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled 709 && forceHwAccelerated)) { 710 // Don't enable hardware acceleration when we're not on the main thread 711 if (!HardwareRenderer.sSystemRendererDisabled && 712 Looper.getMainLooper() != Looper.myLooper()) { 713 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware " 714 + "acceleration outside of the main thread, aborting"); 715 return; 716 } 717 718 final boolean renderThread = isRenderThreadRequested(context); 719 if (renderThread) { 720 Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated"); 721 } 722 723 if (mAttachInfo.mHardwareRenderer != null) { 724 mAttachInfo.mHardwareRenderer.destroy(true); 725 } 726 727 final boolean translucent = attrs.format != PixelFormat.OPAQUE; 728 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent); 729 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested 730 = mAttachInfo.mHardwareRenderer != null; 731 732 } else if (fakeHwAccelerated) { 733 // The window had wanted to use hardware acceleration, but this 734 // is not allowed in its process. By setting this flag, it can 735 // still render as if it was accelerated. This is basically for 736 // the preview windows the window manager shows for launching 737 // applications, so they will look more like the app being launched. 738 mAttachInfo.mHardwareAccelerationRequested = true; 739 } 740 } 741 } 742 743 public View getView() { 744 return mView; 745 } 746 747 final WindowLeaked getLocation() { 748 return mLocation; 749 } 750 751 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) { 752 synchronized (this) { 753 int oldSoftInputMode = mWindowAttributes.softInputMode; 754 // Keep track of the actual window flags supplied by the client. 755 mClientWindowLayoutFlags = attrs.flags; 756 // preserve compatible window flag if exists. 757 int compatibleWindowFlag = 758 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 759 // transfer over system UI visibility values as they carry current state. 760 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility; 761 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility; 762 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs); 763 mWindowAttributes.flags |= compatibleWindowFlag; 764 765 applyKeepScreenOnFlag(mWindowAttributes); 766 767 if (newView) { 768 mSoftInputMode = attrs.softInputMode; 769 requestLayout(); 770 } 771 // Don't lose the mode we last auto-computed. 772 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 773 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 774 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode 775 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 776 | (oldSoftInputMode 777 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST); 778 } 779 mWindowAttributesChanged = true; 780 scheduleTraversals(); 781 } 782 } 783 784 void handleAppVisibility(boolean visible) { 785 if (mAppVisible != visible) { 786 mAppVisible = visible; 787 scheduleTraversals(); 788 } 789 } 790 791 void handleGetNewSurface() { 792 mNewSurfaceNeeded = true; 793 mFullRedrawNeeded = true; 794 scheduleTraversals(); 795 } 796 797 void handleScreenStateChange(boolean on) { 798 if (on != mAttachInfo.mScreenOn) { 799 mAttachInfo.mScreenOn = on; 800 if (mView != null) { 801 mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF); 802 } 803 if (on) { 804 mFullRedrawNeeded = true; 805 scheduleTraversals(); 806 } 807 } 808 } 809 810 /** 811 * {@inheritDoc} 812 */ 813 public void requestFitSystemWindows() { 814 checkThread(); 815 mFitSystemWindowsRequested = true; 816 scheduleTraversals(); 817 } 818 819 /** 820 * {@inheritDoc} 821 */ 822 public void requestLayout() { 823 checkThread(); 824 mLayoutRequested = true; 825 scheduleTraversals(); 826 } 827 828 /** 829 * {@inheritDoc} 830 */ 831 public boolean isLayoutRequested() { 832 return mLayoutRequested; 833 } 834 835 void invalidate() { 836 mDirty.set(0, 0, mWidth, mHeight); 837 scheduleTraversals(); 838 } 839 840 void invalidateWorld(View view) { 841 view.invalidate(); 842 if (view instanceof ViewGroup) { 843 ViewGroup parent = (ViewGroup) view; 844 for (int i = 0; i < parent.getChildCount(); i++) { 845 invalidateWorld(parent.getChildAt(i)); 846 } 847 } 848 } 849 850 public void invalidateChild(View child, Rect dirty) { 851 invalidateChildInParent(null, dirty); 852 } 853 854 public ViewParent invalidateChildInParent(int[] location, Rect dirty) { 855 checkThread(); 856 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty); 857 858 if (dirty == null) { 859 invalidate(); 860 return null; 861 } else if (dirty.isEmpty()) { 862 return null; 863 } 864 865 if (mCurScrollY != 0 || mTranslator != null) { 866 mTempRect.set(dirty); 867 dirty = mTempRect; 868 if (mCurScrollY != 0) { 869 dirty.offset(0, -mCurScrollY); 870 } 871 if (mTranslator != null) { 872 mTranslator.translateRectInAppWindowToScreen(dirty); 873 } 874 if (mAttachInfo.mScalingRequired) { 875 dirty.inset(-1, -1); 876 } 877 } 878 879 final Rect localDirty = mDirty; 880 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) { 881 mAttachInfo.mSetIgnoreDirtyState = true; 882 mAttachInfo.mIgnoreDirtyState = true; 883 } 884 885 // Add the new dirty rect to the current one 886 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom); 887 // Intersect with the bounds of the window to skip 888 // updates that lie outside of the visible region 889 final float appScale = mAttachInfo.mApplicationScale; 890 localDirty.intersect(0, 0, 891 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 892 893 if (!mWillDrawSoon) { 894 scheduleTraversals(); 895 } 896 897 return null; 898 } 899 900 void setStopped(boolean stopped) { 901 if (mStopped != stopped) { 902 mStopped = stopped; 903 if (!stopped) { 904 scheduleTraversals(); 905 } 906 } 907 } 908 909 public ViewParent getParent() { 910 return null; 911 } 912 913 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 914 if (child != mView) { 915 throw new RuntimeException("child is not mine, honest!"); 916 } 917 // Note: don't apply scroll offset, because we want to know its 918 // visibility in the virtual canvas being given to the view hierarchy. 919 return r.intersect(0, 0, mWidth, mHeight); 920 } 921 922 public void bringChildToFront(View child) { 923 } 924 925 int getHostVisibility() { 926 return mAppVisible ? mView.getVisibility() : View.GONE; 927 } 928 929 void disposeResizeBuffer() { 930 if (mResizeBuffer != null) { 931 mResizeBuffer.destroy(); 932 mResizeBuffer = null; 933 } 934 } 935 936 /** 937 * Add LayoutTransition to the list of transitions to be started in the next traversal. 938 * This list will be cleared after the transitions on the list are start()'ed. These 939 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup 940 * happens during the layout phase of traversal, which we want to complete before any of the 941 * animations are started (because those animations may side-effect properties that layout 942 * depends upon, like the bounding rectangles of the affected views). So we add the transition 943 * to the list and it is started just prior to starting the drawing phase of traversal. 944 * 945 * @param transition The LayoutTransition to be started on the next traversal. 946 * 947 * @hide 948 */ 949 public void requestTransitionStart(LayoutTransition transition) { 950 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) { 951 if (mPendingTransitions == null) { 952 mPendingTransitions = new ArrayList<LayoutTransition>(); 953 } 954 mPendingTransitions.add(transition); 955 } 956 } 957 958 void scheduleTraversals() { 959 if (!mTraversalScheduled) { 960 mTraversalScheduled = true; 961 mTraversalBarrier = mHandler.getLooper().postSyncBarrier(); 962 mChoreographer.postCallback( 963 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 964 scheduleConsumeBatchedInput(); 965 } 966 } 967 968 void unscheduleTraversals() { 969 if (mTraversalScheduled) { 970 mTraversalScheduled = false; 971 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 972 mChoreographer.removeCallbacks( 973 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 974 } 975 } 976 977 void doTraversal() { 978 if (mTraversalScheduled) { 979 mTraversalScheduled = false; 980 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 981 982 if (mProfile) { 983 Debug.startMethodTracing("ViewAncestor"); 984 } 985 986 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals"); 987 try { 988 performTraversals(); 989 } finally { 990 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 991 } 992 993 if (mProfile) { 994 Debug.stopMethodTracing(); 995 mProfile = false; 996 } 997 } 998 } 999 1000 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) { 1001 // Update window's global keep screen on flag: if a view has requested 1002 // that the screen be kept on, then it is always set; otherwise, it is 1003 // set to whatever the client last requested for the global state. 1004 if (mAttachInfo.mKeepScreenOn) { 1005 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 1006 } else { 1007 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) 1008 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1009 } 1010 } 1011 1012 private boolean collectViewAttributes() { 1013 final View.AttachInfo attachInfo = mAttachInfo; 1014 if (attachInfo.mRecomputeGlobalAttributes) { 1015 //Log.i(TAG, "Computing view hierarchy attributes!"); 1016 attachInfo.mRecomputeGlobalAttributes = false; 1017 boolean oldScreenOn = attachInfo.mKeepScreenOn; 1018 attachInfo.mKeepScreenOn = false; 1019 attachInfo.mSystemUiVisibility = 0; 1020 attachInfo.mHasSystemUiListeners = false; 1021 mView.dispatchCollectViewAttributes(attachInfo, 0); 1022 attachInfo.mSystemUiVisibility &= ~attachInfo.mDisabledSystemUiVisibility; 1023 WindowManager.LayoutParams params = mWindowAttributes; 1024 if (attachInfo.mKeepScreenOn != oldScreenOn 1025 || attachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility 1026 || attachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) { 1027 applyKeepScreenOnFlag(params); 1028 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility; 1029 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners; 1030 mView.dispatchWindowSystemUiVisiblityChanged(attachInfo.mSystemUiVisibility); 1031 return true; 1032 } 1033 } 1034 return false; 1035 } 1036 1037 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp, 1038 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) { 1039 int childWidthMeasureSpec; 1040 int childHeightMeasureSpec; 1041 boolean windowSizeMayChange = false; 1042 1043 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG, 1044 "Measuring " + host + " in display " + desiredWindowWidth 1045 + "x" + desiredWindowHeight + "..."); 1046 1047 boolean goodMeasure = false; 1048 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) { 1049 // On large screens, we don't want to allow dialogs to just 1050 // stretch to fill the entire width of the screen to display 1051 // one line of text. First try doing the layout at a smaller 1052 // size to see if it will fit. 1053 final DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1054 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true); 1055 int baseSize = 0; 1056 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) { 1057 baseSize = (int)mTmpValue.getDimension(packageMetrics); 1058 } 1059 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize); 1060 if (baseSize != 0 && desiredWindowWidth > baseSize) { 1061 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1062 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1063 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1064 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1065 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1066 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1067 goodMeasure = true; 1068 } else { 1069 // Didn't fit in that size... try expanding a bit. 1070 baseSize = (baseSize+desiredWindowWidth)/2; 1071 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize=" 1072 + baseSize); 1073 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1074 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1075 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1076 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1077 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1078 if (DEBUG_DIALOG) Log.v(TAG, "Good!"); 1079 goodMeasure = true; 1080 } 1081 } 1082 } 1083 } 1084 1085 if (!goodMeasure) { 1086 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); 1087 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1088 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1089 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) { 1090 windowSizeMayChange = true; 1091 } 1092 } 1093 1094 if (DBG) { 1095 System.out.println("======================================"); 1096 System.out.println("performTraversals -- after measure"); 1097 host.debug(); 1098 } 1099 1100 return windowSizeMayChange; 1101 } 1102 1103 private void performTraversals() { 1104 // cache mView since it is used so much below... 1105 final View host = mView; 1106 1107 if (DBG) { 1108 System.out.println("======================================"); 1109 System.out.println("performTraversals"); 1110 host.debug(); 1111 } 1112 1113 if (host == null || !mAdded) 1114 return; 1115 1116 mIsInTraversal = true; 1117 mWillDrawSoon = true; 1118 boolean windowSizeMayChange = false; 1119 boolean newSurface = false; 1120 boolean surfaceChanged = false; 1121 WindowManager.LayoutParams lp = mWindowAttributes; 1122 1123 int desiredWindowWidth; 1124 int desiredWindowHeight; 1125 1126 final View.AttachInfo attachInfo = mAttachInfo; 1127 1128 final int viewVisibility = getHostVisibility(); 1129 boolean viewVisibilityChanged = mViewVisibility != viewVisibility 1130 || mNewSurfaceNeeded; 1131 1132 WindowManager.LayoutParams params = null; 1133 if (mWindowAttributesChanged) { 1134 mWindowAttributesChanged = false; 1135 surfaceChanged = true; 1136 params = lp; 1137 } 1138 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 1139 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) { 1140 params = lp; 1141 mFullRedrawNeeded = true; 1142 mLayoutRequested = true; 1143 if (mLastInCompatMode) { 1144 params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1145 mLastInCompatMode = false; 1146 } else { 1147 params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1148 mLastInCompatMode = true; 1149 } 1150 } 1151 1152 mWindowAttributesChangesFlag = 0; 1153 1154 Rect frame = mWinFrame; 1155 if (mFirst) { 1156 mFullRedrawNeeded = true; 1157 mLayoutRequested = true; 1158 1159 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1160 // NOTE -- system code, won't try to do compat mode. 1161 Point size = new Point(); 1162 mDisplay.getRealSize(size); 1163 desiredWindowWidth = size.x; 1164 desiredWindowHeight = size.y; 1165 } else { 1166 DisplayMetrics packageMetrics = 1167 mView.getContext().getResources().getDisplayMetrics(); 1168 desiredWindowWidth = packageMetrics.widthPixels; 1169 desiredWindowHeight = packageMetrics.heightPixels; 1170 } 1171 1172 // For the very first time, tell the view hierarchy that it 1173 // is attached to the window. Note that at this point the surface 1174 // object is not initialized to its backing store, but soon it 1175 // will be (assuming the window is visible). 1176 attachInfo.mSurface = mSurface; 1177 // We used to use the following condition to choose 32 bits drawing caches: 1178 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888 1179 // However, windows are now always 32 bits by default, so choose 32 bits 1180 attachInfo.mUse32BitDrawingCache = true; 1181 attachInfo.mHasWindowFocus = false; 1182 attachInfo.mWindowVisibility = viewVisibility; 1183 attachInfo.mRecomputeGlobalAttributes = false; 1184 viewVisibilityChanged = false; 1185 mLastConfiguration.setTo(host.getResources().getConfiguration()); 1186 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1187 host.dispatchAttachedToWindow(attachInfo, 0); 1188 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets); 1189 host.fitSystemWindows(mFitSystemWindowsInsets); 1190 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn); 1191 1192 } else { 1193 desiredWindowWidth = frame.width(); 1194 desiredWindowHeight = frame.height(); 1195 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) { 1196 if (DEBUG_ORIENTATION) Log.v(TAG, 1197 "View " + host + " resized to: " + frame); 1198 mFullRedrawNeeded = true; 1199 mLayoutRequested = true; 1200 windowSizeMayChange = true; 1201 } 1202 } 1203 1204 if (viewVisibilityChanged) { 1205 attachInfo.mWindowVisibility = viewVisibility; 1206 host.dispatchWindowVisibilityChanged(viewVisibility); 1207 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) { 1208 destroyHardwareResources(); 1209 } 1210 if (viewVisibility == View.GONE) { 1211 // After making a window gone, we will count it as being 1212 // shown for the first time the next time it gets focus. 1213 mHasHadWindowFocus = false; 1214 } 1215 } 1216 1217 // Execute enqueued actions on every traversal in case a detached view enqueued an action 1218 getRunQueue().executeActions(attachInfo.mHandler); 1219 1220 boolean insetsChanged = false; 1221 1222 boolean layoutRequested = mLayoutRequested && !mStopped; 1223 if (layoutRequested) { 1224 1225 final Resources res = mView.getContext().getResources(); 1226 1227 if (mFirst) { 1228 // make sure touch mode code executes by setting cached value 1229 // to opposite of the added touch mode. 1230 mAttachInfo.mInTouchMode = !mAddedTouchMode; 1231 ensureTouchModeLocally(mAddedTouchMode); 1232 } else { 1233 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) { 1234 insetsChanged = true; 1235 } 1236 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) { 1237 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1238 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1239 + mAttachInfo.mVisibleInsets); 1240 } 1241 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT 1242 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) { 1243 windowSizeMayChange = true; 1244 1245 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1246 // NOTE -- system code, won't try to do compat mode. 1247 Point size = new Point(); 1248 mDisplay.getRealSize(size); 1249 desiredWindowWidth = size.x; 1250 desiredWindowHeight = size.y; 1251 } else { 1252 DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1253 desiredWindowWidth = packageMetrics.widthPixels; 1254 desiredWindowHeight = packageMetrics.heightPixels; 1255 } 1256 } 1257 } 1258 1259 // Ask host how big it wants to be 1260 windowSizeMayChange |= measureHierarchy(host, lp, res, 1261 desiredWindowWidth, desiredWindowHeight); 1262 } 1263 1264 if (collectViewAttributes()) { 1265 params = lp; 1266 } 1267 if (attachInfo.mForceReportNewAttributes) { 1268 attachInfo.mForceReportNewAttributes = false; 1269 params = lp; 1270 } 1271 1272 if (mFirst || attachInfo.mViewVisibilityChanged) { 1273 attachInfo.mViewVisibilityChanged = false; 1274 int resizeMode = mSoftInputMode & 1275 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST; 1276 // If we are in auto resize mode, then we need to determine 1277 // what mode to use now. 1278 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 1279 final int N = attachInfo.mScrollContainers.size(); 1280 for (int i=0; i<N; i++) { 1281 if (attachInfo.mScrollContainers.get(i).isShown()) { 1282 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; 1283 } 1284 } 1285 if (resizeMode == 0) { 1286 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN; 1287 } 1288 if ((lp.softInputMode & 1289 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) { 1290 lp.softInputMode = (lp.softInputMode & 1291 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) | 1292 resizeMode; 1293 params = lp; 1294 } 1295 } 1296 } 1297 1298 if (params != null && (host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 1299 if (!PixelFormat.formatHasAlpha(params.format)) { 1300 params.format = PixelFormat.TRANSLUCENT; 1301 } 1302 } 1303 1304 if (mFitSystemWindowsRequested) { 1305 mFitSystemWindowsRequested = false; 1306 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets); 1307 host.fitSystemWindows(mFitSystemWindowsInsets); 1308 if (mLayoutRequested) { 1309 // Short-circuit catching a new layout request here, so 1310 // we don't need to go through two layout passes when things 1311 // change due to fitting system windows, which can happen a lot. 1312 windowSizeMayChange |= measureHierarchy(host, lp, 1313 mView.getContext().getResources(), 1314 desiredWindowWidth, desiredWindowHeight); 1315 } 1316 } 1317 1318 if (layoutRequested) { 1319 // Clear this now, so that if anything requests a layout in the 1320 // rest of this function we will catch it and re-run a full 1321 // layout pass. 1322 mLayoutRequested = false; 1323 } 1324 1325 boolean windowShouldResize = layoutRequested && windowSizeMayChange 1326 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) 1327 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT && 1328 frame.width() < desiredWindowWidth && frame.width() != mWidth) 1329 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT && 1330 frame.height() < desiredWindowHeight && frame.height() != mHeight)); 1331 1332 final boolean computesInternalInsets = 1333 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners(); 1334 1335 boolean insetsPending = false; 1336 int relayoutResult = 0; 1337 1338 if (mFirst || windowShouldResize || insetsChanged || 1339 viewVisibilityChanged || params != null) { 1340 1341 if (viewVisibility == View.VISIBLE) { 1342 // If this window is giving internal insets to the window 1343 // manager, and it is being added or changing its visibility, 1344 // then we want to first give the window manager "fake" 1345 // insets to cause it to effectively ignore the content of 1346 // the window during layout. This avoids it briefly causing 1347 // other windows to resize/move based on the raw frame of the 1348 // window, waiting until we can finish laying out this window 1349 // and get back to the window manager with the ultimately 1350 // computed insets. 1351 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged); 1352 } 1353 1354 if (mSurfaceHolder != null) { 1355 mSurfaceHolder.mSurfaceLock.lock(); 1356 mDrawingAllowed = true; 1357 } 1358 1359 boolean hwInitialized = false; 1360 boolean contentInsetsChanged = false; 1361 boolean visibleInsetsChanged; 1362 boolean hadSurface = mSurface.isValid(); 1363 1364 try { 1365 if (DEBUG_LAYOUT) { 1366 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" + 1367 host.getMeasuredHeight() + ", params=" + params); 1368 } 1369 1370 final int surfaceGenerationId = mSurface.getGenerationId(); 1371 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending); 1372 1373 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString() 1374 + " content=" + mPendingContentInsets.toShortString() 1375 + " visible=" + mPendingVisibleInsets.toShortString() 1376 + " surface=" + mSurface); 1377 1378 if (mPendingConfiguration.seq != 0) { 1379 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: " 1380 + mPendingConfiguration); 1381 updateConfiguration(mPendingConfiguration, !mFirst); 1382 mPendingConfiguration.seq = 0; 1383 } 1384 1385 contentInsetsChanged = !mPendingContentInsets.equals( 1386 mAttachInfo.mContentInsets); 1387 visibleInsetsChanged = !mPendingVisibleInsets.equals( 1388 mAttachInfo.mVisibleInsets); 1389 if (contentInsetsChanged) { 1390 if (mWidth > 0 && mHeight > 0 && lp != null && 1391 ((lp.systemUiVisibility|lp.subtreeSystemUiVisibility) 1392 & View.SYSTEM_UI_LAYOUT_FLAGS) == 0 && 1393 mSurface != null && mSurface.isValid() && 1394 !mAttachInfo.mTurnOffWindowResizeAnim && 1395 mAttachInfo.mHardwareRenderer != null && 1396 mAttachInfo.mHardwareRenderer.isEnabled() && 1397 mAttachInfo.mHardwareRenderer.validate() && 1398 lp != null && !PixelFormat.formatHasAlpha(lp.format)) { 1399 1400 disposeResizeBuffer(); 1401 1402 boolean completed = false; 1403 HardwareCanvas hwRendererCanvas = mAttachInfo.mHardwareRenderer.getCanvas(); 1404 HardwareCanvas layerCanvas = null; 1405 try { 1406 if (mResizeBuffer == null) { 1407 mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 1408 mWidth, mHeight, false); 1409 } else if (mResizeBuffer.getWidth() != mWidth || 1410 mResizeBuffer.getHeight() != mHeight) { 1411 mResizeBuffer.resize(mWidth, mHeight); 1412 } 1413 // TODO: should handle create/resize failure 1414 layerCanvas = mResizeBuffer.start(hwRendererCanvas); 1415 layerCanvas.setViewport(mWidth, mHeight); 1416 layerCanvas.onPreDraw(null); 1417 final int restoreCount = layerCanvas.save(); 1418 1419 layerCanvas.drawColor(0xff000000, PorterDuff.Mode.SRC); 1420 1421 int yoff; 1422 final boolean scrolling = mScroller != null 1423 && mScroller.computeScrollOffset(); 1424 if (scrolling) { 1425 yoff = mScroller.getCurrY(); 1426 mScroller.abortAnimation(); 1427 } else { 1428 yoff = mScrollY; 1429 } 1430 1431 layerCanvas.translate(0, -yoff); 1432 if (mTranslator != null) { 1433 mTranslator.translateCanvas(layerCanvas); 1434 } 1435 1436 mView.draw(layerCanvas); 1437 1438 drawAccessibilityFocusedDrawableIfNeeded(layerCanvas); 1439 1440 mResizeBufferStartTime = SystemClock.uptimeMillis(); 1441 mResizeBufferDuration = mView.getResources().getInteger( 1442 com.android.internal.R.integer.config_mediumAnimTime); 1443 completed = true; 1444 1445 layerCanvas.restoreToCount(restoreCount); 1446 } catch (OutOfMemoryError e) { 1447 Log.w(TAG, "Not enough memory for content change anim buffer", e); 1448 } finally { 1449 if (layerCanvas != null) { 1450 layerCanvas.onPostDraw(); 1451 } 1452 if (mResizeBuffer != null) { 1453 mResizeBuffer.end(hwRendererCanvas); 1454 if (!completed) { 1455 mResizeBuffer.destroy(); 1456 mResizeBuffer = null; 1457 } 1458 } 1459 } 1460 } 1461 mAttachInfo.mContentInsets.set(mPendingContentInsets); 1462 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: " 1463 + mAttachInfo.mContentInsets); 1464 } 1465 if (contentInsetsChanged || mLastSystemUiVisibility != 1466 mAttachInfo.mSystemUiVisibility || mFitSystemWindowsRequested) { 1467 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1468 mFitSystemWindowsRequested = false; 1469 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets); 1470 host.fitSystemWindows(mFitSystemWindowsInsets); 1471 } 1472 if (visibleInsetsChanged) { 1473 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1474 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1475 + mAttachInfo.mVisibleInsets); 1476 } 1477 1478 if (!hadSurface) { 1479 if (mSurface.isValid()) { 1480 // If we are creating a new surface, then we need to 1481 // completely redraw it. Also, when we get to the 1482 // point of drawing it we will hold off and schedule 1483 // a new traversal instead. This is so we can tell the 1484 // window manager about all of the windows being displayed 1485 // before actually drawing them, so it can display then 1486 // all at once. 1487 newSurface = true; 1488 mFullRedrawNeeded = true; 1489 mPreviousTransparentRegion.setEmpty(); 1490 1491 if (mAttachInfo.mHardwareRenderer != null) { 1492 try { 1493 hwInitialized = mAttachInfo.mHardwareRenderer.initialize( 1494 mHolder.getSurface()); 1495 } catch (Surface.OutOfResourcesException e) { 1496 Log.e(TAG, "OutOfResourcesException initializing HW surface", e); 1497 try { 1498 if (!mWindowSession.outOfMemory(mWindow) && 1499 Process.myUid() != Process.SYSTEM_UID) { 1500 Slog.w(TAG, "No processes killed for memory; killing self"); 1501 Process.killProcess(Process.myPid()); 1502 } 1503 } catch (RemoteException ex) { 1504 } 1505 mLayoutRequested = true; // ask wm for a new surface next time. 1506 return; 1507 } 1508 } 1509 } 1510 } else if (!mSurface.isValid()) { 1511 // If the surface has been removed, then reset the scroll 1512 // positions. 1513 mLastScrolledFocus = null; 1514 mScrollY = mCurScrollY = 0; 1515 if (mScroller != null) { 1516 mScroller.abortAnimation(); 1517 } 1518 disposeResizeBuffer(); 1519 // Our surface is gone 1520 if (mAttachInfo.mHardwareRenderer != null && 1521 mAttachInfo.mHardwareRenderer.isEnabled()) { 1522 mAttachInfo.mHardwareRenderer.destroy(true); 1523 } 1524 } else if (surfaceGenerationId != mSurface.getGenerationId() && 1525 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) { 1526 mFullRedrawNeeded = true; 1527 try { 1528 mAttachInfo.mHardwareRenderer.updateSurface(mHolder.getSurface()); 1529 } catch (Surface.OutOfResourcesException e) { 1530 Log.e(TAG, "OutOfResourcesException updating HW surface", e); 1531 try { 1532 if (!mWindowSession.outOfMemory(mWindow)) { 1533 Slog.w(TAG, "No processes killed for memory; killing self"); 1534 Process.killProcess(Process.myPid()); 1535 } 1536 } catch (RemoteException ex) { 1537 } 1538 mLayoutRequested = true; // ask wm for a new surface next time. 1539 return; 1540 } 1541 } 1542 } catch (RemoteException e) { 1543 } 1544 1545 if (DEBUG_ORIENTATION) Log.v( 1546 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface); 1547 1548 attachInfo.mWindowLeft = frame.left; 1549 attachInfo.mWindowTop = frame.top; 1550 1551 // !!FIXME!! This next section handles the case where we did not get the 1552 // window size we asked for. We should avoid this by getting a maximum size from 1553 // the window session beforehand. 1554 if (mWidth != frame.width() || mHeight != frame.height()) { 1555 mWidth = frame.width(); 1556 mHeight = frame.height(); 1557 } 1558 1559 if (mSurfaceHolder != null) { 1560 // The app owns the surface; tell it about what is going on. 1561 if (mSurface.isValid()) { 1562 // XXX .copyFrom() doesn't work! 1563 //mSurfaceHolder.mSurface.copyFrom(mSurface); 1564 mSurfaceHolder.mSurface = mSurface; 1565 } 1566 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight); 1567 mSurfaceHolder.mSurfaceLock.unlock(); 1568 if (mSurface.isValid()) { 1569 if (!hadSurface) { 1570 mSurfaceHolder.ungetCallbacks(); 1571 1572 mIsCreating = true; 1573 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder); 1574 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1575 if (callbacks != null) { 1576 for (SurfaceHolder.Callback c : callbacks) { 1577 c.surfaceCreated(mSurfaceHolder); 1578 } 1579 } 1580 surfaceChanged = true; 1581 } 1582 if (surfaceChanged) { 1583 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder, 1584 lp.format, mWidth, mHeight); 1585 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1586 if (callbacks != null) { 1587 for (SurfaceHolder.Callback c : callbacks) { 1588 c.surfaceChanged(mSurfaceHolder, lp.format, 1589 mWidth, mHeight); 1590 } 1591 } 1592 } 1593 mIsCreating = false; 1594 } else if (hadSurface) { 1595 mSurfaceHolder.ungetCallbacks(); 1596 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1597 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder); 1598 if (callbacks != null) { 1599 for (SurfaceHolder.Callback c : callbacks) { 1600 c.surfaceDestroyed(mSurfaceHolder); 1601 } 1602 } 1603 mSurfaceHolder.mSurfaceLock.lock(); 1604 try { 1605 mSurfaceHolder.mSurface = new Surface(); 1606 } finally { 1607 mSurfaceHolder.mSurfaceLock.unlock(); 1608 } 1609 } 1610 } 1611 1612 if (mAttachInfo.mHardwareRenderer != null && 1613 mAttachInfo.mHardwareRenderer.isEnabled()) { 1614 if (hwInitialized || windowShouldResize || 1615 mWidth != mAttachInfo.mHardwareRenderer.getWidth() || 1616 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) { 1617 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight); 1618 if (!hwInitialized) { 1619 mAttachInfo.mHardwareRenderer.invalidate(mHolder.getSurface()); 1620 mFullRedrawNeeded = true; 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(args.arg1) 2822 && mPendingContentInsets.equals(args.arg2) 2823 && mPendingVisibleInsets.equals(args.arg3) 2824 && 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 if (mAttachInfo.mHardwareRenderer.initializeIfNeeded( 2887 mWidth, mHeight, mHolder.getSurface())) { 2888 mFullRedrawNeeded = true; 2889 } 2890 } catch (Surface.OutOfResourcesException e) { 2891 Log.e(TAG, "OutOfResourcesException locking surface", e); 2892 try { 2893 if (!mWindowSession.outOfMemory(mWindow)) { 2894 Slog.w(TAG, "No processes killed for memory; killing self"); 2895 Process.killProcess(Process.myPid()); 2896 } 2897 } catch (RemoteException ex) { 2898 } 2899 // Retry in a bit. 2900 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 2901 return; 2902 } 2903 } 2904 } 2905 2906 mLastWasImTarget = WindowManager.LayoutParams 2907 .mayUseInputMethod(mWindowAttributes.flags); 2908 2909 InputMethodManager imm = InputMethodManager.peekInstance(); 2910 if (mView != null) { 2911 if (hasWindowFocus && imm != null && mLastWasImTarget) { 2912 imm.startGettingWindowFocus(mView); 2913 } 2914 mAttachInfo.mKeyDispatchState.reset(); 2915 mView.dispatchWindowFocusChanged(hasWindowFocus); 2916 } 2917 2918 // Note: must be done after the focus change callbacks, 2919 // so all of the view state is set up correctly. 2920 if (hasWindowFocus) { 2921 if (imm != null && mLastWasImTarget) { 2922 imm.onWindowFocus(mView, mView.findFocus(), 2923 mWindowAttributes.softInputMode, 2924 !mHasHadWindowFocus, mWindowAttributes.flags); 2925 } 2926 // Clear the forward bit. We can just do this directly, since 2927 // the window manager doesn't care about it. 2928 mWindowAttributes.softInputMode &= 2929 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2930 ((WindowManager.LayoutParams)mView.getLayoutParams()) 2931 .softInputMode &= 2932 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2933 mHasHadWindowFocus = true; 2934 } 2935 2936 setAccessibilityFocus(null, null); 2937 2938 if (mView != null && mAccessibilityManager.isEnabled()) { 2939 if (hasWindowFocus) { 2940 mView.sendAccessibilityEvent( 2941 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 2942 } 2943 } 2944 } 2945 } break; 2946 case MSG_DIE: 2947 doDie(); 2948 break; 2949 case MSG_DISPATCH_KEY: { 2950 KeyEvent event = (KeyEvent)msg.obj; 2951 enqueueInputEvent(event, null, 0, true); 2952 } break; 2953 case MSG_DISPATCH_KEY_FROM_IME: { 2954 if (LOCAL_LOGV) Log.v( 2955 TAG, "Dispatching key " 2956 + msg.obj + " from IME to " + mView); 2957 KeyEvent event = (KeyEvent)msg.obj; 2958 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 2959 // The IME is trying to say this event is from the 2960 // system! Bad bad bad! 2961 //noinspection UnusedAssignment 2962 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 2963 } 2964 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 2965 } break; 2966 case MSG_FINISH_INPUT_CONNECTION: { 2967 InputMethodManager imm = InputMethodManager.peekInstance(); 2968 if (imm != null) { 2969 imm.reportFinishInputConnection((InputConnection)msg.obj); 2970 } 2971 } break; 2972 case MSG_CHECK_FOCUS: { 2973 InputMethodManager imm = InputMethodManager.peekInstance(); 2974 if (imm != null) { 2975 imm.checkFocus(); 2976 } 2977 } break; 2978 case MSG_CLOSE_SYSTEM_DIALOGS: { 2979 if (mView != null) { 2980 mView.onCloseSystemDialogs((String)msg.obj); 2981 } 2982 } break; 2983 case MSG_DISPATCH_DRAG_EVENT: 2984 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 2985 DragEvent event = (DragEvent)msg.obj; 2986 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 2987 handleDragEvent(event); 2988 } break; 2989 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 2990 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj); 2991 } break; 2992 case MSG_UPDATE_CONFIGURATION: { 2993 Configuration config = (Configuration)msg.obj; 2994 if (config.isOtherSeqNewer(mLastConfiguration)) { 2995 config = mLastConfiguration; 2996 } 2997 updateConfiguration(config, false); 2998 } break; 2999 case MSG_DISPATCH_SCREEN_STATE: { 3000 if (mView != null) { 3001 handleScreenStateChange(msg.arg1 == 1); 3002 } 3003 } break; 3004 case MSG_INVALIDATE_DISPLAY_LIST: { 3005 invalidateDisplayLists(); 3006 } break; 3007 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3008 setAccessibilityFocus(null, null); 3009 } break; 3010 case MSG_DISPATCH_DONE_ANIMATING: { 3011 handleDispatchDoneAnimating(); 3012 } break; 3013 case MSG_INVALIDATE_WORLD: { 3014 if (mView != null) { 3015 invalidateWorld(mView); 3016 } 3017 } break; 3018 } 3019 } 3020 } 3021 3022 final ViewRootHandler mHandler = new ViewRootHandler(); 3023 3024 /** 3025 * Something in the current window tells us we need to change the touch mode. For 3026 * example, we are not in touch mode, and the user touches the screen. 3027 * 3028 * If the touch mode has changed, tell the window manager, and handle it locally. 3029 * 3030 * @param inTouchMode Whether we want to be in touch mode. 3031 * @return True if the touch mode changed and focus changed was changed as a result 3032 */ 3033 boolean ensureTouchMode(boolean inTouchMode) { 3034 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3035 + "touch mode is " + mAttachInfo.mInTouchMode); 3036 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3037 3038 // tell the window manager 3039 try { 3040 mWindowSession.setInTouchMode(inTouchMode); 3041 } catch (RemoteException e) { 3042 throw new RuntimeException(e); 3043 } 3044 3045 // handle the change 3046 return ensureTouchModeLocally(inTouchMode); 3047 } 3048 3049 /** 3050 * Ensure that the touch mode for this window is set, and if it is changing, 3051 * take the appropriate action. 3052 * @param inTouchMode Whether we want to be in touch mode. 3053 * @return True if the touch mode changed and focus changed was changed as a result 3054 */ 3055 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3056 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3057 + "touch mode is " + mAttachInfo.mInTouchMode); 3058 3059 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3060 3061 mAttachInfo.mInTouchMode = inTouchMode; 3062 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3063 3064 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3065 } 3066 3067 private boolean enterTouchMode() { 3068 if (mView != null) { 3069 if (mView.hasFocus()) { 3070 // note: not relying on mFocusedView here because this could 3071 // be when the window is first being added, and mFocused isn't 3072 // set yet. 3073 final View focused = mView.findFocus(); 3074 if (focused != null && !focused.isFocusableInTouchMode()) { 3075 3076 final ViewGroup ancestorToTakeFocus = 3077 findAncestorToTakeFocusInTouchMode(focused); 3078 if (ancestorToTakeFocus != null) { 3079 // there is an ancestor that wants focus after its descendants that 3080 // is focusable in touch mode.. give it focus 3081 return ancestorToTakeFocus.requestFocus(); 3082 } else { 3083 // nothing appropriate to have focus in touch mode, clear it out 3084 mView.unFocus(); 3085 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null); 3086 mFocusedView = null; 3087 mOldFocusedView = null; 3088 return true; 3089 } 3090 } 3091 } 3092 } 3093 return false; 3094 } 3095 3096 /** 3097 * Find an ancestor of focused that wants focus after its descendants and is 3098 * focusable in touch mode. 3099 * @param focused The currently focused view. 3100 * @return An appropriate view, or null if no such view exists. 3101 */ 3102 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3103 ViewParent parent = focused.getParent(); 3104 while (parent instanceof ViewGroup) { 3105 final ViewGroup vgParent = (ViewGroup) parent; 3106 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3107 && vgParent.isFocusableInTouchMode()) { 3108 return vgParent; 3109 } 3110 if (vgParent.isRootNamespace()) { 3111 return null; 3112 } else { 3113 parent = vgParent.getParent(); 3114 } 3115 } 3116 return null; 3117 } 3118 3119 private boolean leaveTouchMode() { 3120 if (mView != null) { 3121 if (mView.hasFocus()) { 3122 // i learned the hard way to not trust mFocusedView :) 3123 mFocusedView = mView.findFocus(); 3124 if (!(mFocusedView instanceof ViewGroup)) { 3125 // some view has focus, let it keep it 3126 return false; 3127 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() != 3128 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3129 // some view group has focus, and doesn't prefer its children 3130 // over itself for focus, so let them keep it. 3131 return false; 3132 } 3133 } 3134 3135 // find the best view to give focus to in this brave new non-touch-mode 3136 // world 3137 final View focused = focusSearch(null, View.FOCUS_DOWN); 3138 if (focused != null) { 3139 return focused.requestFocus(View.FOCUS_DOWN); 3140 } 3141 } 3142 return false; 3143 } 3144 3145 private void deliverInputEvent(QueuedInputEvent q) { 3146 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent"); 3147 try { 3148 if (q.mEvent instanceof KeyEvent) { 3149 deliverKeyEvent(q); 3150 } else { 3151 final int source = q.mEvent.getSource(); 3152 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3153 deliverPointerEvent(q); 3154 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3155 deliverTrackballEvent(q); 3156 } else { 3157 deliverGenericMotionEvent(q); 3158 } 3159 } 3160 } finally { 3161 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 3162 } 3163 } 3164 3165 private void deliverPointerEvent(QueuedInputEvent q) { 3166 final MotionEvent event = (MotionEvent)q.mEvent; 3167 final boolean isTouchEvent = event.isTouchEvent(); 3168 if (mInputEventConsistencyVerifier != null) { 3169 if (isTouchEvent) { 3170 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 3171 } else { 3172 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3173 } 3174 } 3175 3176 // If there is no view, then the event will not be handled. 3177 if (mView == null || !mAdded) { 3178 finishInputEvent(q, false); 3179 return; 3180 } 3181 3182 // Translate the pointer event for compatibility, if needed. 3183 if (mTranslator != null) { 3184 mTranslator.translateEventInScreenToAppWindow(event); 3185 } 3186 3187 // Enter touch mode on down or scroll. 3188 final int action = event.getAction(); 3189 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3190 ensureTouchMode(true); 3191 } 3192 3193 // Offset the scroll position. 3194 if (mCurScrollY != 0) { 3195 event.offsetLocation(0, mCurScrollY); 3196 } 3197 if (MEASURE_LATENCY) { 3198 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano()); 3199 } 3200 3201 // Remember the touch position for possible drag-initiation. 3202 if (isTouchEvent) { 3203 mLastTouchPoint.x = event.getRawX(); 3204 mLastTouchPoint.y = event.getRawY(); 3205 } 3206 3207 // Dispatch touch to view hierarchy. 3208 boolean handled = mView.dispatchPointerEvent(event); 3209 if (MEASURE_LATENCY) { 3210 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano()); 3211 } 3212 if (handled) { 3213 finishInputEvent(q, true); 3214 return; 3215 } 3216 3217 // Pointer event was unhandled. 3218 finishInputEvent(q, false); 3219 } 3220 3221 private void deliverTrackballEvent(QueuedInputEvent q) { 3222 final MotionEvent event = (MotionEvent)q.mEvent; 3223 if (mInputEventConsistencyVerifier != null) { 3224 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 3225 } 3226 3227 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3228 if (LOCAL_LOGV) 3229 Log.v(TAG, "Dispatching trackball " + event + " to " + mView); 3230 3231 // Dispatch to the IME before propagating down the view hierarchy. 3232 // The IME will eventually call back into handleImeFinishedEvent. 3233 if (mLastWasImTarget) { 3234 InputMethodManager imm = InputMethodManager.peekInstance(); 3235 if (imm != null) { 3236 final int seq = event.getSequenceNumber(); 3237 if (DEBUG_IMF) 3238 Log.v(TAG, "Sending trackball event to IME: seq=" 3239 + seq + " event=" + event); 3240 imm.dispatchTrackballEvent(mView.getContext(), seq, event, 3241 mInputMethodCallback); 3242 return; 3243 } 3244 } 3245 } 3246 3247 // Not dispatching to IME, continue with post IME actions. 3248 deliverTrackballEventPostIme(q); 3249 } 3250 3251 private void deliverTrackballEventPostIme(QueuedInputEvent q) { 3252 final MotionEvent event = (MotionEvent) q.mEvent; 3253 3254 // If there is no view, then the event will not be handled. 3255 if (mView == null || !mAdded) { 3256 finishInputEvent(q, false); 3257 return; 3258 } 3259 3260 // Deliver the trackball event to the view. 3261 if (mView.dispatchTrackballEvent(event)) { 3262 // If we reach this, we delivered a trackball event to mView and 3263 // mView consumed it. Because we will not translate the trackball 3264 // event into a key event, touch mode will not exit, so we exit 3265 // touch mode here. 3266 ensureTouchMode(false); 3267 3268 finishInputEvent(q, true); 3269 mLastTrackballTime = Integer.MIN_VALUE; 3270 return; 3271 } 3272 3273 // Translate the trackball event into DPAD keys and try to deliver those. 3274 final TrackballAxis x = mTrackballAxisX; 3275 final TrackballAxis y = mTrackballAxisY; 3276 3277 long curTime = SystemClock.uptimeMillis(); 3278 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) { 3279 // It has been too long since the last movement, 3280 // so restart at the beginning. 3281 x.reset(0); 3282 y.reset(0); 3283 mLastTrackballTime = curTime; 3284 } 3285 3286 final int action = event.getAction(); 3287 final int metaState = event.getMetaState(); 3288 switch (action) { 3289 case MotionEvent.ACTION_DOWN: 3290 x.reset(2); 3291 y.reset(2); 3292 enqueueInputEvent(new KeyEvent(curTime, curTime, 3293 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3294 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3295 InputDevice.SOURCE_KEYBOARD)); 3296 break; 3297 case MotionEvent.ACTION_UP: 3298 x.reset(2); 3299 y.reset(2); 3300 enqueueInputEvent(new KeyEvent(curTime, curTime, 3301 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3302 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3303 InputDevice.SOURCE_KEYBOARD)); 3304 break; 3305 } 3306 3307 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step=" 3308 + x.step + " dir=" + x.dir + " acc=" + x.acceleration 3309 + " move=" + event.getX() 3310 + " / Y=" + y.position + " step=" 3311 + y.step + " dir=" + y.dir + " acc=" + y.acceleration 3312 + " move=" + event.getY()); 3313 final float xOff = x.collect(event.getX(), event.getEventTime(), "X"); 3314 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y"); 3315 3316 // Generate DPAD events based on the trackball movement. 3317 // We pick the axis that has moved the most as the direction of 3318 // the DPAD. When we generate DPAD events for one axis, then the 3319 // other axis is reset -- we don't want to perform DPAD jumps due 3320 // to slight movements in the trackball when making major movements 3321 // along the other axis. 3322 int keycode = 0; 3323 int movement = 0; 3324 float accel = 1; 3325 if (xOff > yOff) { 3326 movement = x.generate((2/event.getXPrecision())); 3327 if (movement != 0) { 3328 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3329 : KeyEvent.KEYCODE_DPAD_LEFT; 3330 accel = x.acceleration; 3331 y.reset(2); 3332 } 3333 } else if (yOff > 0) { 3334 movement = y.generate((2/event.getYPrecision())); 3335 if (movement != 0) { 3336 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3337 : KeyEvent.KEYCODE_DPAD_UP; 3338 accel = y.acceleration; 3339 x.reset(2); 3340 } 3341 } 3342 3343 if (keycode != 0) { 3344 if (movement < 0) movement = -movement; 3345 int accelMovement = (int)(movement * accel); 3346 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 3347 + " accelMovement=" + accelMovement 3348 + " accel=" + accel); 3349 if (accelMovement > movement) { 3350 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3351 + keycode); 3352 movement--; 3353 int repeatCount = accelMovement - movement; 3354 enqueueInputEvent(new KeyEvent(curTime, curTime, 3355 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 3356 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3357 InputDevice.SOURCE_KEYBOARD)); 3358 } 3359 while (movement > 0) { 3360 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3361 + keycode); 3362 movement--; 3363 curTime = SystemClock.uptimeMillis(); 3364 enqueueInputEvent(new KeyEvent(curTime, curTime, 3365 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 3366 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3367 InputDevice.SOURCE_KEYBOARD)); 3368 enqueueInputEvent(new KeyEvent(curTime, curTime, 3369 KeyEvent.ACTION_UP, keycode, 0, metaState, 3370 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3371 InputDevice.SOURCE_KEYBOARD)); 3372 } 3373 mLastTrackballTime = curTime; 3374 } 3375 3376 // Unfortunately we can't tell whether the application consumed the keys, so 3377 // we always consider the trackball event handled. 3378 finishInputEvent(q, true); 3379 } 3380 3381 private void deliverGenericMotionEvent(QueuedInputEvent q) { 3382 final MotionEvent event = (MotionEvent)q.mEvent; 3383 if (mInputEventConsistencyVerifier != null) { 3384 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3385 } 3386 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3387 if (LOCAL_LOGV) 3388 Log.v(TAG, "Dispatching generic motion " + event + " to " + mView); 3389 3390 // Dispatch to the IME before propagating down the view hierarchy. 3391 // The IME will eventually call back into handleImeFinishedEvent. 3392 if (mLastWasImTarget) { 3393 InputMethodManager imm = InputMethodManager.peekInstance(); 3394 if (imm != null) { 3395 final int seq = event.getSequenceNumber(); 3396 if (DEBUG_IMF) 3397 Log.v(TAG, "Sending generic motion event to IME: seq=" 3398 + seq + " event=" + event); 3399 imm.dispatchGenericMotionEvent(mView.getContext(), seq, event, 3400 mInputMethodCallback); 3401 return; 3402 } 3403 } 3404 } 3405 3406 // Not dispatching to IME, continue with post IME actions. 3407 deliverGenericMotionEventPostIme(q); 3408 } 3409 3410 private void deliverGenericMotionEventPostIme(QueuedInputEvent q) { 3411 final MotionEvent event = (MotionEvent) q.mEvent; 3412 final int source = event.getSource(); 3413 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0; 3414 final boolean isTouchPad = (source & InputDevice.SOURCE_CLASS_POSITION) != 0; 3415 3416 // If there is no view, then the event will not be handled. 3417 if (mView == null || !mAdded) { 3418 if (isJoystick) { 3419 updateJoystickDirection(event, false); 3420 } else if (isTouchPad) { 3421 //Convert TouchPad motion into a TrackBall event 3422 mSimulatedTrackball.updateTrackballDirection(this, event); 3423 } 3424 finishInputEvent(q, false); 3425 return; 3426 } 3427 3428 // Deliver the event to the view. 3429 if (mView.dispatchGenericMotionEvent(event)) { 3430 if (isJoystick) { 3431 updateJoystickDirection(event, false); 3432 } else if (isTouchPad) { 3433 //Convert TouchPad motion into a TrackBall event 3434 mSimulatedTrackball.updateTrackballDirection(this, event); 3435 } 3436 finishInputEvent(q, true); 3437 return; 3438 } 3439 3440 if (isJoystick) { 3441 // Translate the joystick event into DPAD keys and try to deliver 3442 // those. 3443 updateJoystickDirection(event, true); 3444 finishInputEvent(q, true); 3445 } else if (isTouchPad) { 3446 //Convert TouchPad motion into a TrackBall event 3447 mSimulatedTrackball.updateTrackballDirection(this, event); 3448 finishInputEvent(q, true); 3449 } else { 3450 finishInputEvent(q, false); 3451 } 3452 } 3453 3454 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) { 3455 final long time = event.getEventTime(); 3456 final int metaState = event.getMetaState(); 3457 final int deviceId = event.getDeviceId(); 3458 final int source = event.getSource(); 3459 3460 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X)); 3461 if (xDirection == 0) { 3462 xDirection = joystickAxisValueToDirection(event.getX()); 3463 } 3464 3465 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 3466 if (yDirection == 0) { 3467 yDirection = joystickAxisValueToDirection(event.getY()); 3468 } 3469 3470 if (xDirection != mLastJoystickXDirection) { 3471 if (mLastJoystickXKeyCode != 0) { 3472 enqueueInputEvent(new KeyEvent(time, time, 3473 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState, 3474 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3475 mLastJoystickXKeyCode = 0; 3476 } 3477 3478 mLastJoystickXDirection = xDirection; 3479 3480 if (xDirection != 0 && synthesizeNewKeys) { 3481 mLastJoystickXKeyCode = xDirection > 0 3482 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 3483 enqueueInputEvent(new KeyEvent(time, time, 3484 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState, 3485 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3486 } 3487 } 3488 3489 if (yDirection != mLastJoystickYDirection) { 3490 if (mLastJoystickYKeyCode != 0) { 3491 enqueueInputEvent(new KeyEvent(time, time, 3492 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState, 3493 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3494 mLastJoystickYKeyCode = 0; 3495 } 3496 3497 mLastJoystickYDirection = yDirection; 3498 3499 if (yDirection != 0 && synthesizeNewKeys) { 3500 mLastJoystickYKeyCode = yDirection > 0 3501 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 3502 enqueueInputEvent(new KeyEvent(time, time, 3503 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState, 3504 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3505 } 3506 } 3507 } 3508 3509 private static int joystickAxisValueToDirection(float value) { 3510 if (value >= 0.5f) { 3511 return 1; 3512 } else if (value <= -0.5f) { 3513 return -1; 3514 } else { 3515 return 0; 3516 } 3517 } 3518 3519 /** 3520 * Returns true if the key is used for keyboard navigation. 3521 * @param keyEvent The key event. 3522 * @return True if the key is used for keyboard navigation. 3523 */ 3524 private static boolean isNavigationKey(KeyEvent keyEvent) { 3525 switch (keyEvent.getKeyCode()) { 3526 case KeyEvent.KEYCODE_DPAD_LEFT: 3527 case KeyEvent.KEYCODE_DPAD_RIGHT: 3528 case KeyEvent.KEYCODE_DPAD_UP: 3529 case KeyEvent.KEYCODE_DPAD_DOWN: 3530 case KeyEvent.KEYCODE_DPAD_CENTER: 3531 case KeyEvent.KEYCODE_PAGE_UP: 3532 case KeyEvent.KEYCODE_PAGE_DOWN: 3533 case KeyEvent.KEYCODE_MOVE_HOME: 3534 case KeyEvent.KEYCODE_MOVE_END: 3535 case KeyEvent.KEYCODE_TAB: 3536 case KeyEvent.KEYCODE_SPACE: 3537 case KeyEvent.KEYCODE_ENTER: 3538 return true; 3539 } 3540 return false; 3541 } 3542 3543 /** 3544 * Returns true if the key is used for typing. 3545 * @param keyEvent The key event. 3546 * @return True if the key is used for typing. 3547 */ 3548 private static boolean isTypingKey(KeyEvent keyEvent) { 3549 return keyEvent.getUnicodeChar() > 0; 3550 } 3551 3552 /** 3553 * See if the key event means we should leave touch mode (and leave touch mode if so). 3554 * @param event The key event. 3555 * @return Whether this key event should be consumed (meaning the act of 3556 * leaving touch mode alone is considered the event). 3557 */ 3558 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 3559 // Only relevant in touch mode. 3560 if (!mAttachInfo.mInTouchMode) { 3561 return false; 3562 } 3563 3564 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 3565 final int action = event.getAction(); 3566 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 3567 return false; 3568 } 3569 3570 // Don't leave touch mode if the IME told us not to. 3571 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 3572 return false; 3573 } 3574 3575 // If the key can be used for keyboard navigation then leave touch mode 3576 // and select a focused view if needed (in ensureTouchMode). 3577 // When a new focused view is selected, we consume the navigation key because 3578 // navigation doesn't make much sense unless a view already has focus so 3579 // the key's purpose is to set focus. 3580 if (isNavigationKey(event)) { 3581 return ensureTouchMode(false); 3582 } 3583 3584 // If the key can be used for typing then leave touch mode 3585 // and select a focused view if needed (in ensureTouchMode). 3586 // Always allow the view to process the typing key. 3587 if (isTypingKey(event)) { 3588 ensureTouchMode(false); 3589 return false; 3590 } 3591 3592 return false; 3593 } 3594 3595 private void deliverKeyEvent(QueuedInputEvent q) { 3596 final KeyEvent event = (KeyEvent)q.mEvent; 3597 if (mInputEventConsistencyVerifier != null) { 3598 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 3599 } 3600 3601 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3602 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView); 3603 3604 // Perform predispatching before the IME. 3605 if (mView.dispatchKeyEventPreIme(event)) { 3606 finishInputEvent(q, true); 3607 return; 3608 } 3609 3610 // Dispatch to the IME before propagating down the view hierarchy. 3611 // The IME will eventually call back into handleImeFinishedEvent. 3612 if (mLastWasImTarget) { 3613 InputMethodManager imm = InputMethodManager.peekInstance(); 3614 if (imm != null) { 3615 final int seq = event.getSequenceNumber(); 3616 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq=" 3617 + seq + " event=" + event); 3618 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback); 3619 return; 3620 } 3621 } 3622 } 3623 3624 // Not dispatching to IME, continue with post IME actions. 3625 deliverKeyEventPostIme(q); 3626 } 3627 3628 void handleImeFinishedEvent(int seq, boolean handled) { 3629 final QueuedInputEvent q = mCurrentInputEvent; 3630 if (q != null && q.mEvent.getSequenceNumber() == seq) { 3631 if (DEBUG_IMF) { 3632 Log.v(TAG, "IME finished event: seq=" + seq 3633 + " handled=" + handled + " event=" + q); 3634 } 3635 if (handled) { 3636 finishInputEvent(q, true); 3637 } else { 3638 if (q.mEvent instanceof KeyEvent) { 3639 KeyEvent event = (KeyEvent)q.mEvent; 3640 if (event.getAction() != KeyEvent.ACTION_UP) { 3641 // If the window doesn't currently have input focus, then drop 3642 // this event. This could be an event that came back from the 3643 // IME dispatch but the window has lost focus in the meantime. 3644 if (!mAttachInfo.mHasWindowFocus) { 3645 Slog.w(TAG, "Dropping event due to no window focus: " + event); 3646 finishInputEvent(q, true); 3647 return; 3648 } 3649 } 3650 deliverKeyEventPostIme(q); 3651 } else { 3652 MotionEvent event = (MotionEvent)q.mEvent; 3653 if (event.getAction() != MotionEvent.ACTION_CANCEL 3654 && event.getAction() != MotionEvent.ACTION_UP) { 3655 // If the window doesn't currently have input focus, then drop 3656 // this event. This could be an event that came back from the 3657 // IME dispatch but the window has lost focus in the meantime. 3658 if (!mAttachInfo.mHasWindowFocus) { 3659 Slog.w(TAG, "Dropping event due to no window focus: " + event); 3660 finishInputEvent(q, true); 3661 return; 3662 } 3663 } 3664 final int source = q.mEvent.getSource(); 3665 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3666 deliverTrackballEventPostIme(q); 3667 } else { 3668 deliverGenericMotionEventPostIme(q); 3669 } 3670 } 3671 } 3672 } else { 3673 if (DEBUG_IMF) { 3674 Log.v(TAG, "IME finished event: seq=" + seq 3675 + " handled=" + handled + ", event not found!"); 3676 } 3677 } 3678 } 3679 3680 private void deliverKeyEventPostIme(QueuedInputEvent q) { 3681 final KeyEvent event = (KeyEvent)q.mEvent; 3682 3683 // If the view went away, then the event will not be handled. 3684 if (mView == null || !mAdded) { 3685 finishInputEvent(q, false); 3686 return; 3687 } 3688 3689 // If the key's purpose is to exit touch mode then we consume it and consider it handled. 3690 if (checkForLeavingTouchModeAndConsume(event)) { 3691 finishInputEvent(q, true); 3692 return; 3693 } 3694 3695 // Make sure the fallback event policy sees all keys that will be delivered to the 3696 // view hierarchy. 3697 mFallbackEventHandler.preDispatchKeyEvent(event); 3698 3699 // Deliver the key to the view hierarchy. 3700 if (mView.dispatchKeyEvent(event)) { 3701 finishInputEvent(q, true); 3702 return; 3703 } 3704 3705 // If the Control modifier is held, try to interpret the key as a shortcut. 3706 if (event.getAction() == KeyEvent.ACTION_DOWN 3707 && event.isCtrlPressed() 3708 && event.getRepeatCount() == 0 3709 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3710 if (mView.dispatchKeyShortcutEvent(event)) { 3711 finishInputEvent(q, true); 3712 return; 3713 } 3714 } 3715 3716 // Apply the fallback event policy. 3717 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3718 finishInputEvent(q, true); 3719 return; 3720 } 3721 3722 // Handle automatic focus changes. 3723 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3724 int direction = 0; 3725 switch (event.getKeyCode()) { 3726 case KeyEvent.KEYCODE_DPAD_LEFT: 3727 if (event.hasNoModifiers()) { 3728 direction = View.FOCUS_LEFT; 3729 } 3730 break; 3731 case KeyEvent.KEYCODE_DPAD_RIGHT: 3732 if (event.hasNoModifiers()) { 3733 direction = View.FOCUS_RIGHT; 3734 } 3735 break; 3736 case KeyEvent.KEYCODE_DPAD_UP: 3737 if (event.hasNoModifiers()) { 3738 direction = View.FOCUS_UP; 3739 } 3740 break; 3741 case KeyEvent.KEYCODE_DPAD_DOWN: 3742 if (event.hasNoModifiers()) { 3743 direction = View.FOCUS_DOWN; 3744 } 3745 break; 3746 case KeyEvent.KEYCODE_TAB: 3747 if (event.hasNoModifiers()) { 3748 direction = View.FOCUS_FORWARD; 3749 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3750 direction = View.FOCUS_BACKWARD; 3751 } 3752 break; 3753 } 3754 if (direction != 0) { 3755 View focused = mView.findFocus(); 3756 if (focused != null) { 3757 View v = focused.focusSearch(direction); 3758 if (v != null && v != focused) { 3759 // do the math the get the interesting rect 3760 // of previous focused into the coord system of 3761 // newly focused view 3762 focused.getFocusedRect(mTempRect); 3763 if (mView instanceof ViewGroup) { 3764 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3765 focused, mTempRect); 3766 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3767 v, mTempRect); 3768 } 3769 if (v.requestFocus(direction, mTempRect)) { 3770 playSoundEffect(SoundEffectConstants 3771 .getContantForFocusDirection(direction)); 3772 finishInputEvent(q, true); 3773 return; 3774 } 3775 } 3776 3777 // Give the focused view a last chance to handle the dpad key. 3778 if (mView.dispatchUnhandledMove(focused, direction)) { 3779 finishInputEvent(q, true); 3780 return; 3781 } 3782 } 3783 } 3784 } 3785 3786 // Key was unhandled. 3787 finishInputEvent(q, false); 3788 } 3789 3790 /* drag/drop */ 3791 void setLocalDragState(Object obj) { 3792 mLocalDragState = obj; 3793 } 3794 3795 private void handleDragEvent(DragEvent event) { 3796 // From the root, only drag start/end/location are dispatched. entered/exited 3797 // are determined and dispatched by the viewgroup hierarchy, who then report 3798 // that back here for ultimate reporting back to the framework. 3799 if (mView != null && mAdded) { 3800 final int what = event.mAction; 3801 3802 if (what == DragEvent.ACTION_DRAG_EXITED) { 3803 // A direct EXITED event means that the window manager knows we've just crossed 3804 // a window boundary, so the current drag target within this one must have 3805 // just been exited. Send it the usual notifications and then we're done 3806 // for now. 3807 mView.dispatchDragEvent(event); 3808 } else { 3809 // Cache the drag description when the operation starts, then fill it in 3810 // on subsequent calls as a convenience 3811 if (what == DragEvent.ACTION_DRAG_STARTED) { 3812 mCurrentDragView = null; // Start the current-recipient tracking 3813 mDragDescription = event.mClipDescription; 3814 } else { 3815 event.mClipDescription = mDragDescription; 3816 } 3817 3818 // For events with a [screen] location, translate into window coordinates 3819 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 3820 mDragPoint.set(event.mX, event.mY); 3821 if (mTranslator != null) { 3822 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 3823 } 3824 3825 if (mCurScrollY != 0) { 3826 mDragPoint.offset(0, mCurScrollY); 3827 } 3828 3829 event.mX = mDragPoint.x; 3830 event.mY = mDragPoint.y; 3831 } 3832 3833 // Remember who the current drag target is pre-dispatch 3834 final View prevDragView = mCurrentDragView; 3835 3836 // Now dispatch the drag/drop event 3837 boolean result = mView.dispatchDragEvent(event); 3838 3839 // If we changed apparent drag target, tell the OS about it 3840 if (prevDragView != mCurrentDragView) { 3841 try { 3842 if (prevDragView != null) { 3843 mWindowSession.dragRecipientExited(mWindow); 3844 } 3845 if (mCurrentDragView != null) { 3846 mWindowSession.dragRecipientEntered(mWindow); 3847 } 3848 } catch (RemoteException e) { 3849 Slog.e(TAG, "Unable to note drag target change"); 3850 } 3851 } 3852 3853 // Report the drop result when we're done 3854 if (what == DragEvent.ACTION_DROP) { 3855 mDragDescription = null; 3856 try { 3857 Log.i(TAG, "Reporting drop result: " + result); 3858 mWindowSession.reportDropResult(mWindow, result); 3859 } catch (RemoteException e) { 3860 Log.e(TAG, "Unable to report drop result"); 3861 } 3862 } 3863 3864 // When the drag operation ends, release any local state object 3865 // that may have been in use 3866 if (what == DragEvent.ACTION_DRAG_ENDED) { 3867 setLocalDragState(null); 3868 } 3869 } 3870 } 3871 event.recycle(); 3872 } 3873 3874 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 3875 if (mSeq != args.seq) { 3876 // The sequence has changed, so we need to update our value and make 3877 // sure to do a traversal afterward so the window manager is given our 3878 // most recent data. 3879 mSeq = args.seq; 3880 mAttachInfo.mForceReportNewAttributes = true; 3881 scheduleTraversals(); 3882 } 3883 if (mView == null) return; 3884 if (args.localChanges != 0) { 3885 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 3886 } 3887 if (mAttachInfo != null) { 3888 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 3889 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 3890 mAttachInfo.mGlobalSystemUiVisibility = visibility; 3891 mView.dispatchSystemUiVisibilityChanged(visibility); 3892 } 3893 } 3894 } 3895 3896 public void handleDispatchDoneAnimating() { 3897 if (mWindowsAnimating) { 3898 mWindowsAnimating = false; 3899 if (!mDirty.isEmpty() || mIsAnimating) { 3900 scheduleTraversals(); 3901 } 3902 } 3903 } 3904 3905 public void getLastTouchPoint(Point outLocation) { 3906 outLocation.x = (int) mLastTouchPoint.x; 3907 outLocation.y = (int) mLastTouchPoint.y; 3908 } 3909 3910 public void setDragFocus(View newDragTarget) { 3911 if (mCurrentDragView != newDragTarget) { 3912 mCurrentDragView = newDragTarget; 3913 } 3914 } 3915 3916 private AudioManager getAudioManager() { 3917 if (mView == null) { 3918 throw new IllegalStateException("getAudioManager called when there is no mView"); 3919 } 3920 if (mAudioManager == null) { 3921 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 3922 } 3923 return mAudioManager; 3924 } 3925 3926 public AccessibilityInteractionController getAccessibilityInteractionController() { 3927 if (mView == null) { 3928 throw new IllegalStateException("getAccessibilityInteractionController" 3929 + " called when there is no mView"); 3930 } 3931 if (mAccessibilityInteractionController == null) { 3932 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 3933 } 3934 return mAccessibilityInteractionController; 3935 } 3936 3937 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 3938 boolean insetsPending) throws RemoteException { 3939 3940 float appScale = mAttachInfo.mApplicationScale; 3941 boolean restore = false; 3942 if (params != null && mTranslator != null) { 3943 restore = true; 3944 params.backup(); 3945 mTranslator.translateWindowLayout(params); 3946 } 3947 if (params != null) { 3948 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 3949 } 3950 mPendingConfiguration.seq = 0; 3951 //Log.d(TAG, ">>>>>> CALLING relayout"); 3952 if (params != null && mOrigWindowType != params.type) { 3953 // For compatibility with old apps, don't crash here. 3954 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 3955 Slog.w(TAG, "Window type can not be changed after " 3956 + "the window is added; ignoring change of " + mView); 3957 params.type = mOrigWindowType; 3958 } 3959 } 3960 int relayoutResult = mWindowSession.relayout( 3961 mWindow, mSeq, params, 3962 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 3963 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 3964 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 3965 mWinFrame, mPendingContentInsets, mPendingVisibleInsets, 3966 mPendingConfiguration, mSurface); 3967 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 3968 if (restore) { 3969 params.restore(); 3970 } 3971 3972 if (mTranslator != null) { 3973 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 3974 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 3975 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 3976 } 3977 return relayoutResult; 3978 } 3979 3980 /** 3981 * {@inheritDoc} 3982 */ 3983 public void playSoundEffect(int effectId) { 3984 checkThread(); 3985 3986 try { 3987 final AudioManager audioManager = getAudioManager(); 3988 3989 switch (effectId) { 3990 case SoundEffectConstants.CLICK: 3991 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 3992 return; 3993 case SoundEffectConstants.NAVIGATION_DOWN: 3994 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 3995 return; 3996 case SoundEffectConstants.NAVIGATION_LEFT: 3997 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 3998 return; 3999 case SoundEffectConstants.NAVIGATION_RIGHT: 4000 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 4001 return; 4002 case SoundEffectConstants.NAVIGATION_UP: 4003 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 4004 return; 4005 default: 4006 throw new IllegalArgumentException("unknown effect id " + effectId + 4007 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 4008 } 4009 } catch (IllegalStateException e) { 4010 // Exception thrown by getAudioManager() when mView is null 4011 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 4012 e.printStackTrace(); 4013 } 4014 } 4015 4016 /** 4017 * {@inheritDoc} 4018 */ 4019 public boolean performHapticFeedback(int effectId, boolean always) { 4020 try { 4021 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 4022 } catch (RemoteException e) { 4023 return false; 4024 } 4025 } 4026 4027 /** 4028 * {@inheritDoc} 4029 */ 4030 public View focusSearch(View focused, int direction) { 4031 checkThread(); 4032 if (!(mView instanceof ViewGroup)) { 4033 return null; 4034 } 4035 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 4036 } 4037 4038 public void debug() { 4039 mView.debug(); 4040 } 4041 4042 public void dumpGfxInfo(int[] info) { 4043 info[0] = info[1] = 0; 4044 if (mView != null) { 4045 getGfxInfo(mView, info); 4046 } 4047 } 4048 4049 private static void getGfxInfo(View view, int[] info) { 4050 DisplayList displayList = view.mDisplayList; 4051 info[0]++; 4052 if (displayList != null) { 4053 info[1] += displayList.getSize(); 4054 } 4055 4056 if (view instanceof ViewGroup) { 4057 ViewGroup group = (ViewGroup) view; 4058 4059 int count = group.getChildCount(); 4060 for (int i = 0; i < count; i++) { 4061 getGfxInfo(group.getChildAt(i), info); 4062 } 4063 } 4064 } 4065 4066 public void die(boolean immediate) { 4067 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 4068 // done by dispatchDetachedFromWindow will cause havoc on return. 4069 if (immediate && !mIsInTraversal) { 4070 doDie(); 4071 } else { 4072 if (!mIsDrawing) { 4073 destroyHardwareRenderer(); 4074 } else { 4075 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 4076 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 4077 } 4078 mHandler.sendEmptyMessage(MSG_DIE); 4079 } 4080 } 4081 4082 void doDie() { 4083 checkThread(); 4084 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 4085 synchronized (this) { 4086 if (mAdded) { 4087 dispatchDetachedFromWindow(); 4088 } 4089 4090 if (mAdded && !mFirst) { 4091 destroyHardwareRenderer(); 4092 4093 if (mView != null) { 4094 int viewVisibility = mView.getVisibility(); 4095 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 4096 if (mWindowAttributesChanged || viewVisibilityChanged) { 4097 // If layout params have been changed, first give them 4098 // to the window manager to make sure it has the correct 4099 // animation info. 4100 try { 4101 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 4102 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 4103 mWindowSession.finishDrawing(mWindow); 4104 } 4105 } catch (RemoteException e) { 4106 } 4107 } 4108 4109 mSurface.release(); 4110 } 4111 } 4112 4113 mAdded = false; 4114 } 4115 } 4116 4117 public void requestUpdateConfiguration(Configuration config) { 4118 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 4119 mHandler.sendMessage(msg); 4120 } 4121 4122 public void loadSystemProperties() { 4123 boolean layout = SystemProperties.getBoolean( 4124 View.DEBUG_LAYOUT_PROPERTY, false); 4125 if (layout != mAttachInfo.mDebugLayout) { 4126 mAttachInfo.mDebugLayout = layout; 4127 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 4128 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 4129 } 4130 } 4131 } 4132 4133 private void destroyHardwareRenderer() { 4134 AttachInfo attachInfo = mAttachInfo; 4135 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 4136 4137 if (hardwareRenderer != null) { 4138 if (mView != null) { 4139 hardwareRenderer.destroyHardwareResources(mView); 4140 } 4141 hardwareRenderer.destroy(true); 4142 hardwareRenderer.setRequested(false); 4143 4144 attachInfo.mHardwareRenderer = null; 4145 attachInfo.mHardwareAccelerated = false; 4146 } 4147 } 4148 4149 void dispatchImeFinishedEvent(int seq, boolean handled) { 4150 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT); 4151 msg.arg1 = seq; 4152 msg.arg2 = handled ? 1 : 0; 4153 msg.setAsynchronous(true); 4154 mHandler.sendMessage(msg); 4155 } 4156 4157 public void dispatchFinishInputConnection(InputConnection connection) { 4158 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 4159 mHandler.sendMessage(msg); 4160 } 4161 4162 public void dispatchResized(Rect frame, Rect contentInsets, 4163 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4164 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 4165 + " contentInsets=" + contentInsets.toShortString() 4166 + " visibleInsets=" + visibleInsets.toShortString() 4167 + " reportDraw=" + reportDraw); 4168 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 4169 if (mTranslator != null) { 4170 mTranslator.translateRectInScreenToAppWindow(frame); 4171 mTranslator.translateRectInScreenToAppWindow(contentInsets); 4172 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 4173 } 4174 SomeArgs args = SomeArgs.obtain(); 4175 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 4176 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 4177 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 4178 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 4179 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 4180 msg.obj = args; 4181 mHandler.sendMessage(msg); 4182 } 4183 4184 public void dispatchMoved(int newX, int newY) { 4185 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 4186 if (mTranslator != null) { 4187 PointF point = new PointF(newX, newY); 4188 mTranslator.translatePointInScreenToAppWindow(point); 4189 newX = (int) (point.x + 0.5); 4190 newY = (int) (point.y + 0.5); 4191 } 4192 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 4193 mHandler.sendMessage(msg); 4194 } 4195 4196 /** 4197 * Represents a pending input event that is waiting in a queue. 4198 * 4199 * Input events are processed in serial order by the timestamp specified by 4200 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 4201 * one input event to the application at a time and waits for the application 4202 * to finish handling it before delivering the next one. 4203 * 4204 * However, because the application or IME can synthesize and inject multiple 4205 * key events at a time without going through the input dispatcher, we end up 4206 * needing a queue on the application's side. 4207 */ 4208 private static final class QueuedInputEvent { 4209 public static final int FLAG_DELIVER_POST_IME = 1; 4210 4211 public QueuedInputEvent mNext; 4212 4213 public InputEvent mEvent; 4214 public InputEventReceiver mReceiver; 4215 public int mFlags; 4216 } 4217 4218 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 4219 InputEventReceiver receiver, int flags) { 4220 QueuedInputEvent q = mQueuedInputEventPool; 4221 if (q != null) { 4222 mQueuedInputEventPoolSize -= 1; 4223 mQueuedInputEventPool = q.mNext; 4224 q.mNext = null; 4225 } else { 4226 q = new QueuedInputEvent(); 4227 } 4228 4229 q.mEvent = event; 4230 q.mReceiver = receiver; 4231 q.mFlags = flags; 4232 return q; 4233 } 4234 4235 private void recycleQueuedInputEvent(QueuedInputEvent q) { 4236 q.mEvent = null; 4237 q.mReceiver = null; 4238 4239 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 4240 mQueuedInputEventPoolSize += 1; 4241 q.mNext = mQueuedInputEventPool; 4242 mQueuedInputEventPool = q; 4243 } 4244 } 4245 4246 void enqueueInputEvent(InputEvent event) { 4247 enqueueInputEvent(event, null, 0, false); 4248 } 4249 4250 void enqueueInputEvent(InputEvent event, 4251 InputEventReceiver receiver, int flags, boolean processImmediately) { 4252 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 4253 4254 // Always enqueue the input event in order, regardless of its time stamp. 4255 // We do this because the application or the IME may inject key events 4256 // in response to touch events and we want to ensure that the injected keys 4257 // are processed in the order they were received and we cannot trust that 4258 // the time stamp of injected events are monotonic. 4259 QueuedInputEvent last = mFirstPendingInputEvent; 4260 if (last == null) { 4261 mFirstPendingInputEvent = q; 4262 } else { 4263 while (last.mNext != null) { 4264 last = last.mNext; 4265 } 4266 last.mNext = q; 4267 } 4268 4269 if (processImmediately) { 4270 doProcessInputEvents(); 4271 } else { 4272 scheduleProcessInputEvents(); 4273 } 4274 } 4275 4276 private void scheduleProcessInputEvents() { 4277 if (!mProcessInputEventsScheduled) { 4278 mProcessInputEventsScheduled = true; 4279 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 4280 msg.setAsynchronous(true); 4281 mHandler.sendMessage(msg); 4282 } 4283 } 4284 4285 void doProcessInputEvents() { 4286 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 4287 QueuedInputEvent q = mFirstPendingInputEvent; 4288 mFirstPendingInputEvent = q.mNext; 4289 q.mNext = null; 4290 mCurrentInputEvent = q; 4291 deliverInputEvent(q); 4292 } 4293 4294 // We are done processing all input events that we can process right now 4295 // so we can clear the pending flag immediately. 4296 if (mProcessInputEventsScheduled) { 4297 mProcessInputEventsScheduled = false; 4298 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 4299 } 4300 } 4301 4302 private void finishInputEvent(QueuedInputEvent q, boolean handled) { 4303 if (q != mCurrentInputEvent) { 4304 throw new IllegalStateException("finished input event out of order"); 4305 } 4306 4307 if (q.mReceiver != null) { 4308 q.mReceiver.finishInputEvent(q.mEvent, handled); 4309 } else { 4310 q.mEvent.recycleIfNeededAfterDispatch(); 4311 } 4312 4313 recycleQueuedInputEvent(q); 4314 4315 mCurrentInputEvent = null; 4316 if (mFirstPendingInputEvent != null) { 4317 scheduleProcessInputEvents(); 4318 } 4319 } 4320 4321 void scheduleConsumeBatchedInput() { 4322 if (!mConsumeBatchedInputScheduled) { 4323 mConsumeBatchedInputScheduled = true; 4324 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 4325 mConsumedBatchedInputRunnable, null); 4326 } 4327 } 4328 4329 void unscheduleConsumeBatchedInput() { 4330 if (mConsumeBatchedInputScheduled) { 4331 mConsumeBatchedInputScheduled = false; 4332 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4333 mConsumedBatchedInputRunnable, null); 4334 } 4335 } 4336 4337 void doConsumeBatchedInput(long frameTimeNanos) { 4338 if (mConsumeBatchedInputScheduled) { 4339 mConsumeBatchedInputScheduled = false; 4340 if (mInputEventReceiver != null) { 4341 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos); 4342 } 4343 doProcessInputEvents(); 4344 } 4345 } 4346 4347 final class TraversalRunnable implements Runnable { 4348 @Override 4349 public void run() { 4350 doTraversal(); 4351 } 4352 } 4353 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 4354 4355 final class WindowInputEventReceiver extends InputEventReceiver { 4356 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 4357 super(inputChannel, looper); 4358 } 4359 4360 @Override 4361 public void onInputEvent(InputEvent event) { 4362 enqueueInputEvent(event, this, 0, true); 4363 } 4364 4365 @Override 4366 public void onBatchedInputEventPending() { 4367 scheduleConsumeBatchedInput(); 4368 } 4369 4370 @Override 4371 public void dispose() { 4372 unscheduleConsumeBatchedInput(); 4373 super.dispose(); 4374 } 4375 } 4376 WindowInputEventReceiver mInputEventReceiver; 4377 4378 final class ConsumeBatchedInputRunnable implements Runnable { 4379 @Override 4380 public void run() { 4381 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 4382 } 4383 } 4384 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 4385 new ConsumeBatchedInputRunnable(); 4386 boolean mConsumeBatchedInputScheduled; 4387 4388 final class InvalidateOnAnimationRunnable implements Runnable { 4389 private boolean mPosted; 4390 private ArrayList<View> mViews = new ArrayList<View>(); 4391 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 4392 new ArrayList<AttachInfo.InvalidateInfo>(); 4393 private View[] mTempViews; 4394 private AttachInfo.InvalidateInfo[] mTempViewRects; 4395 4396 public void addView(View view) { 4397 synchronized (this) { 4398 mViews.add(view); 4399 postIfNeededLocked(); 4400 } 4401 } 4402 4403 public void addViewRect(AttachInfo.InvalidateInfo info) { 4404 synchronized (this) { 4405 mViewRects.add(info); 4406 postIfNeededLocked(); 4407 } 4408 } 4409 4410 public void removeView(View view) { 4411 synchronized (this) { 4412 mViews.remove(view); 4413 4414 for (int i = mViewRects.size(); i-- > 0; ) { 4415 AttachInfo.InvalidateInfo info = mViewRects.get(i); 4416 if (info.target == view) { 4417 mViewRects.remove(i); 4418 info.release(); 4419 } 4420 } 4421 4422 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 4423 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 4424 mPosted = false; 4425 } 4426 } 4427 } 4428 4429 @Override 4430 public void run() { 4431 final int viewCount; 4432 final int viewRectCount; 4433 synchronized (this) { 4434 mPosted = false; 4435 4436 viewCount = mViews.size(); 4437 if (viewCount != 0) { 4438 mTempViews = mViews.toArray(mTempViews != null 4439 ? mTempViews : new View[viewCount]); 4440 mViews.clear(); 4441 } 4442 4443 viewRectCount = mViewRects.size(); 4444 if (viewRectCount != 0) { 4445 mTempViewRects = mViewRects.toArray(mTempViewRects != null 4446 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 4447 mViewRects.clear(); 4448 } 4449 } 4450 4451 for (int i = 0; i < viewCount; i++) { 4452 mTempViews[i].invalidate(); 4453 mTempViews[i] = null; 4454 } 4455 4456 for (int i = 0; i < viewRectCount; i++) { 4457 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 4458 info.target.invalidate(info.left, info.top, info.right, info.bottom); 4459 info.release(); 4460 } 4461 } 4462 4463 private void postIfNeededLocked() { 4464 if (!mPosted) { 4465 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 4466 mPosted = true; 4467 } 4468 } 4469 } 4470 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 4471 new InvalidateOnAnimationRunnable(); 4472 4473 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 4474 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 4475 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4476 } 4477 4478 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 4479 long delayMilliseconds) { 4480 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 4481 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4482 } 4483 4484 public void dispatchInvalidateOnAnimation(View view) { 4485 mInvalidateOnAnimationRunnable.addView(view); 4486 } 4487 4488 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 4489 mInvalidateOnAnimationRunnable.addViewRect(info); 4490 } 4491 4492 public void enqueueDisplayList(DisplayList displayList) { 4493 mDisplayLists.add(displayList); 4494 4495 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4496 Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST); 4497 mHandler.sendMessage(msg); 4498 } 4499 4500 public void dequeueDisplayList(DisplayList displayList) { 4501 if (mDisplayLists.remove(displayList)) { 4502 displayList.invalidate(); 4503 if (mDisplayLists.size() == 0) { 4504 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4505 } 4506 } 4507 } 4508 4509 public void cancelInvalidate(View view) { 4510 mHandler.removeMessages(MSG_INVALIDATE, view); 4511 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 4512 // them to the pool 4513 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 4514 mInvalidateOnAnimationRunnable.removeView(view); 4515 } 4516 4517 public void dispatchKey(KeyEvent event) { 4518 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 4519 msg.setAsynchronous(true); 4520 mHandler.sendMessage(msg); 4521 } 4522 4523 public void dispatchKeyFromIme(KeyEvent event) { 4524 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 4525 msg.setAsynchronous(true); 4526 mHandler.sendMessage(msg); 4527 } 4528 4529 public void dispatchUnhandledKey(KeyEvent event) { 4530 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 4531 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 4532 final int keyCode = event.getKeyCode(); 4533 final int metaState = event.getMetaState(); 4534 4535 // Check for fallback actions specified by the key character map. 4536 KeyCharacterMap.FallbackAction fallbackAction = 4537 kcm.getFallbackAction(keyCode, metaState); 4538 if (fallbackAction != null) { 4539 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 4540 KeyEvent fallbackEvent = KeyEvent.obtain( 4541 event.getDownTime(), event.getEventTime(), 4542 event.getAction(), fallbackAction.keyCode, 4543 event.getRepeatCount(), fallbackAction.metaState, 4544 event.getDeviceId(), event.getScanCode(), 4545 flags, event.getSource(), null); 4546 fallbackAction.recycle(); 4547 4548 dispatchKey(fallbackEvent); 4549 } 4550 } 4551 } 4552 4553 public void dispatchAppVisibility(boolean visible) { 4554 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 4555 msg.arg1 = visible ? 1 : 0; 4556 mHandler.sendMessage(msg); 4557 } 4558 4559 public void dispatchScreenStateChange(boolean on) { 4560 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 4561 msg.arg1 = on ? 1 : 0; 4562 mHandler.sendMessage(msg); 4563 } 4564 4565 public void dispatchGetNewSurface() { 4566 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 4567 mHandler.sendMessage(msg); 4568 } 4569 4570 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4571 Message msg = Message.obtain(); 4572 msg.what = MSG_WINDOW_FOCUS_CHANGED; 4573 msg.arg1 = hasFocus ? 1 : 0; 4574 msg.arg2 = inTouchMode ? 1 : 0; 4575 mHandler.sendMessage(msg); 4576 } 4577 4578 public void dispatchCloseSystemDialogs(String reason) { 4579 Message msg = Message.obtain(); 4580 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 4581 msg.obj = reason; 4582 mHandler.sendMessage(msg); 4583 } 4584 4585 public void dispatchDragEvent(DragEvent event) { 4586 final int what; 4587 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 4588 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 4589 mHandler.removeMessages(what); 4590 } else { 4591 what = MSG_DISPATCH_DRAG_EVENT; 4592 } 4593 Message msg = mHandler.obtainMessage(what, event); 4594 mHandler.sendMessage(msg); 4595 } 4596 4597 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4598 int localValue, int localChanges) { 4599 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 4600 args.seq = seq; 4601 args.globalVisibility = globalVisibility; 4602 args.localValue = localValue; 4603 args.localChanges = localChanges; 4604 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 4605 } 4606 4607 public void dispatchDoneAnimating() { 4608 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 4609 } 4610 4611 public void dispatchCheckFocus() { 4612 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 4613 // This will result in a call to checkFocus() below. 4614 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 4615 } 4616 } 4617 4618 /** 4619 * Post a callback to send a 4620 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4621 * This event is send at most once every 4622 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 4623 */ 4624 private void postSendWindowContentChangedCallback(View source) { 4625 if (mSendWindowContentChangedAccessibilityEvent == null) { 4626 mSendWindowContentChangedAccessibilityEvent = 4627 new SendWindowContentChangedAccessibilityEvent(); 4628 } 4629 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource; 4630 if (oldSource == null) { 4631 mSendWindowContentChangedAccessibilityEvent.mSource = source; 4632 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 4633 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 4634 } else { 4635 mSendWindowContentChangedAccessibilityEvent.mSource = 4636 getCommonPredecessor(oldSource, source); 4637 } 4638 } 4639 4640 /** 4641 * Remove a posted callback to send a 4642 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4643 */ 4644 private void removeSendWindowContentChangedCallback() { 4645 if (mSendWindowContentChangedAccessibilityEvent != null) { 4646 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 4647 } 4648 } 4649 4650 public boolean showContextMenuForChild(View originalView) { 4651 return false; 4652 } 4653 4654 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 4655 return null; 4656 } 4657 4658 public void createContextMenu(ContextMenu menu) { 4659 } 4660 4661 public void childDrawableStateChanged(View child) { 4662 } 4663 4664 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 4665 if (mView == null) { 4666 return false; 4667 } 4668 // Intercept accessibility focus events fired by virtual nodes to keep 4669 // track of accessibility focus position in such nodes. 4670 final int eventType = event.getEventType(); 4671 switch (eventType) { 4672 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 4673 final long sourceNodeId = event.getSourceNodeId(); 4674 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 4675 sourceNodeId); 4676 View source = mView.findViewByAccessibilityId(accessibilityViewId); 4677 if (source != null) { 4678 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 4679 if (provider != null) { 4680 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo( 4681 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId)); 4682 setAccessibilityFocus(source, node); 4683 } 4684 } 4685 } break; 4686 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 4687 final long sourceNodeId = event.getSourceNodeId(); 4688 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 4689 sourceNodeId); 4690 View source = mView.findViewByAccessibilityId(accessibilityViewId); 4691 if (source != null) { 4692 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 4693 if (provider != null) { 4694 setAccessibilityFocus(null, null); 4695 } 4696 } 4697 } break; 4698 } 4699 mAccessibilityManager.sendAccessibilityEvent(event); 4700 return true; 4701 } 4702 4703 @Override 4704 public void childAccessibilityStateChanged(View child) { 4705 postSendWindowContentChangedCallback(child); 4706 } 4707 4708 private View getCommonPredecessor(View first, View second) { 4709 if (mAttachInfo != null) { 4710 if (mTempHashSet == null) { 4711 mTempHashSet = new HashSet<View>(); 4712 } 4713 HashSet<View> seen = mTempHashSet; 4714 seen.clear(); 4715 View firstCurrent = first; 4716 while (firstCurrent != null) { 4717 seen.add(firstCurrent); 4718 ViewParent firstCurrentParent = firstCurrent.mParent; 4719 if (firstCurrentParent instanceof View) { 4720 firstCurrent = (View) firstCurrentParent; 4721 } else { 4722 firstCurrent = null; 4723 } 4724 } 4725 View secondCurrent = second; 4726 while (secondCurrent != null) { 4727 if (seen.contains(secondCurrent)) { 4728 seen.clear(); 4729 return secondCurrent; 4730 } 4731 ViewParent secondCurrentParent = secondCurrent.mParent; 4732 if (secondCurrentParent instanceof View) { 4733 secondCurrent = (View) secondCurrentParent; 4734 } else { 4735 secondCurrent = null; 4736 } 4737 } 4738 seen.clear(); 4739 } 4740 return null; 4741 } 4742 4743 void checkThread() { 4744 if (mThread != Thread.currentThread()) { 4745 throw new CalledFromWrongThreadException( 4746 "Only the original thread that created a view hierarchy can touch its views."); 4747 } 4748 } 4749 4750 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4751 // ViewAncestor never intercepts touch event, so this can be a no-op 4752 } 4753 4754 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 4755 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 4756 if (rectangle != null) { 4757 mTempRect.set(rectangle); 4758 mTempRect.offset(0, -mCurScrollY); 4759 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4760 try { 4761 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate); 4762 } catch (RemoteException re) { 4763 /* ignore */ 4764 } 4765 } 4766 return scrolled; 4767 } 4768 4769 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 4770 // Do nothing. 4771 } 4772 4773 class TakenSurfaceHolder extends BaseSurfaceHolder { 4774 @Override 4775 public boolean onAllowLockCanvas() { 4776 return mDrawingAllowed; 4777 } 4778 4779 @Override 4780 public void onRelayoutContainer() { 4781 // Not currently interesting -- from changing between fixed and layout size. 4782 } 4783 4784 public void setFormat(int format) { 4785 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4786 } 4787 4788 public void setType(int type) { 4789 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4790 } 4791 4792 @Override 4793 public void onUpdateSurface() { 4794 // We take care of format and type changes on our own. 4795 throw new IllegalStateException("Shouldn't be here"); 4796 } 4797 4798 public boolean isCreating() { 4799 return mIsCreating; 4800 } 4801 4802 @Override 4803 public void setFixedSize(int width, int height) { 4804 throw new UnsupportedOperationException( 4805 "Currently only support sizing from layout"); 4806 } 4807 4808 public void setKeepScreenOn(boolean screenOn) { 4809 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4810 } 4811 } 4812 4813 static final class InputMethodCallback implements InputMethodManager.FinishedEventCallback { 4814 private WeakReference<ViewRootImpl> mViewAncestor; 4815 4816 public InputMethodCallback(ViewRootImpl viewAncestor) { 4817 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4818 } 4819 4820 @Override 4821 public void finishedEvent(int seq, boolean handled) { 4822 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4823 if (viewAncestor != null) { 4824 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4825 } 4826 } 4827 } 4828 4829 static class W extends IWindow.Stub { 4830 private final WeakReference<ViewRootImpl> mViewAncestor; 4831 private final IWindowSession mWindowSession; 4832 4833 W(ViewRootImpl viewAncestor) { 4834 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4835 mWindowSession = viewAncestor.mWindowSession; 4836 } 4837 4838 public void resized(Rect frame, Rect contentInsets, 4839 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4840 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4841 if (viewAncestor != null) { 4842 viewAncestor.dispatchResized(frame, contentInsets, 4843 visibleInsets, reportDraw, newConfig); 4844 } 4845 } 4846 4847 @Override 4848 public void moved(int newX, int newY) { 4849 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4850 if (viewAncestor != null) { 4851 viewAncestor.dispatchMoved(newX, newY); 4852 } 4853 } 4854 4855 public void dispatchAppVisibility(boolean visible) { 4856 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4857 if (viewAncestor != null) { 4858 viewAncestor.dispatchAppVisibility(visible); 4859 } 4860 } 4861 4862 public void dispatchScreenState(boolean on) { 4863 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4864 if (viewAncestor != null) { 4865 viewAncestor.dispatchScreenStateChange(on); 4866 } 4867 } 4868 4869 public void dispatchGetNewSurface() { 4870 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4871 if (viewAncestor != null) { 4872 viewAncestor.dispatchGetNewSurface(); 4873 } 4874 } 4875 4876 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4877 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4878 if (viewAncestor != null) { 4879 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4880 } 4881 } 4882 4883 private static int checkCallingPermission(String permission) { 4884 try { 4885 return ActivityManagerNative.getDefault().checkPermission( 4886 permission, Binder.getCallingPid(), Binder.getCallingUid()); 4887 } catch (RemoteException e) { 4888 return PackageManager.PERMISSION_DENIED; 4889 } 4890 } 4891 4892 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 4893 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4894 if (viewAncestor != null) { 4895 final View view = viewAncestor.mView; 4896 if (view != null) { 4897 if (checkCallingPermission(Manifest.permission.DUMP) != 4898 PackageManager.PERMISSION_GRANTED) { 4899 throw new SecurityException("Insufficient permissions to invoke" 4900 + " executeCommand() from pid=" + Binder.getCallingPid() 4901 + ", uid=" + Binder.getCallingUid()); 4902 } 4903 4904 OutputStream clientStream = null; 4905 try { 4906 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 4907 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 4908 } catch (IOException e) { 4909 e.printStackTrace(); 4910 } finally { 4911 if (clientStream != null) { 4912 try { 4913 clientStream.close(); 4914 } catch (IOException e) { 4915 e.printStackTrace(); 4916 } 4917 } 4918 } 4919 } 4920 } 4921 } 4922 4923 public void closeSystemDialogs(String reason) { 4924 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4925 if (viewAncestor != null) { 4926 viewAncestor.dispatchCloseSystemDialogs(reason); 4927 } 4928 } 4929 4930 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 4931 boolean sync) { 4932 if (sync) { 4933 try { 4934 mWindowSession.wallpaperOffsetsComplete(asBinder()); 4935 } catch (RemoteException e) { 4936 } 4937 } 4938 } 4939 4940 public void dispatchWallpaperCommand(String action, int x, int y, 4941 int z, Bundle extras, boolean sync) { 4942 if (sync) { 4943 try { 4944 mWindowSession.wallpaperCommandComplete(asBinder(), null); 4945 } catch (RemoteException e) { 4946 } 4947 } 4948 } 4949 4950 /* Drag/drop */ 4951 public void dispatchDragEvent(DragEvent event) { 4952 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4953 if (viewAncestor != null) { 4954 viewAncestor.dispatchDragEvent(event); 4955 } 4956 } 4957 4958 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4959 int localValue, int localChanges) { 4960 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4961 if (viewAncestor != null) { 4962 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 4963 localValue, localChanges); 4964 } 4965 } 4966 4967 public void doneAnimating() { 4968 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4969 if (viewAncestor != null) { 4970 viewAncestor.dispatchDoneAnimating(); 4971 } 4972 } 4973 } 4974 4975 /** 4976 * Maintains state information for a single trackball axis, generating 4977 * discrete (DPAD) movements based on raw trackball motion. 4978 */ 4979 static final class TrackballAxis { 4980 /** 4981 * The maximum amount of acceleration we will apply. 4982 */ 4983 static final float MAX_ACCELERATION = 20; 4984 4985 /** 4986 * The maximum amount of time (in milliseconds) between events in order 4987 * for us to consider the user to be doing fast trackball movements, 4988 * and thus apply an acceleration. 4989 */ 4990 static final long FAST_MOVE_TIME = 150; 4991 4992 /** 4993 * Scaling factor to the time (in milliseconds) between events to how 4994 * much to multiple/divide the current acceleration. When movement 4995 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4996 * FAST_MOVE_TIME it divides it. 4997 */ 4998 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4999 5000 float position; 5001 float absPosition; 5002 float acceleration = 1; 5003 long lastMoveTime = 0; 5004 int step; 5005 int dir; 5006 int nonAccelMovement; 5007 5008 void reset(int _step) { 5009 position = 0; 5010 acceleration = 1; 5011 lastMoveTime = 0; 5012 step = _step; 5013 dir = 0; 5014 } 5015 5016 /** 5017 * Add trackball movement into the state. If the direction of movement 5018 * has been reversed, the state is reset before adding the 5019 * movement (so that you don't have to compensate for any previously 5020 * collected movement before see the result of the movement in the 5021 * new direction). 5022 * 5023 * @return Returns the absolute value of the amount of movement 5024 * collected so far. 5025 */ 5026 float collect(float off, long time, String axis) { 5027 long normTime; 5028 if (off > 0) { 5029 normTime = (long)(off * FAST_MOVE_TIME); 5030 if (dir < 0) { 5031 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 5032 position = 0; 5033 step = 0; 5034 acceleration = 1; 5035 lastMoveTime = 0; 5036 } 5037 dir = 1; 5038 } else if (off < 0) { 5039 normTime = (long)((-off) * FAST_MOVE_TIME); 5040 if (dir > 0) { 5041 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 5042 position = 0; 5043 step = 0; 5044 acceleration = 1; 5045 lastMoveTime = 0; 5046 } 5047 dir = -1; 5048 } else { 5049 normTime = 0; 5050 } 5051 5052 // The number of milliseconds between each movement that is 5053 // considered "normal" and will not result in any acceleration 5054 // or deceleration, scaled by the offset we have here. 5055 if (normTime > 0) { 5056 long delta = time - lastMoveTime; 5057 lastMoveTime = time; 5058 float acc = acceleration; 5059 if (delta < normTime) { 5060 // The user is scrolling rapidly, so increase acceleration. 5061 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 5062 if (scale > 1) acc *= scale; 5063 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 5064 + off + " normTime=" + normTime + " delta=" + delta 5065 + " scale=" + scale + " acc=" + acc); 5066 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 5067 } else { 5068 // The user is scrolling slowly, so decrease acceleration. 5069 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 5070 if (scale > 1) acc /= scale; 5071 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 5072 + off + " normTime=" + normTime + " delta=" + delta 5073 + " scale=" + scale + " acc=" + acc); 5074 acceleration = acc > 1 ? acc : 1; 5075 } 5076 } 5077 position += off; 5078 return (absPosition = Math.abs(position)); 5079 } 5080 5081 /** 5082 * Generate the number of discrete movement events appropriate for 5083 * the currently collected trackball movement. 5084 * 5085 * @param precision The minimum movement required to generate the 5086 * first discrete movement. 5087 * 5088 * @return Returns the number of discrete movements, either positive 5089 * or negative, or 0 if there is not enough trackball movement yet 5090 * for a discrete movement. 5091 */ 5092 int generate(float precision) { 5093 int movement = 0; 5094 nonAccelMovement = 0; 5095 do { 5096 final int dir = position >= 0 ? 1 : -1; 5097 switch (step) { 5098 // If we are going to execute the first step, then we want 5099 // to do this as soon as possible instead of waiting for 5100 // a full movement, in order to make things look responsive. 5101 case 0: 5102 if (absPosition < precision) { 5103 return movement; 5104 } 5105 movement += dir; 5106 nonAccelMovement += dir; 5107 step = 1; 5108 break; 5109 // If we have generated the first movement, then we need 5110 // to wait for the second complete trackball motion before 5111 // generating the second discrete movement. 5112 case 1: 5113 if (absPosition < 2) { 5114 return movement; 5115 } 5116 movement += dir; 5117 nonAccelMovement += dir; 5118 position += dir > 0 ? -2 : 2; 5119 absPosition = Math.abs(position); 5120 step = 2; 5121 break; 5122 // After the first two, we generate discrete movements 5123 // consistently with the trackball, applying an acceleration 5124 // if the trackball is moving quickly. This is a simple 5125 // acceleration on top of what we already compute based 5126 // on how quickly the wheel is being turned, to apply 5127 // a longer increasing acceleration to continuous movement 5128 // in one direction. 5129 default: 5130 if (absPosition < 1) { 5131 return movement; 5132 } 5133 movement += dir; 5134 position += dir >= 0 ? -1 : 1; 5135 absPosition = Math.abs(position); 5136 float acc = acceleration; 5137 acc *= 1.1f; 5138 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 5139 break; 5140 } 5141 } while (true); 5142 } 5143 } 5144 5145 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 5146 public CalledFromWrongThreadException(String msg) { 5147 super(msg); 5148 } 5149 } 5150 5151 private SurfaceHolder mHolder = new SurfaceHolder() { 5152 // we only need a SurfaceHolder for opengl. it would be nice 5153 // to implement everything else though, especially the callback 5154 // support (opengl doesn't make use of it right now, but eventually 5155 // will). 5156 public Surface getSurface() { 5157 return mSurface; 5158 } 5159 5160 public boolean isCreating() { 5161 return false; 5162 } 5163 5164 public void addCallback(Callback callback) { 5165 } 5166 5167 public void removeCallback(Callback callback) { 5168 } 5169 5170 public void setFixedSize(int width, int height) { 5171 } 5172 5173 public void setSizeFromLayout() { 5174 } 5175 5176 public void setFormat(int format) { 5177 } 5178 5179 public void setType(int type) { 5180 } 5181 5182 public void setKeepScreenOn(boolean screenOn) { 5183 } 5184 5185 public Canvas lockCanvas() { 5186 return null; 5187 } 5188 5189 public Canvas lockCanvas(Rect dirty) { 5190 return null; 5191 } 5192 5193 public void unlockCanvasAndPost(Canvas canvas) { 5194 } 5195 public Rect getSurfaceFrame() { 5196 return null; 5197 } 5198 }; 5199 5200 static RunQueue getRunQueue() { 5201 RunQueue rq = sRunQueues.get(); 5202 if (rq != null) { 5203 return rq; 5204 } 5205 rq = new RunQueue(); 5206 sRunQueues.set(rq); 5207 return rq; 5208 } 5209 5210 /** 5211 * The run queue is used to enqueue pending work from Views when no Handler is 5212 * attached. The work is executed during the next call to performTraversals on 5213 * the thread. 5214 * @hide 5215 */ 5216 static final class RunQueue { 5217 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 5218 5219 void post(Runnable action) { 5220 postDelayed(action, 0); 5221 } 5222 5223 void postDelayed(Runnable action, long delayMillis) { 5224 HandlerAction handlerAction = new HandlerAction(); 5225 handlerAction.action = action; 5226 handlerAction.delay = delayMillis; 5227 5228 synchronized (mActions) { 5229 mActions.add(handlerAction); 5230 } 5231 } 5232 5233 void removeCallbacks(Runnable action) { 5234 final HandlerAction handlerAction = new HandlerAction(); 5235 handlerAction.action = action; 5236 5237 synchronized (mActions) { 5238 final ArrayList<HandlerAction> actions = mActions; 5239 5240 while (actions.remove(handlerAction)) { 5241 // Keep going 5242 } 5243 } 5244 } 5245 5246 void executeActions(Handler handler) { 5247 synchronized (mActions) { 5248 final ArrayList<HandlerAction> actions = mActions; 5249 final int count = actions.size(); 5250 5251 for (int i = 0; i < count; i++) { 5252 final HandlerAction handlerAction = actions.get(i); 5253 handler.postDelayed(handlerAction.action, handlerAction.delay); 5254 } 5255 5256 actions.clear(); 5257 } 5258 } 5259 5260 private static class HandlerAction { 5261 Runnable action; 5262 long delay; 5263 5264 @Override 5265 public boolean equals(Object o) { 5266 if (this == o) return true; 5267 if (o == null || getClass() != o.getClass()) return false; 5268 5269 HandlerAction that = (HandlerAction) o; 5270 return !(action != null ? !action.equals(that.action) : that.action != null); 5271 5272 } 5273 5274 @Override 5275 public int hashCode() { 5276 int result = action != null ? action.hashCode() : 0; 5277 result = 31 * result + (int) (delay ^ (delay >>> 32)); 5278 return result; 5279 } 5280 } 5281 } 5282 5283 /** 5284 * Class for managing the accessibility interaction connection 5285 * based on the global accessibility state. 5286 */ 5287 final class AccessibilityInteractionConnectionManager 5288 implements AccessibilityStateChangeListener { 5289 public void onAccessibilityStateChanged(boolean enabled) { 5290 if (enabled) { 5291 ensureConnection(); 5292 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 5293 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 5294 View focusedView = mView.findFocus(); 5295 if (focusedView != null && focusedView != mView) { 5296 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5297 } 5298 } 5299 } else { 5300 ensureNoConnection(); 5301 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 5302 } 5303 } 5304 5305 public void ensureConnection() { 5306 if (mAttachInfo != null) { 5307 final boolean registered = 5308 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5309 if (!registered) { 5310 mAttachInfo.mAccessibilityWindowId = 5311 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 5312 new AccessibilityInteractionConnection(ViewRootImpl.this)); 5313 } 5314 } 5315 } 5316 5317 public void ensureNoConnection() { 5318 final boolean registered = 5319 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5320 if (registered) { 5321 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 5322 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 5323 } 5324 } 5325 } 5326 5327 /** 5328 * This class is an interface this ViewAncestor provides to the 5329 * AccessibilityManagerService to the latter can interact with 5330 * the view hierarchy in this ViewAncestor. 5331 */ 5332 static final class AccessibilityInteractionConnection 5333 extends IAccessibilityInteractionConnection.Stub { 5334 private final WeakReference<ViewRootImpl> mViewRootImpl; 5335 5336 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 5337 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 5338 } 5339 5340 @Override 5341 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 5342 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5343 int interrogatingPid, long interrogatingTid) { 5344 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5345 if (viewRootImpl != null && viewRootImpl.mView != null) { 5346 viewRootImpl.getAccessibilityInteractionController() 5347 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 5348 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5349 } else { 5350 // We cannot make the call and notify the caller so it does not wait. 5351 try { 5352 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5353 } catch (RemoteException re) { 5354 /* best effort - ignore */ 5355 } 5356 } 5357 } 5358 5359 @Override 5360 public void performAccessibilityAction(long accessibilityNodeId, int action, 5361 Bundle arguments, int interactionId, 5362 IAccessibilityInteractionConnectionCallback callback, int flags, 5363 int interogatingPid, long interrogatingTid) { 5364 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5365 if (viewRootImpl != null && viewRootImpl.mView != null) { 5366 viewRootImpl.getAccessibilityInteractionController() 5367 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 5368 interactionId, callback, flags, interogatingPid, interrogatingTid); 5369 } else { 5370 // We cannot make the call and notify the caller so it does not wait. 5371 try { 5372 callback.setPerformAccessibilityActionResult(false, interactionId); 5373 } catch (RemoteException re) { 5374 /* best effort - ignore */ 5375 } 5376 } 5377 } 5378 5379 @Override 5380 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId, 5381 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5382 int interrogatingPid, long interrogatingTid) { 5383 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5384 if (viewRootImpl != null && viewRootImpl.mView != null) { 5385 viewRootImpl.getAccessibilityInteractionController() 5386 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId, 5387 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5388 } else { 5389 // We cannot make the call and notify the caller so it does not wait. 5390 try { 5391 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5392 } catch (RemoteException re) { 5393 /* best effort - ignore */ 5394 } 5395 } 5396 } 5397 5398 @Override 5399 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 5400 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5401 int interrogatingPid, long interrogatingTid) { 5402 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5403 if (viewRootImpl != null && viewRootImpl.mView != null) { 5404 viewRootImpl.getAccessibilityInteractionController() 5405 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 5406 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5407 } else { 5408 // We cannot make the call and notify the caller so it does not wait. 5409 try { 5410 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5411 } catch (RemoteException re) { 5412 /* best effort - ignore */ 5413 } 5414 } 5415 } 5416 5417 @Override 5418 public void findFocus(long accessibilityNodeId, int focusType, int interactionId, 5419 IAccessibilityInteractionConnectionCallback callback, int flags, 5420 int interrogatingPid, long interrogatingTid) { 5421 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5422 if (viewRootImpl != null && viewRootImpl.mView != null) { 5423 viewRootImpl.getAccessibilityInteractionController() 5424 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback, 5425 flags, interrogatingPid, interrogatingTid); 5426 } else { 5427 // We cannot make the call and notify the caller so it does not wait. 5428 try { 5429 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5430 } catch (RemoteException re) { 5431 /* best effort - ignore */ 5432 } 5433 } 5434 } 5435 5436 @Override 5437 public void focusSearch(long accessibilityNodeId, int direction, int interactionId, 5438 IAccessibilityInteractionConnectionCallback callback, int flags, 5439 int interrogatingPid, long interrogatingTid) { 5440 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5441 if (viewRootImpl != null && viewRootImpl.mView != null) { 5442 viewRootImpl.getAccessibilityInteractionController() 5443 .focusSearchClientThread(accessibilityNodeId, direction, interactionId, 5444 callback, flags, interrogatingPid, interrogatingTid); 5445 } else { 5446 // We cannot make the call and notify the caller so it does not wait. 5447 try { 5448 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5449 } catch (RemoteException re) { 5450 /* best effort - ignore */ 5451 } 5452 } 5453 } 5454 } 5455 5456 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 5457 public View mSource; 5458 5459 public void run() { 5460 if (mSource != null) { 5461 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 5462 mSource.resetAccessibilityStateChanged(); 5463 mSource = null; 5464 } 5465 } 5466 } 5467} 5468