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