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