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