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