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