ViewRootImpl.java revision 3b84206bba19ae2bc9decef6a88f97951c2a205c
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.os.UserHandle; 56import android.util.AndroidRuntimeException; 57import android.util.DisplayMetrics; 58import android.util.Log; 59import android.util.Slog; 60import android.util.TypedValue; 61import android.view.View.AttachInfo; 62import android.view.View.MeasureSpec; 63import android.view.accessibility.AccessibilityEvent; 64import android.view.accessibility.AccessibilityManager; 65import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener; 66import android.view.accessibility.AccessibilityNodeInfo; 67import android.view.accessibility.AccessibilityNodeProvider; 68import android.view.accessibility.IAccessibilityInteractionConnection; 69import android.view.accessibility.IAccessibilityInteractionConnectionCallback; 70import android.view.animation.AccelerateDecelerateInterpolator; 71import android.view.animation.Interpolator; 72import android.view.inputmethod.InputConnection; 73import android.view.inputmethod.InputMethodManager; 74import android.widget.Scroller; 75 76import com.android.internal.R; 77import com.android.internal.os.SomeArgs; 78import com.android.internal.policy.PolicyManager; 79import com.android.internal.view.BaseSurfaceHolder; 80import com.android.internal.view.RootViewSurfaceTaker; 81 82import java.io.IOException; 83import java.io.OutputStream; 84import java.lang.ref.WeakReference; 85import java.util.ArrayList; 86import java.util.HashSet; 87 88/** 89 * The top of a view hierarchy, implementing the needed protocol between View 90 * and the WindowManager. This is for the most part an internal implementation 91 * detail of {@link WindowManagerGlobal}. 92 * 93 * {@hide} 94 */ 95@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"}) 96public final class ViewRootImpl implements ViewParent, 97 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks { 98 private static final String TAG = "ViewRootImpl"; 99 private static final boolean DBG = false; 100 private static final boolean LOCAL_LOGV = false; 101 /** @noinspection PointlessBooleanExpression*/ 102 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV; 103 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV; 104 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV; 105 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV; 106 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV; 107 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV; 108 private static final boolean DEBUG_IMF = false || LOCAL_LOGV; 109 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV; 110 private static final boolean DEBUG_FPS = false; 111 112 private static final boolean USE_RENDER_THREAD = false; 113 114 /** 115 * Set this system property to true to force the view hierarchy to render 116 * at 60 Hz. This can be used to measure the potential framerate. 117 */ 118 private static final String PROPERTY_PROFILE_RENDERING = "viewancestor.profile_rendering"; 119 120 private static final boolean MEASURE_LATENCY = false; 121 private static LatencyTimer lt; 122 123 /** 124 * Maximum time we allow the user to roll the trackball enough to generate 125 * a key event, before resetting the counters. 126 */ 127 static final int MAX_TRACKBALL_DELAY = 250; 128 129 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>(); 130 131 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>(); 132 static boolean sFirstDrawComplete = false; 133 134 static final ArrayList<ComponentCallbacks> sConfigCallbacks 135 = new ArrayList<ComponentCallbacks>(); 136 137 private static boolean sUseRenderThread = false; 138 private static boolean sRenderThreadQueried = false; 139 private static final Object[] sRenderThreadQueryLock = new Object[0]; 140 141 final IWindowSession mWindowSession; 142 final Display mDisplay; 143 144 long mLastTrackballTime = 0; 145 final TrackballAxis mTrackballAxisX = new TrackballAxis(); 146 final TrackballAxis mTrackballAxisY = new TrackballAxis(); 147 148 int mLastJoystickXDirection; 149 int mLastJoystickYDirection; 150 int mLastJoystickXKeyCode; 151 int mLastJoystickYKeyCode; 152 153 final int[] mTmpLocation = new int[2]; 154 155 final TypedValue mTmpValue = new TypedValue(); 156 157 final InputMethodCallback mInputMethodCallback; 158 final Thread mThread; 159 160 final WindowLeaked mLocation; 161 162 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams(); 163 164 final W mWindow; 165 166 final int mTargetSdkVersion; 167 168 int mSeq; 169 170 View mView; 171 View mFocusedView; 172 View mRealFocusedView; // this is not set to null in touch mode 173 View mOldFocusedView; 174 175 View mAccessibilityFocusedHost; 176 AccessibilityNodeInfo mAccessibilityFocusedVirtualView; 177 178 int mViewVisibility; 179 boolean mAppVisible = true; 180 int mOrigWindowType = -1; 181 182 // Set to true if the owner of this window is in the stopped state, 183 // so the window should no longer be active. 184 boolean mStopped = false; 185 186 boolean mLastInCompatMode = false; 187 188 SurfaceHolder.Callback2 mSurfaceHolderCallback; 189 BaseSurfaceHolder mSurfaceHolder; 190 boolean mIsCreating; 191 boolean mDrawingAllowed; 192 193 final Region mTransparentRegion; 194 final Region mPreviousTransparentRegion; 195 196 int mWidth; 197 int mHeight; 198 Rect mDirty; 199 final Rect mCurrentDirty = new Rect(); 200 final Rect mPreviousDirty = new Rect(); 201 boolean mIsAnimating; 202 203 CompatibilityInfo.Translator mTranslator; 204 205 final View.AttachInfo mAttachInfo; 206 InputChannel mInputChannel; 207 InputQueue.Callback mInputQueueCallback; 208 InputQueue mInputQueue; 209 FallbackEventHandler mFallbackEventHandler; 210 Choreographer mChoreographer; 211 212 final Rect mTempRect; // used in the transaction to not thrash the heap. 213 final Rect mVisRect; // used to retrieve visible rect of focused view. 214 215 boolean mTraversalScheduled; 216 int mTraversalBarrier; 217 boolean mWillDrawSoon; 218 /** Set to true while in performTraversals for detecting when die(true) is called from internal 219 * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */ 220 boolean mIsInTraversal; 221 boolean mFitSystemWindowsRequested; 222 boolean mLayoutRequested; 223 boolean mFirst; 224 boolean mReportNextDraw; 225 boolean mFullRedrawNeeded; 226 boolean mNewSurfaceNeeded; 227 boolean mHasHadWindowFocus; 228 boolean mLastWasImTarget; 229 boolean mWindowsAnimating; 230 boolean mIsDrawing; 231 int mLastSystemUiVisibility; 232 int mClientWindowLayoutFlags; 233 234 // Pool of queued input events. 235 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10; 236 private QueuedInputEvent mQueuedInputEventPool; 237 private int mQueuedInputEventPoolSize; 238 239 // Input event queue. 240 QueuedInputEvent mFirstPendingInputEvent; 241 QueuedInputEvent mCurrentInputEvent; 242 boolean mProcessInputEventsScheduled; 243 244 boolean mWindowAttributesChanged = false; 245 int mWindowAttributesChangesFlag = 0; 246 247 // These can be accessed by any thread, must be protected with a lock. 248 // Surface can never be reassigned or cleared (use Surface.clear()). 249 private final Surface mSurface = new Surface(); 250 251 boolean mAdded; 252 boolean mAddedTouchMode; 253 254 final CompatibilityInfoHolder mCompatibilityInfo; 255 256 // These are accessed by multiple threads. 257 final Rect mWinFrame; // frame given by window manager. 258 259 final Rect mPendingVisibleInsets = new Rect(); 260 final Rect mPendingContentInsets = new Rect(); 261 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets 262 = new ViewTreeObserver.InternalInsetsInfo(); 263 264 final Rect mFitSystemWindowsInsets = new Rect(); 265 266 final Configuration mLastConfiguration = new Configuration(); 267 final Configuration mPendingConfiguration = new Configuration(); 268 269 boolean mScrollMayChange; 270 int mSoftInputMode; 271 View mLastScrolledFocus; 272 int mScrollY; 273 int mCurScrollY; 274 Scroller mScroller; 275 HardwareLayer mResizeBuffer; 276 long mResizeBufferStartTime; 277 int mResizeBufferDuration; 278 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator(); 279 private ArrayList<LayoutTransition> mPendingTransitions; 280 281 final ViewConfiguration mViewConfiguration; 282 283 /* Drag/drop */ 284 ClipDescription mDragDescription; 285 View mCurrentDragView; 286 volatile Object mLocalDragState; 287 final PointF mDragPoint = new PointF(); 288 final PointF mLastTouchPoint = new PointF(); 289 290 private boolean mProfileRendering; 291 private Thread mRenderProfiler; 292 private volatile boolean mRenderProfilingEnabled; 293 294 // Variables to track frames per second, enabled via DEBUG_FPS flag 295 private long mFpsStartTime = -1; 296 private long mFpsPrevTime = -1; 297 private int mFpsNumFrames; 298 299 private final ArrayList<DisplayList> mDisplayLists = new ArrayList<DisplayList>(24); 300 301 /** 302 * see {@link #playSoundEffect(int)} 303 */ 304 AudioManager mAudioManager; 305 306 final AccessibilityManager mAccessibilityManager; 307 308 AccessibilityInteractionController mAccessibilityInteractionController; 309 310 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager; 311 312 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent; 313 314 HashSet<View> mTempHashSet; 315 316 private final int mDensity; 317 private final int mNoncompatDensity; 318 319 /** 320 * Consistency verifier for debugging purposes. 321 */ 322 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 323 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 324 new InputEventConsistencyVerifier(this, 0) : null; 325 326 static final class SystemUiVisibilityInfo { 327 int seq; 328 int globalVisibility; 329 int localValue; 330 int localChanges; 331 } 332 333 public ViewRootImpl(Context context, Display display) { 334 super(); 335 336 if (MEASURE_LATENCY) { 337 if (lt == null) { 338 lt = new LatencyTimer(100, 1000); 339 } 340 } 341 342 // Initialize the statics when this class is first instantiated. This is 343 // done here instead of in the static block because Zygote does not 344 // allow the spawning of threads. 345 mWindowSession = WindowManagerGlobal.getWindowSession(context.getMainLooper()); 346 mDisplay = display; 347 348 CompatibilityInfoHolder cih = display.getCompatibilityInfo(); 349 mCompatibilityInfo = cih != null ? cih : new CompatibilityInfoHolder(); 350 351 mThread = Thread.currentThread(); 352 mLocation = new WindowLeaked(null); 353 mLocation.fillInStackTrace(); 354 mWidth = -1; 355 mHeight = -1; 356 mDirty = new Rect(); 357 mTempRect = new Rect(); 358 mVisRect = new Rect(); 359 mWinFrame = new Rect(); 360 mWindow = new W(this); 361 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion; 362 mInputMethodCallback = new InputMethodCallback(this); 363 mViewVisibility = View.GONE; 364 mTransparentRegion = new Region(); 365 mPreviousTransparentRegion = new Region(); 366 mFirst = true; // true for the first time the view is added 367 mAdded = false; 368 mAccessibilityManager = AccessibilityManager.getInstance(context); 369 mAccessibilityInteractionConnectionManager = 370 new AccessibilityInteractionConnectionManager(); 371 mAccessibilityManager.addAccessibilityStateChangeListener( 372 mAccessibilityInteractionConnectionManager); 373 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this); 374 mViewConfiguration = ViewConfiguration.get(context); 375 mDensity = context.getResources().getDisplayMetrics().densityDpi; 376 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi; 377 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context); 378 mProfileRendering = Boolean.parseBoolean( 379 SystemProperties.get(PROPERTY_PROFILE_RENDERING, "false")); 380 mChoreographer = Choreographer.getInstance(); 381 382 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 383 mAttachInfo.mScreenOn = powerManager.isScreenOn(); 384 loadSystemProperties(); 385 } 386 387 /** 388 * @return True if the application requests the use of a separate render thread, 389 * false otherwise 390 */ 391 private static boolean isRenderThreadRequested(Context context) { 392 if (USE_RENDER_THREAD) { 393 synchronized (sRenderThreadQueryLock) { 394 if (!sRenderThreadQueried) { 395 final PackageManager packageManager = context.getPackageManager(); 396 final String packageName = context.getApplicationInfo().packageName; 397 try { 398 ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 399 PackageManager.GET_META_DATA); 400 if (applicationInfo.metaData != null) { 401 sUseRenderThread = applicationInfo.metaData.getBoolean( 402 "android.graphics.renderThread", false); 403 } 404 } catch (PackageManager.NameNotFoundException e) { 405 } finally { 406 sRenderThreadQueried = true; 407 } 408 } 409 return sUseRenderThread; 410 } 411 } else { 412 return false; 413 } 414 } 415 416 public static void addFirstDrawHandler(Runnable callback) { 417 synchronized (sFirstDrawHandlers) { 418 if (!sFirstDrawComplete) { 419 sFirstDrawHandlers.add(callback); 420 } 421 } 422 } 423 424 public static void addConfigCallback(ComponentCallbacks callback) { 425 synchronized (sConfigCallbacks) { 426 sConfigCallbacks.add(callback); 427 } 428 } 429 430 // FIXME for perf testing only 431 private boolean mProfile = false; 432 433 /** 434 * Call this to profile the next traversal call. 435 * FIXME for perf testing only. Remove eventually 436 */ 437 public void profile() { 438 mProfile = true; 439 } 440 441 /** 442 * Indicates whether we are in touch mode. Calling this method triggers an IPC 443 * call and should be avoided whenever possible. 444 * 445 * @return True, if the device is in touch mode, false otherwise. 446 * 447 * @hide 448 */ 449 static boolean isInTouchMode() { 450 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession(); 451 if (windowSession != null) { 452 try { 453 return windowSession.getInTouchMode(); 454 } catch (RemoteException e) { 455 } 456 } 457 return false; 458 } 459 460 /** 461 * We have one child 462 */ 463 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) { 464 synchronized (this) { 465 if (mView == null) { 466 mView = view; 467 mFallbackEventHandler.setView(view); 468 mWindowAttributes.copyFrom(attrs); 469 attrs = mWindowAttributes; 470 // Keep track of the actual window flags supplied by the client. 471 mClientWindowLayoutFlags = attrs.flags; 472 473 setAccessibilityFocus(null, null); 474 475 if (view instanceof RootViewSurfaceTaker) { 476 mSurfaceHolderCallback = 477 ((RootViewSurfaceTaker)view).willYouTakeTheSurface(); 478 if (mSurfaceHolderCallback != null) { 479 mSurfaceHolder = new TakenSurfaceHolder(); 480 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN); 481 } 482 } 483 484 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 485 mTranslator = compatibilityInfo.getTranslator(); 486 487 // If the application owns the surface, don't enable hardware acceleration 488 if (mSurfaceHolder == null) { 489 enableHardwareAcceleration(mView.getContext(), attrs); 490 } 491 492 boolean restore = false; 493 if (mTranslator != null) { 494 mSurface.setCompatibilityTranslator(mTranslator); 495 restore = true; 496 attrs.backup(); 497 mTranslator.translateWindowLayout(attrs); 498 } 499 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs); 500 501 if (!compatibilityInfo.supportsScreen()) { 502 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 503 mLastInCompatMode = true; 504 } 505 506 mSoftInputMode = attrs.softInputMode; 507 mWindowAttributesChanged = true; 508 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED; 509 mAttachInfo.mRootView = view; 510 mAttachInfo.mScalingRequired = mTranslator != null; 511 mAttachInfo.mApplicationScale = 512 mTranslator == null ? 1.0f : mTranslator.applicationScale; 513 if (panelParentView != null) { 514 mAttachInfo.mPanelParentWindowToken 515 = panelParentView.getApplicationWindowToken(); 516 } 517 mAdded = true; 518 int res; /* = WindowManagerImpl.ADD_OKAY; */ 519 520 // Schedule the first layout -before- adding to the window 521 // manager, to make sure we do the relayout before receiving 522 // any other events from the system. 523 requestLayout(); 524 if ((mWindowAttributes.inputFeatures 525 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { 526 mInputChannel = new InputChannel(); 527 } 528 try { 529 mOrigWindowType = mWindowAttributes.type; 530 mAttachInfo.mRecomputeGlobalAttributes = true; 531 collectViewAttributes(); 532 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes, 533 getHostVisibility(), mDisplay.getDisplayId(), 534 mAttachInfo.mContentInsets, mInputChannel); 535 } catch (RemoteException e) { 536 mAdded = false; 537 mView = null; 538 mAttachInfo.mRootView = null; 539 mInputChannel = null; 540 mFallbackEventHandler.setView(null); 541 unscheduleTraversals(); 542 setAccessibilityFocus(null, null); 543 throw new RuntimeException("Adding window failed", e); 544 } finally { 545 if (restore) { 546 attrs.restore(); 547 } 548 } 549 550 if (mTranslator != null) { 551 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets); 552 } 553 mPendingContentInsets.set(mAttachInfo.mContentInsets); 554 mPendingVisibleInsets.set(0, 0, 0, 0); 555 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow); 556 if (res < WindowManagerGlobal.ADD_OKAY) { 557 mView = null; 558 mAttachInfo.mRootView = null; 559 mAdded = false; 560 mFallbackEventHandler.setView(null); 561 unscheduleTraversals(); 562 setAccessibilityFocus(null, null); 563 switch (res) { 564 case WindowManagerGlobal.ADD_BAD_APP_TOKEN: 565 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN: 566 throw new WindowManager.BadTokenException( 567 "Unable to add window -- token " + attrs.token 568 + " is not valid; is your activity running?"); 569 case WindowManagerGlobal.ADD_NOT_APP_TOKEN: 570 throw new WindowManager.BadTokenException( 571 "Unable to add window -- token " + attrs.token 572 + " is not for an application"); 573 case WindowManagerGlobal.ADD_APP_EXITING: 574 throw new WindowManager.BadTokenException( 575 "Unable to add window -- app for token " + attrs.token 576 + " is exiting"); 577 case WindowManagerGlobal.ADD_DUPLICATE_ADD: 578 throw new WindowManager.BadTokenException( 579 "Unable to add window -- window " + mWindow 580 + " has already been added"); 581 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED: 582 // Silently ignore -- we would have just removed it 583 // right away, anyway. 584 return; 585 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON: 586 throw new WindowManager.BadTokenException( 587 "Unable to add window " + mWindow + 588 " -- another window of this type already exists"); 589 case WindowManagerGlobal.ADD_PERMISSION_DENIED: 590 throw new WindowManager.BadTokenException( 591 "Unable to add window " + mWindow + 592 " -- permission denied for this window type"); 593 } 594 throw new RuntimeException( 595 "Unable to add window -- unknown error code " + res); 596 } 597 598 if (view instanceof RootViewSurfaceTaker) { 599 mInputQueueCallback = 600 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue(); 601 } 602 if (mInputChannel != null) { 603 if (mInputQueueCallback != null) { 604 mInputQueue = new InputQueue(mInputChannel); 605 mInputQueueCallback.onInputQueueCreated(mInputQueue); 606 } else { 607 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel, 608 Looper.myLooper()); 609 } 610 } 611 612 view.assignParent(this); 613 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0; 614 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0; 615 616 if (mAccessibilityManager.isEnabled()) { 617 mAccessibilityInteractionConnectionManager.ensureConnection(); 618 } 619 620 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 621 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES); 622 } 623 } 624 } 625 } 626 627 void destroyHardwareResources() { 628 if (mAttachInfo.mHardwareRenderer != null) { 629 if (mAttachInfo.mHardwareRenderer.isEnabled()) { 630 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 631 } 632 mAttachInfo.mHardwareRenderer.destroy(false); 633 } 634 } 635 636 void terminateHardwareResources() { 637 if (mAttachInfo.mHardwareRenderer != null) { 638 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView); 639 mAttachInfo.mHardwareRenderer.destroy(false); 640 } 641 } 642 643 void destroyHardwareLayers() { 644 if (mThread != Thread.currentThread()) { 645 if (mAttachInfo.mHardwareRenderer != null && 646 mAttachInfo.mHardwareRenderer.isEnabled()) { 647 HardwareRenderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE); 648 } 649 } else { 650 if (mAttachInfo.mHardwareRenderer != null && 651 mAttachInfo.mHardwareRenderer.isEnabled()) { 652 mAttachInfo.mHardwareRenderer.destroyLayers(mView); 653 } 654 } 655 } 656 657 void pushHardwareLayerUpdate(HardwareLayer layer) { 658 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 659 mAttachInfo.mHardwareRenderer.pushLayerUpdate(layer); 660 } 661 } 662 663 public boolean attachFunctor(int functor) { 664 //noinspection SimplifiableIfStatement 665 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) { 666 return mAttachInfo.mHardwareRenderer.attachFunctor(mAttachInfo, functor); 667 } 668 return false; 669 } 670 671 public void detachFunctor(int functor) { 672 if (mAttachInfo.mHardwareRenderer != null) { 673 mAttachInfo.mHardwareRenderer.detachFunctor(functor); 674 } 675 } 676 677 private void enableHardwareAcceleration(Context context, WindowManager.LayoutParams attrs) { 678 mAttachInfo.mHardwareAccelerated = false; 679 mAttachInfo.mHardwareAccelerationRequested = false; 680 681 // Don't enable hardware acceleration when the application is in compatibility mode 682 if (mTranslator != null) return; 683 684 // Try to enable hardware acceleration if requested 685 final boolean hardwareAccelerated = 686 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0; 687 688 if (hardwareAccelerated) { 689 if (!HardwareRenderer.isAvailable()) { 690 return; 691 } 692 693 // Persistent processes (including the system) should not do 694 // accelerated rendering on low-end devices. In that case, 695 // sRendererDisabled will be set. In addition, the system process 696 // itself should never do accelerated rendering. In that case, both 697 // sRendererDisabled and sSystemRendererDisabled are set. When 698 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED 699 // can be used by code on the system process to escape that and enable 700 // HW accelerated drawing. (This is basically for the lock screen.) 701 702 final boolean fakeHwAccelerated = (attrs.privateFlags & 703 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0; 704 final boolean forceHwAccelerated = (attrs.privateFlags & 705 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0; 706 707 if (!HardwareRenderer.sRendererDisabled || (HardwareRenderer.sSystemRendererDisabled 708 && forceHwAccelerated)) { 709 // Don't enable hardware acceleration when we're not on the main thread 710 if (!HardwareRenderer.sSystemRendererDisabled && 711 Looper.getMainLooper() != Looper.myLooper()) { 712 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware " 713 + "acceleration outside of the main thread, aborting"); 714 return; 715 } 716 717 final boolean renderThread = isRenderThreadRequested(context); 718 if (renderThread) { 719 Log.i(HardwareRenderer.LOG_TAG, "Render threat initiated"); 720 } 721 722 if (mAttachInfo.mHardwareRenderer != null) { 723 mAttachInfo.mHardwareRenderer.destroy(true); 724 } 725 726 final boolean translucent = attrs.format != PixelFormat.OPAQUE; 727 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent); 728 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested 729 = mAttachInfo.mHardwareRenderer != null; 730 731 } else if (fakeHwAccelerated) { 732 // The window had wanted to use hardware acceleration, but this 733 // is not allowed in its process. By setting this flag, it can 734 // still render as if it was accelerated. This is basically for 735 // the preview windows the window manager shows for launching 736 // applications, so they will look more like the app being launched. 737 mAttachInfo.mHardwareAccelerationRequested = true; 738 } 739 } 740 } 741 742 public View getView() { 743 return mView; 744 } 745 746 final WindowLeaked getLocation() { 747 return mLocation; 748 } 749 750 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) { 751 synchronized (this) { 752 int oldSoftInputMode = mWindowAttributes.softInputMode; 753 // Keep track of the actual window flags supplied by the client. 754 mClientWindowLayoutFlags = attrs.flags; 755 // preserve compatible window flag if exists. 756 int compatibleWindowFlag = 757 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 758 // transfer over system UI visibility values as they carry current state. 759 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility; 760 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility; 761 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs); 762 mWindowAttributes.flags |= compatibleWindowFlag; 763 764 applyKeepScreenOnFlag(mWindowAttributes); 765 766 if (newView) { 767 mSoftInputMode = attrs.softInputMode; 768 requestLayout(); 769 } 770 // Don't lose the mode we last auto-computed. 771 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 772 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 773 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode 774 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 775 | (oldSoftInputMode 776 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST); 777 } 778 mWindowAttributesChanged = true; 779 scheduleTraversals(); 780 } 781 } 782 783 void handleAppVisibility(boolean visible) { 784 if (mAppVisible != visible) { 785 mAppVisible = visible; 786 scheduleTraversals(); 787 } 788 } 789 790 void handleGetNewSurface() { 791 mNewSurfaceNeeded = true; 792 mFullRedrawNeeded = true; 793 scheduleTraversals(); 794 } 795 796 void handleScreenStateChange(boolean on) { 797 if (on != mAttachInfo.mScreenOn) { 798 mAttachInfo.mScreenOn = on; 799 if (mView != null) { 800 mView.dispatchScreenStateChanged(on ? View.SCREEN_STATE_ON : View.SCREEN_STATE_OFF); 801 } 802 if (on) { 803 mFullRedrawNeeded = true; 804 scheduleTraversals(); 805 } 806 } 807 } 808 809 /** 810 * {@inheritDoc} 811 */ 812 public void requestFitSystemWindows() { 813 checkThread(); 814 mFitSystemWindowsRequested = true; 815 scheduleTraversals(); 816 } 817 818 /** 819 * {@inheritDoc} 820 */ 821 public void requestLayout() { 822 checkThread(); 823 mLayoutRequested = true; 824 scheduleTraversals(); 825 } 826 827 /** 828 * {@inheritDoc} 829 */ 830 public boolean isLayoutRequested() { 831 return mLayoutRequested; 832 } 833 834 void invalidate() { 835 mDirty.set(0, 0, mWidth, mHeight); 836 scheduleTraversals(); 837 } 838 839 void invalidateWorld(View view) { 840 view.invalidate(); 841 if (view instanceof ViewGroup) { 842 ViewGroup parent = (ViewGroup) view; 843 for (int i = 0; i < parent.getChildCount(); i++) { 844 invalidateWorld(parent.getChildAt(i)); 845 } 846 } 847 } 848 849 public void invalidateChild(View child, Rect dirty) { 850 invalidateChildInParent(null, dirty); 851 } 852 853 public ViewParent invalidateChildInParent(int[] location, Rect dirty) { 854 checkThread(); 855 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty); 856 857 if (dirty == null) { 858 invalidate(); 859 return null; 860 } else if (dirty.isEmpty()) { 861 return null; 862 } 863 864 if (mCurScrollY != 0 || mTranslator != null) { 865 mTempRect.set(dirty); 866 dirty = mTempRect; 867 if (mCurScrollY != 0) { 868 dirty.offset(0, -mCurScrollY); 869 } 870 if (mTranslator != null) { 871 mTranslator.translateRectInAppWindowToScreen(dirty); 872 } 873 if (mAttachInfo.mScalingRequired) { 874 dirty.inset(-1, -1); 875 } 876 } 877 878 final Rect localDirty = mDirty; 879 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) { 880 mAttachInfo.mSetIgnoreDirtyState = true; 881 mAttachInfo.mIgnoreDirtyState = true; 882 } 883 884 // Add the new dirty rect to the current one 885 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom); 886 // Intersect with the bounds of the window to skip 887 // updates that lie outside of the visible region 888 final float appScale = mAttachInfo.mApplicationScale; 889 localDirty.intersect(0, 0, 890 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f)); 891 892 if (!mWillDrawSoon) { 893 scheduleTraversals(); 894 } 895 896 return null; 897 } 898 899 void setStopped(boolean stopped) { 900 if (mStopped != stopped) { 901 mStopped = stopped; 902 if (!stopped) { 903 scheduleTraversals(); 904 } 905 } 906 } 907 908 public ViewParent getParent() { 909 return null; 910 } 911 912 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 913 if (child != mView) { 914 throw new RuntimeException("child is not mine, honest!"); 915 } 916 // Note: don't apply scroll offset, because we want to know its 917 // visibility in the virtual canvas being given to the view hierarchy. 918 return r.intersect(0, 0, mWidth, mHeight); 919 } 920 921 public void bringChildToFront(View child) { 922 } 923 924 int getHostVisibility() { 925 return mAppVisible ? mView.getVisibility() : View.GONE; 926 } 927 928 void disposeResizeBuffer() { 929 if (mResizeBuffer != null) { 930 mResizeBuffer.destroy(); 931 mResizeBuffer = null; 932 } 933 } 934 935 /** 936 * Add LayoutTransition to the list of transitions to be started in the next traversal. 937 * This list will be cleared after the transitions on the list are start()'ed. These 938 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup 939 * happens during the layout phase of traversal, which we want to complete before any of the 940 * animations are started (because those animations may side-effect properties that layout 941 * depends upon, like the bounding rectangles of the affected views). So we add the transition 942 * to the list and it is started just prior to starting the drawing phase of traversal. 943 * 944 * @param transition The LayoutTransition to be started on the next traversal. 945 * 946 * @hide 947 */ 948 public void requestTransitionStart(LayoutTransition transition) { 949 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) { 950 if (mPendingTransitions == null) { 951 mPendingTransitions = new ArrayList<LayoutTransition>(); 952 } 953 mPendingTransitions.add(transition); 954 } 955 } 956 957 void scheduleTraversals() { 958 if (!mTraversalScheduled) { 959 mTraversalScheduled = true; 960 mTraversalBarrier = mHandler.getLooper().postSyncBarrier(); 961 mChoreographer.postCallback( 962 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 963 scheduleConsumeBatchedInput(); 964 } 965 } 966 967 void unscheduleTraversals() { 968 if (mTraversalScheduled) { 969 mTraversalScheduled = false; 970 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 971 mChoreographer.removeCallbacks( 972 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 973 } 974 } 975 976 void doTraversal() { 977 if (mTraversalScheduled) { 978 mTraversalScheduled = false; 979 mHandler.getLooper().removeSyncBarrier(mTraversalBarrier); 980 981 if (mProfile) { 982 Debug.startMethodTracing("ViewAncestor"); 983 } 984 985 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals"); 986 try { 987 performTraversals(); 988 } finally { 989 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 990 } 991 992 if (mProfile) { 993 Debug.stopMethodTracing(); 994 mProfile = false; 995 } 996 } 997 } 998 999 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) { 1000 // Update window's global keep screen on flag: if a view has requested 1001 // that the screen be kept on, then it is always set; otherwise, it is 1002 // set to whatever the client last requested for the global state. 1003 if (mAttachInfo.mKeepScreenOn) { 1004 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 1005 } else { 1006 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) 1007 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1008 } 1009 } 1010 1011 private boolean collectViewAttributes() { 1012 final View.AttachInfo attachInfo = mAttachInfo; 1013 if (attachInfo.mRecomputeGlobalAttributes) { 1014 //Log.i(TAG, "Computing view hierarchy attributes!"); 1015 attachInfo.mRecomputeGlobalAttributes = false; 1016 boolean oldScreenOn = attachInfo.mKeepScreenOn; 1017 attachInfo.mKeepScreenOn = false; 1018 attachInfo.mSystemUiVisibility = 0; 1019 attachInfo.mHasSystemUiListeners = false; 1020 mView.dispatchCollectViewAttributes(attachInfo, 0); 1021 attachInfo.mSystemUiVisibility &= ~attachInfo.mDisabledSystemUiVisibility; 1022 WindowManager.LayoutParams params = mWindowAttributes; 1023 if (attachInfo.mKeepScreenOn != oldScreenOn 1024 || attachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility 1025 || attachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) { 1026 applyKeepScreenOnFlag(params); 1027 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility; 1028 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners; 1029 mView.dispatchWindowSystemUiVisiblityChanged(attachInfo.mSystemUiVisibility); 1030 return true; 1031 } 1032 } 1033 return false; 1034 } 1035 1036 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp, 1037 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) { 1038 int childWidthMeasureSpec; 1039 int childHeightMeasureSpec; 1040 boolean windowSizeMayChange = false; 1041 1042 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG, 1043 "Measuring " + host + " in display " + desiredWindowWidth 1044 + "x" + desiredWindowHeight + "..."); 1045 1046 boolean goodMeasure = false; 1047 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) { 1048 // On large screens, we don't want to allow dialogs to just 1049 // stretch to fill the entire width of the screen to display 1050 // one line of text. First try doing the layout at a smaller 1051 // size to see if it will fit. 1052 final DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1053 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true); 1054 int baseSize = 0; 1055 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) { 1056 baseSize = (int)mTmpValue.getDimension(packageMetrics); 1057 } 1058 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize); 1059 if (baseSize != 0 && desiredWindowWidth > baseSize) { 1060 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1061 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1062 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1063 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1064 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1065 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1066 goodMeasure = true; 1067 } else { 1068 // Didn't fit in that size... try expanding a bit. 1069 baseSize = (baseSize+desiredWindowWidth)/2; 1070 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize=" 1071 + baseSize); 1072 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); 1073 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1074 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" 1075 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); 1076 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { 1077 if (DEBUG_DIALOG) Log.v(TAG, "Good!"); 1078 goodMeasure = true; 1079 } 1080 } 1081 } 1082 } 1083 1084 if (!goodMeasure) { 1085 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); 1086 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 1087 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 1088 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) { 1089 windowSizeMayChange = true; 1090 } 1091 } 1092 1093 if (DBG) { 1094 System.out.println("======================================"); 1095 System.out.println("performTraversals -- after measure"); 1096 host.debug(); 1097 } 1098 1099 return windowSizeMayChange; 1100 } 1101 1102 private void performTraversals() { 1103 // cache mView since it is used so much below... 1104 final View host = mView; 1105 1106 if (DBG) { 1107 System.out.println("======================================"); 1108 System.out.println("performTraversals"); 1109 host.debug(); 1110 } 1111 1112 if (host == null || !mAdded) 1113 return; 1114 1115 mIsInTraversal = true; 1116 mWillDrawSoon = true; 1117 boolean windowSizeMayChange = false; 1118 boolean newSurface = false; 1119 boolean surfaceChanged = false; 1120 WindowManager.LayoutParams lp = mWindowAttributes; 1121 1122 int desiredWindowWidth; 1123 int desiredWindowHeight; 1124 1125 final View.AttachInfo attachInfo = mAttachInfo; 1126 1127 final int viewVisibility = getHostVisibility(); 1128 boolean viewVisibilityChanged = mViewVisibility != viewVisibility 1129 || mNewSurfaceNeeded; 1130 1131 WindowManager.LayoutParams params = null; 1132 if (mWindowAttributesChanged) { 1133 mWindowAttributesChanged = false; 1134 surfaceChanged = true; 1135 params = lp; 1136 } 1137 CompatibilityInfo compatibilityInfo = mCompatibilityInfo.get(); 1138 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) { 1139 params = lp; 1140 mFullRedrawNeeded = true; 1141 mLayoutRequested = true; 1142 if (mLastInCompatMode) { 1143 params.flags &= ~WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1144 mLastInCompatMode = false; 1145 } else { 1146 params.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 1147 mLastInCompatMode = true; 1148 } 1149 } 1150 1151 mWindowAttributesChangesFlag = 0; 1152 1153 Rect frame = mWinFrame; 1154 if (mFirst) { 1155 mFullRedrawNeeded = true; 1156 mLayoutRequested = true; 1157 1158 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1159 // NOTE -- system code, won't try to do compat mode. 1160 Point size = new Point(); 1161 mDisplay.getRealSize(size); 1162 desiredWindowWidth = size.x; 1163 desiredWindowHeight = size.y; 1164 } else { 1165 DisplayMetrics packageMetrics = 1166 mView.getContext().getResources().getDisplayMetrics(); 1167 desiredWindowWidth = packageMetrics.widthPixels; 1168 desiredWindowHeight = packageMetrics.heightPixels; 1169 } 1170 1171 // For the very first time, tell the view hierarchy that it 1172 // is attached to the window. Note that at this point the surface 1173 // object is not initialized to its backing store, but soon it 1174 // will be (assuming the window is visible). 1175 attachInfo.mSurface = mSurface; 1176 // We used to use the following condition to choose 32 bits drawing caches: 1177 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888 1178 // However, windows are now always 32 bits by default, so choose 32 bits 1179 attachInfo.mUse32BitDrawingCache = true; 1180 attachInfo.mHasWindowFocus = false; 1181 attachInfo.mWindowVisibility = viewVisibility; 1182 attachInfo.mRecomputeGlobalAttributes = false; 1183 viewVisibilityChanged = false; 1184 mLastConfiguration.setTo(host.getResources().getConfiguration()); 1185 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1186 host.dispatchAttachedToWindow(attachInfo, 0); 1187 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets); 1188 host.fitSystemWindows(mFitSystemWindowsInsets); 1189 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn); 1190 1191 } else { 1192 desiredWindowWidth = frame.width(); 1193 desiredWindowHeight = frame.height(); 1194 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) { 1195 if (DEBUG_ORIENTATION) Log.v(TAG, 1196 "View " + host + " resized to: " + frame); 1197 mFullRedrawNeeded = true; 1198 mLayoutRequested = true; 1199 windowSizeMayChange = true; 1200 } 1201 } 1202 1203 if (viewVisibilityChanged) { 1204 attachInfo.mWindowVisibility = viewVisibility; 1205 host.dispatchWindowVisibilityChanged(viewVisibility); 1206 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) { 1207 destroyHardwareResources(); 1208 } 1209 if (viewVisibility == View.GONE) { 1210 // After making a window gone, we will count it as being 1211 // shown for the first time the next time it gets focus. 1212 mHasHadWindowFocus = false; 1213 } 1214 } 1215 1216 // Execute enqueued actions on every traversal in case a detached view enqueued an action 1217 getRunQueue().executeActions(attachInfo.mHandler); 1218 1219 boolean insetsChanged = false; 1220 1221 boolean layoutRequested = mLayoutRequested && !mStopped; 1222 if (layoutRequested) { 1223 1224 final Resources res = mView.getContext().getResources(); 1225 1226 if (mFirst) { 1227 // make sure touch mode code executes by setting cached value 1228 // to opposite of the added touch mode. 1229 mAttachInfo.mInTouchMode = !mAddedTouchMode; 1230 ensureTouchModeLocally(mAddedTouchMode); 1231 } else { 1232 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) { 1233 insetsChanged = true; 1234 } 1235 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) { 1236 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1237 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1238 + mAttachInfo.mVisibleInsets); 1239 } 1240 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT 1241 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) { 1242 windowSizeMayChange = true; 1243 1244 if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL) { 1245 // NOTE -- system code, won't try to do compat mode. 1246 Point size = new Point(); 1247 mDisplay.getRealSize(size); 1248 desiredWindowWidth = size.x; 1249 desiredWindowHeight = size.y; 1250 } else { 1251 DisplayMetrics packageMetrics = res.getDisplayMetrics(); 1252 desiredWindowWidth = packageMetrics.widthPixels; 1253 desiredWindowHeight = packageMetrics.heightPixels; 1254 } 1255 } 1256 } 1257 1258 // Ask host how big it wants to be 1259 windowSizeMayChange |= measureHierarchy(host, lp, res, 1260 desiredWindowWidth, desiredWindowHeight); 1261 } 1262 1263 if (collectViewAttributes()) { 1264 params = lp; 1265 } 1266 if (attachInfo.mForceReportNewAttributes) { 1267 attachInfo.mForceReportNewAttributes = false; 1268 params = lp; 1269 } 1270 1271 if (mFirst || attachInfo.mViewVisibilityChanged) { 1272 attachInfo.mViewVisibilityChanged = false; 1273 int resizeMode = mSoftInputMode & 1274 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST; 1275 // If we are in auto resize mode, then we need to determine 1276 // what mode to use now. 1277 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) { 1278 final int N = attachInfo.mScrollContainers.size(); 1279 for (int i=0; i<N; i++) { 1280 if (attachInfo.mScrollContainers.get(i).isShown()) { 1281 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; 1282 } 1283 } 1284 if (resizeMode == 0) { 1285 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN; 1286 } 1287 if ((lp.softInputMode & 1288 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) { 1289 lp.softInputMode = (lp.softInputMode & 1290 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) | 1291 resizeMode; 1292 params = lp; 1293 } 1294 } 1295 } 1296 1297 if (params != null && (host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 1298 if (!PixelFormat.formatHasAlpha(params.format)) { 1299 params.format = PixelFormat.TRANSLUCENT; 1300 } 1301 } 1302 1303 if (mFitSystemWindowsRequested) { 1304 mFitSystemWindowsRequested = false; 1305 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets); 1306 host.fitSystemWindows(mFitSystemWindowsInsets); 1307 if (mLayoutRequested) { 1308 // Short-circuit catching a new layout request here, so 1309 // we don't need to go through two layout passes when things 1310 // change due to fitting system windows, which can happen a lot. 1311 windowSizeMayChange |= measureHierarchy(host, lp, 1312 mView.getContext().getResources(), 1313 desiredWindowWidth, desiredWindowHeight); 1314 } 1315 } 1316 1317 if (layoutRequested) { 1318 // Clear this now, so that if anything requests a layout in the 1319 // rest of this function we will catch it and re-run a full 1320 // layout pass. 1321 mLayoutRequested = false; 1322 } 1323 1324 boolean windowShouldResize = layoutRequested && windowSizeMayChange 1325 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) 1326 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT && 1327 frame.width() < desiredWindowWidth && frame.width() != mWidth) 1328 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT && 1329 frame.height() < desiredWindowHeight && frame.height() != mHeight)); 1330 1331 final boolean computesInternalInsets = 1332 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners(); 1333 1334 boolean insetsPending = false; 1335 int relayoutResult = 0; 1336 1337 if (mFirst || windowShouldResize || insetsChanged || 1338 viewVisibilityChanged || params != null) { 1339 1340 if (viewVisibility == View.VISIBLE) { 1341 // If this window is giving internal insets to the window 1342 // manager, and it is being added or changing its visibility, 1343 // then we want to first give the window manager "fake" 1344 // insets to cause it to effectively ignore the content of 1345 // the window during layout. This avoids it briefly causing 1346 // other windows to resize/move based on the raw frame of the 1347 // window, waiting until we can finish laying out this window 1348 // and get back to the window manager with the ultimately 1349 // computed insets. 1350 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged); 1351 } 1352 1353 if (mSurfaceHolder != null) { 1354 mSurfaceHolder.mSurfaceLock.lock(); 1355 mDrawingAllowed = true; 1356 } 1357 1358 boolean hwInitialized = false; 1359 boolean contentInsetsChanged = false; 1360 boolean visibleInsetsChanged; 1361 boolean hadSurface = mSurface.isValid(); 1362 1363 try { 1364 if (DEBUG_LAYOUT) { 1365 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" + 1366 host.getMeasuredHeight() + ", params=" + params); 1367 } 1368 1369 final int surfaceGenerationId = mSurface.getGenerationId(); 1370 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending); 1371 1372 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString() 1373 + " content=" + mPendingContentInsets.toShortString() 1374 + " visible=" + mPendingVisibleInsets.toShortString() 1375 + " surface=" + mSurface); 1376 1377 if (mPendingConfiguration.seq != 0) { 1378 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: " 1379 + mPendingConfiguration); 1380 updateConfiguration(mPendingConfiguration, !mFirst); 1381 mPendingConfiguration.seq = 0; 1382 } 1383 1384 contentInsetsChanged = !mPendingContentInsets.equals( 1385 mAttachInfo.mContentInsets); 1386 visibleInsetsChanged = !mPendingVisibleInsets.equals( 1387 mAttachInfo.mVisibleInsets); 1388 if (contentInsetsChanged) { 1389 if (mWidth > 0 && mHeight > 0 && lp != null && 1390 ((lp.systemUiVisibility|lp.subtreeSystemUiVisibility) 1391 & View.SYSTEM_UI_LAYOUT_FLAGS) == 0 && 1392 mSurface != null && mSurface.isValid() && 1393 !mAttachInfo.mTurnOffWindowResizeAnim && 1394 mAttachInfo.mHardwareRenderer != null && 1395 mAttachInfo.mHardwareRenderer.isEnabled() && 1396 mAttachInfo.mHardwareRenderer.validate() && 1397 lp != null && !PixelFormat.formatHasAlpha(lp.format)) { 1398 1399 disposeResizeBuffer(); 1400 1401 boolean completed = false; 1402 HardwareCanvas hwRendererCanvas = mAttachInfo.mHardwareRenderer.getCanvas(); 1403 HardwareCanvas layerCanvas = null; 1404 try { 1405 if (mResizeBuffer == null) { 1406 mResizeBuffer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 1407 mWidth, mHeight, false); 1408 } else if (mResizeBuffer.getWidth() != mWidth || 1409 mResizeBuffer.getHeight() != mHeight) { 1410 mResizeBuffer.resize(mWidth, mHeight); 1411 } 1412 // TODO: should handle create/resize failure 1413 layerCanvas = mResizeBuffer.start(hwRendererCanvas); 1414 layerCanvas.setViewport(mWidth, mHeight); 1415 layerCanvas.onPreDraw(null); 1416 final int restoreCount = layerCanvas.save(); 1417 1418 layerCanvas.drawColor(0xff000000, PorterDuff.Mode.SRC); 1419 1420 int yoff; 1421 final boolean scrolling = mScroller != null 1422 && mScroller.computeScrollOffset(); 1423 if (scrolling) { 1424 yoff = mScroller.getCurrY(); 1425 mScroller.abortAnimation(); 1426 } else { 1427 yoff = mScrollY; 1428 } 1429 1430 layerCanvas.translate(0, -yoff); 1431 if (mTranslator != null) { 1432 mTranslator.translateCanvas(layerCanvas); 1433 } 1434 1435 mView.draw(layerCanvas); 1436 1437 drawAccessibilityFocusedDrawableIfNeeded(layerCanvas); 1438 1439 mResizeBufferStartTime = SystemClock.uptimeMillis(); 1440 mResizeBufferDuration = mView.getResources().getInteger( 1441 com.android.internal.R.integer.config_mediumAnimTime); 1442 completed = true; 1443 1444 layerCanvas.restoreToCount(restoreCount); 1445 } catch (OutOfMemoryError e) { 1446 Log.w(TAG, "Not enough memory for content change anim buffer", e); 1447 } finally { 1448 if (layerCanvas != null) { 1449 layerCanvas.onPostDraw(); 1450 } 1451 if (mResizeBuffer != null) { 1452 mResizeBuffer.end(hwRendererCanvas); 1453 if (!completed) { 1454 mResizeBuffer.destroy(); 1455 mResizeBuffer = null; 1456 } 1457 } 1458 } 1459 } 1460 mAttachInfo.mContentInsets.set(mPendingContentInsets); 1461 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: " 1462 + mAttachInfo.mContentInsets); 1463 } 1464 if (contentInsetsChanged || mLastSystemUiVisibility != 1465 mAttachInfo.mSystemUiVisibility || mFitSystemWindowsRequested) { 1466 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility; 1467 mFitSystemWindowsRequested = false; 1468 mFitSystemWindowsInsets.set(mAttachInfo.mContentInsets); 1469 host.fitSystemWindows(mFitSystemWindowsInsets); 1470 } 1471 if (visibleInsetsChanged) { 1472 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets); 1473 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: " 1474 + mAttachInfo.mVisibleInsets); 1475 } 1476 1477 if (!hadSurface) { 1478 if (mSurface.isValid()) { 1479 // If we are creating a new surface, then we need to 1480 // completely redraw it. Also, when we get to the 1481 // point of drawing it we will hold off and schedule 1482 // a new traversal instead. This is so we can tell the 1483 // window manager about all of the windows being displayed 1484 // before actually drawing them, so it can display then 1485 // all at once. 1486 newSurface = true; 1487 mFullRedrawNeeded = true; 1488 mPreviousTransparentRegion.setEmpty(); 1489 1490 if (mAttachInfo.mHardwareRenderer != null) { 1491 try { 1492 hwInitialized = mAttachInfo.mHardwareRenderer.initialize( 1493 mHolder.getSurface()); 1494 } catch (Surface.OutOfResourcesException e) { 1495 Log.e(TAG, "OutOfResourcesException initializing HW surface", e); 1496 try { 1497 if (!mWindowSession.outOfMemory(mWindow) && 1498 Process.myUid() != Process.SYSTEM_UID) { 1499 Slog.w(TAG, "No processes killed for memory; killing self"); 1500 Process.killProcess(Process.myPid()); 1501 } 1502 } catch (RemoteException ex) { 1503 } 1504 mLayoutRequested = true; // ask wm for a new surface next time. 1505 return; 1506 } 1507 } 1508 } 1509 } else if (!mSurface.isValid()) { 1510 // If the surface has been removed, then reset the scroll 1511 // positions. 1512 mLastScrolledFocus = null; 1513 mScrollY = mCurScrollY = 0; 1514 if (mScroller != null) { 1515 mScroller.abortAnimation(); 1516 } 1517 disposeResizeBuffer(); 1518 // Our surface is gone 1519 if (mAttachInfo.mHardwareRenderer != null && 1520 mAttachInfo.mHardwareRenderer.isEnabled()) { 1521 mAttachInfo.mHardwareRenderer.destroy(true); 1522 } 1523 } else if (surfaceGenerationId != mSurface.getGenerationId() && 1524 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) { 1525 mFullRedrawNeeded = true; 1526 try { 1527 mAttachInfo.mHardwareRenderer.updateSurface(mHolder.getSurface()); 1528 } catch (Surface.OutOfResourcesException e) { 1529 Log.e(TAG, "OutOfResourcesException updating HW surface", e); 1530 try { 1531 if (!mWindowSession.outOfMemory(mWindow)) { 1532 Slog.w(TAG, "No processes killed for memory; killing self"); 1533 Process.killProcess(Process.myPid()); 1534 } 1535 } catch (RemoteException ex) { 1536 } 1537 mLayoutRequested = true; // ask wm for a new surface next time. 1538 return; 1539 } 1540 } 1541 } catch (RemoteException e) { 1542 } 1543 1544 if (DEBUG_ORIENTATION) Log.v( 1545 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface); 1546 1547 attachInfo.mWindowLeft = frame.left; 1548 attachInfo.mWindowTop = frame.top; 1549 1550 // !!FIXME!! This next section handles the case where we did not get the 1551 // window size we asked for. We should avoid this by getting a maximum size from 1552 // the window session beforehand. 1553 if (mWidth != frame.width() || mHeight != frame.height()) { 1554 mWidth = frame.width(); 1555 mHeight = frame.height(); 1556 } 1557 1558 if (mSurfaceHolder != null) { 1559 // The app owns the surface; tell it about what is going on. 1560 if (mSurface.isValid()) { 1561 // XXX .copyFrom() doesn't work! 1562 //mSurfaceHolder.mSurface.copyFrom(mSurface); 1563 mSurfaceHolder.mSurface = mSurface; 1564 } 1565 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight); 1566 mSurfaceHolder.mSurfaceLock.unlock(); 1567 if (mSurface.isValid()) { 1568 if (!hadSurface) { 1569 mSurfaceHolder.ungetCallbacks(); 1570 1571 mIsCreating = true; 1572 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder); 1573 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1574 if (callbacks != null) { 1575 for (SurfaceHolder.Callback c : callbacks) { 1576 c.surfaceCreated(mSurfaceHolder); 1577 } 1578 } 1579 surfaceChanged = true; 1580 } 1581 if (surfaceChanged) { 1582 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder, 1583 lp.format, mWidth, mHeight); 1584 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1585 if (callbacks != null) { 1586 for (SurfaceHolder.Callback c : callbacks) { 1587 c.surfaceChanged(mSurfaceHolder, lp.format, 1588 mWidth, mHeight); 1589 } 1590 } 1591 } 1592 mIsCreating = false; 1593 } else if (hadSurface) { 1594 mSurfaceHolder.ungetCallbacks(); 1595 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks(); 1596 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder); 1597 if (callbacks != null) { 1598 for (SurfaceHolder.Callback c : callbacks) { 1599 c.surfaceDestroyed(mSurfaceHolder); 1600 } 1601 } 1602 mSurfaceHolder.mSurfaceLock.lock(); 1603 try { 1604 mSurfaceHolder.mSurface = new Surface(); 1605 } finally { 1606 mSurfaceHolder.mSurfaceLock.unlock(); 1607 } 1608 } 1609 } 1610 1611 if (mAttachInfo.mHardwareRenderer != null && 1612 mAttachInfo.mHardwareRenderer.isEnabled()) { 1613 if (hwInitialized || windowShouldResize || 1614 mWidth != mAttachInfo.mHardwareRenderer.getWidth() || 1615 mHeight != mAttachInfo.mHardwareRenderer.getHeight()) { 1616 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight); 1617 if (!hwInitialized) { 1618 mAttachInfo.mHardwareRenderer.invalidate(mHolder.getSurface()); 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((Rect) args.arg1) 2820 && mPendingContentInsets.equals((Rect) args.arg2) 2821 && mPendingVisibleInsets.equals((Rect) args.arg3) 2822 && ((Configuration) 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 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight, 2885 mHolder.getSurface()); 2886 } catch (Surface.OutOfResourcesException e) { 2887 Log.e(TAG, "OutOfResourcesException locking surface", e); 2888 try { 2889 if (!mWindowSession.outOfMemory(mWindow)) { 2890 Slog.w(TAG, "No processes killed for memory; killing self"); 2891 Process.killProcess(Process.myPid()); 2892 } 2893 } catch (RemoteException ex) { 2894 } 2895 // Retry in a bit. 2896 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); 2897 return; 2898 } 2899 } 2900 } 2901 2902 mLastWasImTarget = WindowManager.LayoutParams 2903 .mayUseInputMethod(mWindowAttributes.flags); 2904 2905 InputMethodManager imm = InputMethodManager.peekInstance(); 2906 if (mView != null) { 2907 if (hasWindowFocus && imm != null && mLastWasImTarget) { 2908 imm.startGettingWindowFocus(mView); 2909 } 2910 mAttachInfo.mKeyDispatchState.reset(); 2911 mView.dispatchWindowFocusChanged(hasWindowFocus); 2912 } 2913 2914 // Note: must be done after the focus change callbacks, 2915 // so all of the view state is set up correctly. 2916 if (hasWindowFocus) { 2917 if (imm != null && mLastWasImTarget) { 2918 imm.onWindowFocus(mView, mView.findFocus(), 2919 mWindowAttributes.softInputMode, 2920 !mHasHadWindowFocus, mWindowAttributes.flags); 2921 } 2922 // Clear the forward bit. We can just do this directly, since 2923 // the window manager doesn't care about it. 2924 mWindowAttributes.softInputMode &= 2925 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2926 ((WindowManager.LayoutParams)mView.getLayoutParams()) 2927 .softInputMode &= 2928 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; 2929 mHasHadWindowFocus = true; 2930 } 2931 2932 setAccessibilityFocus(null, null); 2933 2934 if (mView != null && mAccessibilityManager.isEnabled()) { 2935 if (hasWindowFocus) { 2936 mView.sendAccessibilityEvent( 2937 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 2938 } 2939 } 2940 } 2941 } break; 2942 case MSG_DIE: 2943 doDie(); 2944 break; 2945 case MSG_DISPATCH_KEY: { 2946 KeyEvent event = (KeyEvent)msg.obj; 2947 enqueueInputEvent(event, null, 0, true); 2948 } break; 2949 case MSG_DISPATCH_KEY_FROM_IME: { 2950 if (LOCAL_LOGV) Log.v( 2951 TAG, "Dispatching key " 2952 + msg.obj + " from IME to " + mView); 2953 KeyEvent event = (KeyEvent)msg.obj; 2954 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { 2955 // The IME is trying to say this event is from the 2956 // system! Bad bad bad! 2957 //noinspection UnusedAssignment 2958 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); 2959 } 2960 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); 2961 } break; 2962 case MSG_FINISH_INPUT_CONNECTION: { 2963 InputMethodManager imm = InputMethodManager.peekInstance(); 2964 if (imm != null) { 2965 imm.reportFinishInputConnection((InputConnection)msg.obj); 2966 } 2967 } break; 2968 case MSG_CHECK_FOCUS: { 2969 InputMethodManager imm = InputMethodManager.peekInstance(); 2970 if (imm != null) { 2971 imm.checkFocus(); 2972 } 2973 } break; 2974 case MSG_CLOSE_SYSTEM_DIALOGS: { 2975 if (mView != null) { 2976 mView.onCloseSystemDialogs((String)msg.obj); 2977 } 2978 } break; 2979 case MSG_DISPATCH_DRAG_EVENT: 2980 case MSG_DISPATCH_DRAG_LOCATION_EVENT: { 2981 DragEvent event = (DragEvent)msg.obj; 2982 event.mLocalState = mLocalDragState; // only present when this app called startDrag() 2983 handleDragEvent(event); 2984 } break; 2985 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { 2986 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo)msg.obj); 2987 } break; 2988 case MSG_UPDATE_CONFIGURATION: { 2989 Configuration config = (Configuration)msg.obj; 2990 if (config.isOtherSeqNewer(mLastConfiguration)) { 2991 config = mLastConfiguration; 2992 } 2993 updateConfiguration(config, false); 2994 } break; 2995 case MSG_DISPATCH_SCREEN_STATE: { 2996 if (mView != null) { 2997 handleScreenStateChange(msg.arg1 == 1); 2998 } 2999 } break; 3000 case MSG_INVALIDATE_DISPLAY_LIST: { 3001 invalidateDisplayLists(); 3002 } break; 3003 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { 3004 setAccessibilityFocus(null, null); 3005 } break; 3006 case MSG_DISPATCH_DONE_ANIMATING: { 3007 handleDispatchDoneAnimating(); 3008 } break; 3009 case MSG_INVALIDATE_WORLD: { 3010 if (mView != null) { 3011 invalidateWorld(mView); 3012 } 3013 } break; 3014 } 3015 } 3016 } 3017 3018 final ViewRootHandler mHandler = new ViewRootHandler(); 3019 3020 /** 3021 * Something in the current window tells us we need to change the touch mode. For 3022 * example, we are not in touch mode, and the user touches the screen. 3023 * 3024 * If the touch mode has changed, tell the window manager, and handle it locally. 3025 * 3026 * @param inTouchMode Whether we want to be in touch mode. 3027 * @return True if the touch mode changed and focus changed was changed as a result 3028 */ 3029 boolean ensureTouchMode(boolean inTouchMode) { 3030 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current " 3031 + "touch mode is " + mAttachInfo.mInTouchMode); 3032 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3033 3034 // tell the window manager 3035 try { 3036 mWindowSession.setInTouchMode(inTouchMode); 3037 } catch (RemoteException e) { 3038 throw new RuntimeException(e); 3039 } 3040 3041 // handle the change 3042 return ensureTouchModeLocally(inTouchMode); 3043 } 3044 3045 /** 3046 * Ensure that the touch mode for this window is set, and if it is changing, 3047 * take the appropriate action. 3048 * @param inTouchMode Whether we want to be in touch mode. 3049 * @return True if the touch mode changed and focus changed was changed as a result 3050 */ 3051 private boolean ensureTouchModeLocally(boolean inTouchMode) { 3052 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current " 3053 + "touch mode is " + mAttachInfo.mInTouchMode); 3054 3055 if (mAttachInfo.mInTouchMode == inTouchMode) return false; 3056 3057 mAttachInfo.mInTouchMode = inTouchMode; 3058 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode); 3059 3060 return (inTouchMode) ? enterTouchMode() : leaveTouchMode(); 3061 } 3062 3063 private boolean enterTouchMode() { 3064 if (mView != null) { 3065 if (mView.hasFocus()) { 3066 // note: not relying on mFocusedView here because this could 3067 // be when the window is first being added, and mFocused isn't 3068 // set yet. 3069 final View focused = mView.findFocus(); 3070 if (focused != null && !focused.isFocusableInTouchMode()) { 3071 3072 final ViewGroup ancestorToTakeFocus = 3073 findAncestorToTakeFocusInTouchMode(focused); 3074 if (ancestorToTakeFocus != null) { 3075 // there is an ancestor that wants focus after its descendants that 3076 // is focusable in touch mode.. give it focus 3077 return ancestorToTakeFocus.requestFocus(); 3078 } else { 3079 // nothing appropriate to have focus in touch mode, clear it out 3080 mView.unFocus(); 3081 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null); 3082 mFocusedView = null; 3083 mOldFocusedView = null; 3084 return true; 3085 } 3086 } 3087 } 3088 } 3089 return false; 3090 } 3091 3092 /** 3093 * Find an ancestor of focused that wants focus after its descendants and is 3094 * focusable in touch mode. 3095 * @param focused The currently focused view. 3096 * @return An appropriate view, or null if no such view exists. 3097 */ 3098 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) { 3099 ViewParent parent = focused.getParent(); 3100 while (parent instanceof ViewGroup) { 3101 final ViewGroup vgParent = (ViewGroup) parent; 3102 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS 3103 && vgParent.isFocusableInTouchMode()) { 3104 return vgParent; 3105 } 3106 if (vgParent.isRootNamespace()) { 3107 return null; 3108 } else { 3109 parent = vgParent.getParent(); 3110 } 3111 } 3112 return null; 3113 } 3114 3115 private boolean leaveTouchMode() { 3116 if (mView != null) { 3117 if (mView.hasFocus()) { 3118 // i learned the hard way to not trust mFocusedView :) 3119 mFocusedView = mView.findFocus(); 3120 if (!(mFocusedView instanceof ViewGroup)) { 3121 // some view has focus, let it keep it 3122 return false; 3123 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() != 3124 ViewGroup.FOCUS_AFTER_DESCENDANTS) { 3125 // some view group has focus, and doesn't prefer its children 3126 // over itself for focus, so let them keep it. 3127 return false; 3128 } 3129 } 3130 3131 // find the best view to give focus to in this brave new non-touch-mode 3132 // world 3133 final View focused = focusSearch(null, View.FOCUS_DOWN); 3134 if (focused != null) { 3135 return focused.requestFocus(View.FOCUS_DOWN); 3136 } 3137 } 3138 return false; 3139 } 3140 3141 private void deliverInputEvent(QueuedInputEvent q) { 3142 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent"); 3143 try { 3144 if (q.mEvent instanceof KeyEvent) { 3145 deliverKeyEvent(q); 3146 } else { 3147 final int source = q.mEvent.getSource(); 3148 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 3149 deliverPointerEvent(q); 3150 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3151 deliverTrackballEvent(q); 3152 } else { 3153 deliverGenericMotionEvent(q); 3154 } 3155 } 3156 } finally { 3157 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 3158 } 3159 } 3160 3161 private void deliverPointerEvent(QueuedInputEvent q) { 3162 final MotionEvent event = (MotionEvent)q.mEvent; 3163 final boolean isTouchEvent = event.isTouchEvent(); 3164 if (mInputEventConsistencyVerifier != null) { 3165 if (isTouchEvent) { 3166 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 3167 } else { 3168 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3169 } 3170 } 3171 3172 // If there is no view, then the event will not be handled. 3173 if (mView == null || !mAdded) { 3174 finishInputEvent(q, false); 3175 return; 3176 } 3177 3178 // Translate the pointer event for compatibility, if needed. 3179 if (mTranslator != null) { 3180 mTranslator.translateEventInScreenToAppWindow(event); 3181 } 3182 3183 // Enter touch mode on down or scroll. 3184 final int action = event.getAction(); 3185 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) { 3186 ensureTouchMode(true); 3187 } 3188 3189 // Offset the scroll position. 3190 if (mCurScrollY != 0) { 3191 event.offsetLocation(0, mCurScrollY); 3192 } 3193 if (MEASURE_LATENCY) { 3194 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano()); 3195 } 3196 3197 // Remember the touch position for possible drag-initiation. 3198 if (isTouchEvent) { 3199 mLastTouchPoint.x = event.getRawX(); 3200 mLastTouchPoint.y = event.getRawY(); 3201 } 3202 3203 // Dispatch touch to view hierarchy. 3204 boolean handled = mView.dispatchPointerEvent(event); 3205 if (MEASURE_LATENCY) { 3206 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano()); 3207 } 3208 if (handled) { 3209 finishInputEvent(q, true); 3210 return; 3211 } 3212 3213 // Pointer event was unhandled. 3214 finishInputEvent(q, false); 3215 } 3216 3217 private void deliverTrackballEvent(QueuedInputEvent q) { 3218 final MotionEvent event = (MotionEvent)q.mEvent; 3219 if (mInputEventConsistencyVerifier != null) { 3220 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 3221 } 3222 3223 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3224 if (LOCAL_LOGV) 3225 Log.v(TAG, "Dispatching trackball " + event + " to " + mView); 3226 3227 // Dispatch to the IME before propagating down the view hierarchy. 3228 // The IME will eventually call back into handleImeFinishedEvent. 3229 if (mLastWasImTarget) { 3230 InputMethodManager imm = InputMethodManager.peekInstance(); 3231 if (imm != null) { 3232 final int seq = event.getSequenceNumber(); 3233 if (DEBUG_IMF) 3234 Log.v(TAG, "Sending trackball event to IME: seq=" 3235 + seq + " event=" + event); 3236 imm.dispatchTrackballEvent(mView.getContext(), seq, event, 3237 mInputMethodCallback); 3238 return; 3239 } 3240 } 3241 } 3242 3243 // Not dispatching to IME, continue with post IME actions. 3244 deliverTrackballEventPostIme(q); 3245 } 3246 3247 private void deliverTrackballEventPostIme(QueuedInputEvent q) { 3248 final MotionEvent event = (MotionEvent) q.mEvent; 3249 3250 // If there is no view, then the event will not be handled. 3251 if (mView == null || !mAdded) { 3252 finishInputEvent(q, false); 3253 return; 3254 } 3255 3256 // Deliver the trackball event to the view. 3257 if (mView.dispatchTrackballEvent(event)) { 3258 // If we reach this, we delivered a trackball event to mView and 3259 // mView consumed it. Because we will not translate the trackball 3260 // event into a key event, touch mode will not exit, so we exit 3261 // touch mode here. 3262 ensureTouchMode(false); 3263 3264 finishInputEvent(q, true); 3265 mLastTrackballTime = Integer.MIN_VALUE; 3266 return; 3267 } 3268 3269 // Translate the trackball event into DPAD keys and try to deliver those. 3270 final TrackballAxis x = mTrackballAxisX; 3271 final TrackballAxis y = mTrackballAxisY; 3272 3273 long curTime = SystemClock.uptimeMillis(); 3274 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) { 3275 // It has been too long since the last movement, 3276 // so restart at the beginning. 3277 x.reset(0); 3278 y.reset(0); 3279 mLastTrackballTime = curTime; 3280 } 3281 3282 final int action = event.getAction(); 3283 final int metaState = event.getMetaState(); 3284 switch (action) { 3285 case MotionEvent.ACTION_DOWN: 3286 x.reset(2); 3287 y.reset(2); 3288 enqueueInputEvent(new KeyEvent(curTime, curTime, 3289 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3290 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3291 InputDevice.SOURCE_KEYBOARD)); 3292 break; 3293 case MotionEvent.ACTION_UP: 3294 x.reset(2); 3295 y.reset(2); 3296 enqueueInputEvent(new KeyEvent(curTime, curTime, 3297 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState, 3298 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3299 InputDevice.SOURCE_KEYBOARD)); 3300 break; 3301 } 3302 3303 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step=" 3304 + x.step + " dir=" + x.dir + " acc=" + x.acceleration 3305 + " move=" + event.getX() 3306 + " / Y=" + y.position + " step=" 3307 + y.step + " dir=" + y.dir + " acc=" + y.acceleration 3308 + " move=" + event.getY()); 3309 final float xOff = x.collect(event.getX(), event.getEventTime(), "X"); 3310 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y"); 3311 3312 // Generate DPAD events based on the trackball movement. 3313 // We pick the axis that has moved the most as the direction of 3314 // the DPAD. When we generate DPAD events for one axis, then the 3315 // other axis is reset -- we don't want to perform DPAD jumps due 3316 // to slight movements in the trackball when making major movements 3317 // along the other axis. 3318 int keycode = 0; 3319 int movement = 0; 3320 float accel = 1; 3321 if (xOff > yOff) { 3322 movement = x.generate((2/event.getXPrecision())); 3323 if (movement != 0) { 3324 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT 3325 : KeyEvent.KEYCODE_DPAD_LEFT; 3326 accel = x.acceleration; 3327 y.reset(2); 3328 } 3329 } else if (yOff > 0) { 3330 movement = y.generate((2/event.getYPrecision())); 3331 if (movement != 0) { 3332 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN 3333 : KeyEvent.KEYCODE_DPAD_UP; 3334 accel = y.acceleration; 3335 x.reset(2); 3336 } 3337 } 3338 3339 if (keycode != 0) { 3340 if (movement < 0) movement = -movement; 3341 int accelMovement = (int)(movement * accel); 3342 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement 3343 + " accelMovement=" + accelMovement 3344 + " accel=" + accel); 3345 if (accelMovement > movement) { 3346 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3347 + keycode); 3348 movement--; 3349 int repeatCount = accelMovement - movement; 3350 enqueueInputEvent(new KeyEvent(curTime, curTime, 3351 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState, 3352 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3353 InputDevice.SOURCE_KEYBOARD)); 3354 } 3355 while (movement > 0) { 3356 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: " 3357 + keycode); 3358 movement--; 3359 curTime = SystemClock.uptimeMillis(); 3360 enqueueInputEvent(new KeyEvent(curTime, curTime, 3361 KeyEvent.ACTION_DOWN, keycode, 0, metaState, 3362 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3363 InputDevice.SOURCE_KEYBOARD)); 3364 enqueueInputEvent(new KeyEvent(curTime, curTime, 3365 KeyEvent.ACTION_UP, keycode, 0, metaState, 3366 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK, 3367 InputDevice.SOURCE_KEYBOARD)); 3368 } 3369 mLastTrackballTime = curTime; 3370 } 3371 3372 // Unfortunately we can't tell whether the application consumed the keys, so 3373 // we always consider the trackball event handled. 3374 finishInputEvent(q, true); 3375 } 3376 3377 private void deliverGenericMotionEvent(QueuedInputEvent q) { 3378 final MotionEvent event = (MotionEvent)q.mEvent; 3379 if (mInputEventConsistencyVerifier != null) { 3380 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 3381 } 3382 3383 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3384 if (LOCAL_LOGV) 3385 Log.v(TAG, "Dispatching generic motion " + event + " to " + mView); 3386 3387 // Dispatch to the IME before propagating down the view hierarchy. 3388 // The IME will eventually call back into handleImeFinishedEvent. 3389 if (mLastWasImTarget) { 3390 InputMethodManager imm = InputMethodManager.peekInstance(); 3391 if (imm != null) { 3392 final int seq = event.getSequenceNumber(); 3393 if (DEBUG_IMF) 3394 Log.v(TAG, "Sending generic motion event to IME: seq=" 3395 + seq + " event=" + event); 3396 imm.dispatchGenericMotionEvent(mView.getContext(), seq, event, 3397 mInputMethodCallback); 3398 return; 3399 } 3400 } 3401 } 3402 3403 // Not dispatching to IME, continue with post IME actions. 3404 deliverGenericMotionEventPostIme(q); 3405 } 3406 3407 private void deliverGenericMotionEventPostIme(QueuedInputEvent q) { 3408 final MotionEvent event = (MotionEvent) q.mEvent; 3409 final boolean isJoystick = (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0; 3410 3411 // If there is no view, then the event will not be handled. 3412 if (mView == null || !mAdded) { 3413 if (isJoystick) { 3414 updateJoystickDirection(event, false); 3415 } 3416 finishInputEvent(q, false); 3417 return; 3418 } 3419 3420 // Deliver the event to the view. 3421 if (mView.dispatchGenericMotionEvent(event)) { 3422 if (isJoystick) { 3423 updateJoystickDirection(event, false); 3424 } 3425 finishInputEvent(q, true); 3426 return; 3427 } 3428 3429 if (isJoystick) { 3430 // Translate the joystick event into DPAD keys and try to deliver 3431 // those. 3432 updateJoystickDirection(event, true); 3433 finishInputEvent(q, true); 3434 } else { 3435 finishInputEvent(q, false); 3436 } 3437 } 3438 3439 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) { 3440 final long time = event.getEventTime(); 3441 final int metaState = event.getMetaState(); 3442 final int deviceId = event.getDeviceId(); 3443 final int source = event.getSource(); 3444 3445 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X)); 3446 if (xDirection == 0) { 3447 xDirection = joystickAxisValueToDirection(event.getX()); 3448 } 3449 3450 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y)); 3451 if (yDirection == 0) { 3452 yDirection = joystickAxisValueToDirection(event.getY()); 3453 } 3454 3455 if (xDirection != mLastJoystickXDirection) { 3456 if (mLastJoystickXKeyCode != 0) { 3457 enqueueInputEvent(new KeyEvent(time, time, 3458 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState, 3459 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3460 mLastJoystickXKeyCode = 0; 3461 } 3462 3463 mLastJoystickXDirection = xDirection; 3464 3465 if (xDirection != 0 && synthesizeNewKeys) { 3466 mLastJoystickXKeyCode = xDirection > 0 3467 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; 3468 enqueueInputEvent(new KeyEvent(time, time, 3469 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState, 3470 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3471 } 3472 } 3473 3474 if (yDirection != mLastJoystickYDirection) { 3475 if (mLastJoystickYKeyCode != 0) { 3476 enqueueInputEvent(new KeyEvent(time, time, 3477 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState, 3478 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3479 mLastJoystickYKeyCode = 0; 3480 } 3481 3482 mLastJoystickYDirection = yDirection; 3483 3484 if (yDirection != 0 && synthesizeNewKeys) { 3485 mLastJoystickYKeyCode = yDirection > 0 3486 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; 3487 enqueueInputEvent(new KeyEvent(time, time, 3488 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState, 3489 deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); 3490 } 3491 } 3492 } 3493 3494 private static int joystickAxisValueToDirection(float value) { 3495 if (value >= 0.5f) { 3496 return 1; 3497 } else if (value <= -0.5f) { 3498 return -1; 3499 } else { 3500 return 0; 3501 } 3502 } 3503 3504 /** 3505 * Returns true if the key is used for keyboard navigation. 3506 * @param keyEvent The key event. 3507 * @return True if the key is used for keyboard navigation. 3508 */ 3509 private static boolean isNavigationKey(KeyEvent keyEvent) { 3510 switch (keyEvent.getKeyCode()) { 3511 case KeyEvent.KEYCODE_DPAD_LEFT: 3512 case KeyEvent.KEYCODE_DPAD_RIGHT: 3513 case KeyEvent.KEYCODE_DPAD_UP: 3514 case KeyEvent.KEYCODE_DPAD_DOWN: 3515 case KeyEvent.KEYCODE_DPAD_CENTER: 3516 case KeyEvent.KEYCODE_PAGE_UP: 3517 case KeyEvent.KEYCODE_PAGE_DOWN: 3518 case KeyEvent.KEYCODE_MOVE_HOME: 3519 case KeyEvent.KEYCODE_MOVE_END: 3520 case KeyEvent.KEYCODE_TAB: 3521 case KeyEvent.KEYCODE_SPACE: 3522 case KeyEvent.KEYCODE_ENTER: 3523 return true; 3524 } 3525 return false; 3526 } 3527 3528 /** 3529 * Returns true if the key is used for typing. 3530 * @param keyEvent The key event. 3531 * @return True if the key is used for typing. 3532 */ 3533 private static boolean isTypingKey(KeyEvent keyEvent) { 3534 return keyEvent.getUnicodeChar() > 0; 3535 } 3536 3537 /** 3538 * See if the key event means we should leave touch mode (and leave touch mode if so). 3539 * @param event The key event. 3540 * @return Whether this key event should be consumed (meaning the act of 3541 * leaving touch mode alone is considered the event). 3542 */ 3543 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) { 3544 // Only relevant in touch mode. 3545 if (!mAttachInfo.mInTouchMode) { 3546 return false; 3547 } 3548 3549 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP. 3550 final int action = event.getAction(); 3551 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) { 3552 return false; 3553 } 3554 3555 // Don't leave touch mode if the IME told us not to. 3556 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) { 3557 return false; 3558 } 3559 3560 // If the key can be used for keyboard navigation then leave touch mode 3561 // and select a focused view if needed (in ensureTouchMode). 3562 // When a new focused view is selected, we consume the navigation key because 3563 // navigation doesn't make much sense unless a view already has focus so 3564 // the key's purpose is to set focus. 3565 if (isNavigationKey(event)) { 3566 return ensureTouchMode(false); 3567 } 3568 3569 // If the key can be used for typing then leave touch mode 3570 // and select a focused view if needed (in ensureTouchMode). 3571 // Always allow the view to process the typing key. 3572 if (isTypingKey(event)) { 3573 ensureTouchMode(false); 3574 return false; 3575 } 3576 3577 return false; 3578 } 3579 3580 private void deliverKeyEvent(QueuedInputEvent q) { 3581 final KeyEvent event = (KeyEvent)q.mEvent; 3582 if (mInputEventConsistencyVerifier != null) { 3583 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 3584 } 3585 3586 if (mView != null && mAdded && (q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) { 3587 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView); 3588 3589 // Perform predispatching before the IME. 3590 if (mView.dispatchKeyEventPreIme(event)) { 3591 finishInputEvent(q, true); 3592 return; 3593 } 3594 3595 // Dispatch to the IME before propagating down the view hierarchy. 3596 // The IME will eventually call back into handleImeFinishedEvent. 3597 if (mLastWasImTarget) { 3598 InputMethodManager imm = InputMethodManager.peekInstance(); 3599 if (imm != null) { 3600 final int seq = event.getSequenceNumber(); 3601 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq=" 3602 + seq + " event=" + event); 3603 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback); 3604 return; 3605 } 3606 } 3607 } 3608 3609 // Not dispatching to IME, continue with post IME actions. 3610 deliverKeyEventPostIme(q); 3611 } 3612 3613 void handleImeFinishedEvent(int seq, boolean handled) { 3614 final QueuedInputEvent q = mCurrentInputEvent; 3615 if (q != null && q.mEvent.getSequenceNumber() == seq) { 3616 if (DEBUG_IMF) { 3617 Log.v(TAG, "IME finished event: seq=" + seq 3618 + " handled=" + handled + " event=" + q); 3619 } 3620 if (handled) { 3621 finishInputEvent(q, true); 3622 } else { 3623 if (q.mEvent instanceof KeyEvent) { 3624 KeyEvent event = (KeyEvent)q.mEvent; 3625 if (event.getAction() != KeyEvent.ACTION_UP) { 3626 // If the window doesn't currently have input focus, then drop 3627 // this event. This could be an event that came back from the 3628 // IME dispatch but the window has lost focus in the meantime. 3629 if (!mAttachInfo.mHasWindowFocus) { 3630 Slog.w(TAG, "Dropping event due to no window focus: " + event); 3631 finishInputEvent(q, true); 3632 return; 3633 } 3634 } 3635 deliverKeyEventPostIme(q); 3636 } else { 3637 MotionEvent event = (MotionEvent)q.mEvent; 3638 if (event.getAction() != MotionEvent.ACTION_CANCEL 3639 && event.getAction() != MotionEvent.ACTION_UP) { 3640 // If the window doesn't currently have input focus, then drop 3641 // this event. This could be an event that came back from the 3642 // IME dispatch but the window has lost focus in the meantime. 3643 if (!mAttachInfo.mHasWindowFocus) { 3644 Slog.w(TAG, "Dropping event due to no window focus: " + event); 3645 finishInputEvent(q, true); 3646 return; 3647 } 3648 } 3649 final int source = q.mEvent.getSource(); 3650 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { 3651 deliverTrackballEventPostIme(q); 3652 } else { 3653 deliverGenericMotionEventPostIme(q); 3654 } 3655 } 3656 } 3657 } else { 3658 if (DEBUG_IMF) { 3659 Log.v(TAG, "IME finished event: seq=" + seq 3660 + " handled=" + handled + ", event not found!"); 3661 } 3662 } 3663 } 3664 3665 private void deliverKeyEventPostIme(QueuedInputEvent q) { 3666 final KeyEvent event = (KeyEvent)q.mEvent; 3667 3668 // If the view went away, then the event will not be handled. 3669 if (mView == null || !mAdded) { 3670 finishInputEvent(q, false); 3671 return; 3672 } 3673 3674 // If the key's purpose is to exit touch mode then we consume it and consider it handled. 3675 if (checkForLeavingTouchModeAndConsume(event)) { 3676 finishInputEvent(q, true); 3677 return; 3678 } 3679 3680 // Make sure the fallback event policy sees all keys that will be delivered to the 3681 // view hierarchy. 3682 mFallbackEventHandler.preDispatchKeyEvent(event); 3683 3684 // Deliver the key to the view hierarchy. 3685 if (mView.dispatchKeyEvent(event)) { 3686 finishInputEvent(q, true); 3687 return; 3688 } 3689 3690 // If the Control modifier is held, try to interpret the key as a shortcut. 3691 if (event.getAction() == KeyEvent.ACTION_DOWN 3692 && event.isCtrlPressed() 3693 && event.getRepeatCount() == 0 3694 && !KeyEvent.isModifierKey(event.getKeyCode())) { 3695 if (mView.dispatchKeyShortcutEvent(event)) { 3696 finishInputEvent(q, true); 3697 return; 3698 } 3699 } 3700 3701 // Apply the fallback event policy. 3702 if (mFallbackEventHandler.dispatchKeyEvent(event)) { 3703 finishInputEvent(q, true); 3704 return; 3705 } 3706 3707 // Handle automatic focus changes. 3708 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3709 int direction = 0; 3710 switch (event.getKeyCode()) { 3711 case KeyEvent.KEYCODE_DPAD_LEFT: 3712 if (event.hasNoModifiers()) { 3713 direction = View.FOCUS_LEFT; 3714 } 3715 break; 3716 case KeyEvent.KEYCODE_DPAD_RIGHT: 3717 if (event.hasNoModifiers()) { 3718 direction = View.FOCUS_RIGHT; 3719 } 3720 break; 3721 case KeyEvent.KEYCODE_DPAD_UP: 3722 if (event.hasNoModifiers()) { 3723 direction = View.FOCUS_UP; 3724 } 3725 break; 3726 case KeyEvent.KEYCODE_DPAD_DOWN: 3727 if (event.hasNoModifiers()) { 3728 direction = View.FOCUS_DOWN; 3729 } 3730 break; 3731 case KeyEvent.KEYCODE_TAB: 3732 if (event.hasNoModifiers()) { 3733 direction = View.FOCUS_FORWARD; 3734 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 3735 direction = View.FOCUS_BACKWARD; 3736 } 3737 break; 3738 } 3739 if (direction != 0) { 3740 View focused = mView.findFocus(); 3741 if (focused != null) { 3742 View v = focused.focusSearch(direction); 3743 if (v != null && v != focused) { 3744 // do the math the get the interesting rect 3745 // of previous focused into the coord system of 3746 // newly focused view 3747 focused.getFocusedRect(mTempRect); 3748 if (mView instanceof ViewGroup) { 3749 ((ViewGroup) mView).offsetDescendantRectToMyCoords( 3750 focused, mTempRect); 3751 ((ViewGroup) mView).offsetRectIntoDescendantCoords( 3752 v, mTempRect); 3753 } 3754 if (v.requestFocus(direction, mTempRect)) { 3755 playSoundEffect(SoundEffectConstants 3756 .getContantForFocusDirection(direction)); 3757 finishInputEvent(q, true); 3758 return; 3759 } 3760 } 3761 3762 // Give the focused view a last chance to handle the dpad key. 3763 if (mView.dispatchUnhandledMove(focused, direction)) { 3764 finishInputEvent(q, true); 3765 return; 3766 } 3767 } 3768 } 3769 } 3770 3771 // Key was unhandled. 3772 finishInputEvent(q, false); 3773 } 3774 3775 /* drag/drop */ 3776 void setLocalDragState(Object obj) { 3777 mLocalDragState = obj; 3778 } 3779 3780 private void handleDragEvent(DragEvent event) { 3781 // From the root, only drag start/end/location are dispatched. entered/exited 3782 // are determined and dispatched by the viewgroup hierarchy, who then report 3783 // that back here for ultimate reporting back to the framework. 3784 if (mView != null && mAdded) { 3785 final int what = event.mAction; 3786 3787 if (what == DragEvent.ACTION_DRAG_EXITED) { 3788 // A direct EXITED event means that the window manager knows we've just crossed 3789 // a window boundary, so the current drag target within this one must have 3790 // just been exited. Send it the usual notifications and then we're done 3791 // for now. 3792 mView.dispatchDragEvent(event); 3793 } else { 3794 // Cache the drag description when the operation starts, then fill it in 3795 // on subsequent calls as a convenience 3796 if (what == DragEvent.ACTION_DRAG_STARTED) { 3797 mCurrentDragView = null; // Start the current-recipient tracking 3798 mDragDescription = event.mClipDescription; 3799 } else { 3800 event.mClipDescription = mDragDescription; 3801 } 3802 3803 // For events with a [screen] location, translate into window coordinates 3804 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) { 3805 mDragPoint.set(event.mX, event.mY); 3806 if (mTranslator != null) { 3807 mTranslator.translatePointInScreenToAppWindow(mDragPoint); 3808 } 3809 3810 if (mCurScrollY != 0) { 3811 mDragPoint.offset(0, mCurScrollY); 3812 } 3813 3814 event.mX = mDragPoint.x; 3815 event.mY = mDragPoint.y; 3816 } 3817 3818 // Remember who the current drag target is pre-dispatch 3819 final View prevDragView = mCurrentDragView; 3820 3821 // Now dispatch the drag/drop event 3822 boolean result = mView.dispatchDragEvent(event); 3823 3824 // If we changed apparent drag target, tell the OS about it 3825 if (prevDragView != mCurrentDragView) { 3826 try { 3827 if (prevDragView != null) { 3828 mWindowSession.dragRecipientExited(mWindow); 3829 } 3830 if (mCurrentDragView != null) { 3831 mWindowSession.dragRecipientEntered(mWindow); 3832 } 3833 } catch (RemoteException e) { 3834 Slog.e(TAG, "Unable to note drag target change"); 3835 } 3836 } 3837 3838 // Report the drop result when we're done 3839 if (what == DragEvent.ACTION_DROP) { 3840 mDragDescription = null; 3841 try { 3842 Log.i(TAG, "Reporting drop result: " + result); 3843 mWindowSession.reportDropResult(mWindow, result); 3844 } catch (RemoteException e) { 3845 Log.e(TAG, "Unable to report drop result"); 3846 } 3847 } 3848 3849 // When the drag operation ends, release any local state object 3850 // that may have been in use 3851 if (what == DragEvent.ACTION_DRAG_ENDED) { 3852 setLocalDragState(null); 3853 } 3854 } 3855 } 3856 event.recycle(); 3857 } 3858 3859 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) { 3860 if (mSeq != args.seq) { 3861 // The sequence has changed, so we need to update our value and make 3862 // sure to do a traversal afterward so the window manager is given our 3863 // most recent data. 3864 mSeq = args.seq; 3865 mAttachInfo.mForceReportNewAttributes = true; 3866 scheduleTraversals(); 3867 } 3868 if (mView == null) return; 3869 if (args.localChanges != 0) { 3870 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges); 3871 } 3872 if (mAttachInfo != null) { 3873 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS; 3874 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) { 3875 mAttachInfo.mGlobalSystemUiVisibility = visibility; 3876 mView.dispatchSystemUiVisibilityChanged(visibility); 3877 } 3878 } 3879 } 3880 3881 public void handleDispatchDoneAnimating() { 3882 if (mWindowsAnimating) { 3883 mWindowsAnimating = false; 3884 if (!mDirty.isEmpty() || mIsAnimating) { 3885 scheduleTraversals(); 3886 } 3887 } 3888 } 3889 3890 public void getLastTouchPoint(Point outLocation) { 3891 outLocation.x = (int) mLastTouchPoint.x; 3892 outLocation.y = (int) mLastTouchPoint.y; 3893 } 3894 3895 public void setDragFocus(View newDragTarget) { 3896 if (mCurrentDragView != newDragTarget) { 3897 mCurrentDragView = newDragTarget; 3898 } 3899 } 3900 3901 private AudioManager getAudioManager() { 3902 if (mView == null) { 3903 throw new IllegalStateException("getAudioManager called when there is no mView"); 3904 } 3905 if (mAudioManager == null) { 3906 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE); 3907 } 3908 return mAudioManager; 3909 } 3910 3911 public AccessibilityInteractionController getAccessibilityInteractionController() { 3912 if (mView == null) { 3913 throw new IllegalStateException("getAccessibilityInteractionController" 3914 + " called when there is no mView"); 3915 } 3916 if (mAccessibilityInteractionController == null) { 3917 mAccessibilityInteractionController = new AccessibilityInteractionController(this); 3918 } 3919 return mAccessibilityInteractionController; 3920 } 3921 3922 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, 3923 boolean insetsPending) throws RemoteException { 3924 3925 float appScale = mAttachInfo.mApplicationScale; 3926 boolean restore = false; 3927 if (params != null && mTranslator != null) { 3928 restore = true; 3929 params.backup(); 3930 mTranslator.translateWindowLayout(params); 3931 } 3932 if (params != null) { 3933 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params); 3934 } 3935 mPendingConfiguration.seq = 0; 3936 //Log.d(TAG, ">>>>>> CALLING relayout"); 3937 if (params != null && mOrigWindowType != params.type) { 3938 // For compatibility with old apps, don't crash here. 3939 if (mTargetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 3940 Slog.w(TAG, "Window type can not be changed after " 3941 + "the window is added; ignoring change of " + mView); 3942 params.type = mOrigWindowType; 3943 } 3944 } 3945 int relayoutResult = mWindowSession.relayout( 3946 mWindow, mSeq, params, 3947 (int) (mView.getMeasuredWidth() * appScale + 0.5f), 3948 (int) (mView.getMeasuredHeight() * appScale + 0.5f), 3949 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, 3950 mWinFrame, mPendingContentInsets, mPendingVisibleInsets, 3951 mPendingConfiguration, mSurface); 3952 //Log.d(TAG, "<<<<<< BACK FROM relayout"); 3953 if (restore) { 3954 params.restore(); 3955 } 3956 3957 if (mTranslator != null) { 3958 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame); 3959 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets); 3960 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets); 3961 } 3962 return relayoutResult; 3963 } 3964 3965 /** 3966 * {@inheritDoc} 3967 */ 3968 public void playSoundEffect(int effectId) { 3969 checkThread(); 3970 3971 try { 3972 final AudioManager audioManager = getAudioManager(); 3973 3974 switch (effectId) { 3975 case SoundEffectConstants.CLICK: 3976 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 3977 return; 3978 case SoundEffectConstants.NAVIGATION_DOWN: 3979 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN); 3980 return; 3981 case SoundEffectConstants.NAVIGATION_LEFT: 3982 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT); 3983 return; 3984 case SoundEffectConstants.NAVIGATION_RIGHT: 3985 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT); 3986 return; 3987 case SoundEffectConstants.NAVIGATION_UP: 3988 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP); 3989 return; 3990 default: 3991 throw new IllegalArgumentException("unknown effect id " + effectId + 3992 " not defined in " + SoundEffectConstants.class.getCanonicalName()); 3993 } 3994 } catch (IllegalStateException e) { 3995 // Exception thrown by getAudioManager() when mView is null 3996 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e); 3997 e.printStackTrace(); 3998 } 3999 } 4000 4001 /** 4002 * {@inheritDoc} 4003 */ 4004 public boolean performHapticFeedback(int effectId, boolean always) { 4005 try { 4006 return mWindowSession.performHapticFeedback(mWindow, effectId, always); 4007 } catch (RemoteException e) { 4008 return false; 4009 } 4010 } 4011 4012 /** 4013 * {@inheritDoc} 4014 */ 4015 public View focusSearch(View focused, int direction) { 4016 checkThread(); 4017 if (!(mView instanceof ViewGroup)) { 4018 return null; 4019 } 4020 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction); 4021 } 4022 4023 public void debug() { 4024 mView.debug(); 4025 } 4026 4027 public void dumpGfxInfo(int[] info) { 4028 info[0] = info[1] = 0; 4029 if (mView != null) { 4030 getGfxInfo(mView, info); 4031 } 4032 } 4033 4034 private static void getGfxInfo(View view, int[] info) { 4035 DisplayList displayList = view.mDisplayList; 4036 info[0]++; 4037 if (displayList != null) { 4038 info[1] += displayList.getSize(); 4039 } 4040 4041 if (view instanceof ViewGroup) { 4042 ViewGroup group = (ViewGroup) view; 4043 4044 int count = group.getChildCount(); 4045 for (int i = 0; i < count; i++) { 4046 getGfxInfo(group.getChildAt(i), info); 4047 } 4048 } 4049 } 4050 4051 public void die(boolean immediate) { 4052 // Make sure we do execute immediately if we are in the middle of a traversal or the damage 4053 // done by dispatchDetachedFromWindow will cause havoc on return. 4054 if (immediate && !mIsInTraversal) { 4055 doDie(); 4056 } else { 4057 if (!mIsDrawing) { 4058 destroyHardwareRenderer(); 4059 } else { 4060 Log.e(TAG, "Attempting to destroy the window while drawing!\n" + 4061 " window=" + this + ", title=" + mWindowAttributes.getTitle()); 4062 } 4063 mHandler.sendEmptyMessage(MSG_DIE); 4064 } 4065 } 4066 4067 void doDie() { 4068 checkThread(); 4069 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface); 4070 synchronized (this) { 4071 if (mAdded) { 4072 dispatchDetachedFromWindow(); 4073 } 4074 4075 if (mAdded && !mFirst) { 4076 destroyHardwareRenderer(); 4077 4078 if (mView != null) { 4079 int viewVisibility = mView.getVisibility(); 4080 boolean viewVisibilityChanged = mViewVisibility != viewVisibility; 4081 if (mWindowAttributesChanged || viewVisibilityChanged) { 4082 // If layout params have been changed, first give them 4083 // to the window manager to make sure it has the correct 4084 // animation info. 4085 try { 4086 if ((relayoutWindow(mWindowAttributes, viewVisibility, false) 4087 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { 4088 mWindowSession.finishDrawing(mWindow); 4089 } 4090 } catch (RemoteException e) { 4091 } 4092 } 4093 4094 mSurface.release(); 4095 } 4096 } 4097 4098 mAdded = false; 4099 } 4100 } 4101 4102 public void requestUpdateConfiguration(Configuration config) { 4103 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config); 4104 mHandler.sendMessage(msg); 4105 } 4106 4107 public void loadSystemProperties() { 4108 boolean layout = SystemProperties.getBoolean( 4109 View.DEBUG_LAYOUT_PROPERTY, false); 4110 if (layout != mAttachInfo.mDebugLayout) { 4111 mAttachInfo.mDebugLayout = layout; 4112 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) { 4113 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200); 4114 } 4115 } 4116 } 4117 4118 private void destroyHardwareRenderer() { 4119 AttachInfo attachInfo = mAttachInfo; 4120 HardwareRenderer hardwareRenderer = attachInfo.mHardwareRenderer; 4121 4122 if (hardwareRenderer != null) { 4123 if (mView != null) { 4124 hardwareRenderer.destroyHardwareResources(mView); 4125 } 4126 hardwareRenderer.destroy(true); 4127 hardwareRenderer.setRequested(false); 4128 4129 attachInfo.mHardwareRenderer = null; 4130 attachInfo.mHardwareAccelerated = false; 4131 } 4132 } 4133 4134 void dispatchImeFinishedEvent(int seq, boolean handled) { 4135 Message msg = mHandler.obtainMessage(MSG_IME_FINISHED_EVENT); 4136 msg.arg1 = seq; 4137 msg.arg2 = handled ? 1 : 0; 4138 msg.setAsynchronous(true); 4139 mHandler.sendMessage(msg); 4140 } 4141 4142 public void dispatchFinishInputConnection(InputConnection connection) { 4143 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection); 4144 mHandler.sendMessage(msg); 4145 } 4146 4147 public void dispatchResized(Rect frame, Rect contentInsets, 4148 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4149 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": frame=" + frame.toShortString() 4150 + " contentInsets=" + contentInsets.toShortString() 4151 + " visibleInsets=" + visibleInsets.toShortString() 4152 + " reportDraw=" + reportDraw); 4153 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED); 4154 if (mTranslator != null) { 4155 mTranslator.translateRectInScreenToAppWindow(frame); 4156 mTranslator.translateRectInScreenToAppWindow(contentInsets); 4157 mTranslator.translateRectInScreenToAppWindow(visibleInsets); 4158 } 4159 SomeArgs args = SomeArgs.obtain(); 4160 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid()); 4161 args.arg1 = sameProcessCall ? new Rect(frame) : frame; 4162 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets; 4163 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets; 4164 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig; 4165 msg.obj = args; 4166 mHandler.sendMessage(msg); 4167 } 4168 4169 public void dispatchMoved(int newX, int newY) { 4170 if (DEBUG_LAYOUT) Log.v(TAG, "Window moved " + this + ": newX=" + newX + " newY=" + newY); 4171 if (mTranslator != null) { 4172 PointF point = new PointF(newX, newY); 4173 mTranslator.translatePointInScreenToAppWindow(point); 4174 newX = (int) (point.x + 0.5); 4175 newY = (int) (point.y + 0.5); 4176 } 4177 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY); 4178 mHandler.sendMessage(msg); 4179 } 4180 4181 /** 4182 * Represents a pending input event that is waiting in a queue. 4183 * 4184 * Input events are processed in serial order by the timestamp specified by 4185 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers 4186 * one input event to the application at a time and waits for the application 4187 * to finish handling it before delivering the next one. 4188 * 4189 * However, because the application or IME can synthesize and inject multiple 4190 * key events at a time without going through the input dispatcher, we end up 4191 * needing a queue on the application's side. 4192 */ 4193 private static final class QueuedInputEvent { 4194 public static final int FLAG_DELIVER_POST_IME = 1; 4195 4196 public QueuedInputEvent mNext; 4197 4198 public InputEvent mEvent; 4199 public InputEventReceiver mReceiver; 4200 public int mFlags; 4201 } 4202 4203 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event, 4204 InputEventReceiver receiver, int flags) { 4205 QueuedInputEvent q = mQueuedInputEventPool; 4206 if (q != null) { 4207 mQueuedInputEventPoolSize -= 1; 4208 mQueuedInputEventPool = q.mNext; 4209 q.mNext = null; 4210 } else { 4211 q = new QueuedInputEvent(); 4212 } 4213 4214 q.mEvent = event; 4215 q.mReceiver = receiver; 4216 q.mFlags = flags; 4217 return q; 4218 } 4219 4220 private void recycleQueuedInputEvent(QueuedInputEvent q) { 4221 q.mEvent = null; 4222 q.mReceiver = null; 4223 4224 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) { 4225 mQueuedInputEventPoolSize += 1; 4226 q.mNext = mQueuedInputEventPool; 4227 mQueuedInputEventPool = q; 4228 } 4229 } 4230 4231 void enqueueInputEvent(InputEvent event) { 4232 enqueueInputEvent(event, null, 0, false); 4233 } 4234 4235 void enqueueInputEvent(InputEvent event, 4236 InputEventReceiver receiver, int flags, boolean processImmediately) { 4237 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags); 4238 4239 // Always enqueue the input event in order, regardless of its time stamp. 4240 // We do this because the application or the IME may inject key events 4241 // in response to touch events and we want to ensure that the injected keys 4242 // are processed in the order they were received and we cannot trust that 4243 // the time stamp of injected events are monotonic. 4244 QueuedInputEvent last = mFirstPendingInputEvent; 4245 if (last == null) { 4246 mFirstPendingInputEvent = q; 4247 } else { 4248 while (last.mNext != null) { 4249 last = last.mNext; 4250 } 4251 last.mNext = q; 4252 } 4253 4254 if (processImmediately) { 4255 doProcessInputEvents(); 4256 } else { 4257 scheduleProcessInputEvents(); 4258 } 4259 } 4260 4261 private void scheduleProcessInputEvents() { 4262 if (!mProcessInputEventsScheduled) { 4263 mProcessInputEventsScheduled = true; 4264 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS); 4265 msg.setAsynchronous(true); 4266 mHandler.sendMessage(msg); 4267 } 4268 } 4269 4270 void doProcessInputEvents() { 4271 while (mCurrentInputEvent == null && mFirstPendingInputEvent != null) { 4272 QueuedInputEvent q = mFirstPendingInputEvent; 4273 mFirstPendingInputEvent = q.mNext; 4274 q.mNext = null; 4275 mCurrentInputEvent = q; 4276 deliverInputEvent(q); 4277 } 4278 4279 // We are done processing all input events that we can process right now 4280 // so we can clear the pending flag immediately. 4281 if (mProcessInputEventsScheduled) { 4282 mProcessInputEventsScheduled = false; 4283 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS); 4284 } 4285 } 4286 4287 private void finishInputEvent(QueuedInputEvent q, boolean handled) { 4288 if (q != mCurrentInputEvent) { 4289 throw new IllegalStateException("finished input event out of order"); 4290 } 4291 4292 if (q.mReceiver != null) { 4293 q.mReceiver.finishInputEvent(q.mEvent, handled); 4294 } else { 4295 q.mEvent.recycleIfNeededAfterDispatch(); 4296 } 4297 4298 recycleQueuedInputEvent(q); 4299 4300 mCurrentInputEvent = null; 4301 if (mFirstPendingInputEvent != null) { 4302 scheduleProcessInputEvents(); 4303 } 4304 } 4305 4306 void scheduleConsumeBatchedInput() { 4307 if (!mConsumeBatchedInputScheduled) { 4308 mConsumeBatchedInputScheduled = true; 4309 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT, 4310 mConsumedBatchedInputRunnable, null); 4311 } 4312 } 4313 4314 void unscheduleConsumeBatchedInput() { 4315 if (mConsumeBatchedInputScheduled) { 4316 mConsumeBatchedInputScheduled = false; 4317 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT, 4318 mConsumedBatchedInputRunnable, null); 4319 } 4320 } 4321 4322 void doConsumeBatchedInput(long frameTimeNanos) { 4323 if (mConsumeBatchedInputScheduled) { 4324 mConsumeBatchedInputScheduled = false; 4325 if (mInputEventReceiver != null) { 4326 mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos); 4327 } 4328 doProcessInputEvents(); 4329 } 4330 } 4331 4332 final class TraversalRunnable implements Runnable { 4333 @Override 4334 public void run() { 4335 doTraversal(); 4336 } 4337 } 4338 final TraversalRunnable mTraversalRunnable = new TraversalRunnable(); 4339 4340 final class WindowInputEventReceiver extends InputEventReceiver { 4341 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) { 4342 super(inputChannel, looper); 4343 } 4344 4345 @Override 4346 public void onInputEvent(InputEvent event) { 4347 enqueueInputEvent(event, this, 0, true); 4348 } 4349 4350 @Override 4351 public void onBatchedInputEventPending() { 4352 scheduleConsumeBatchedInput(); 4353 } 4354 4355 @Override 4356 public void dispose() { 4357 unscheduleConsumeBatchedInput(); 4358 super.dispose(); 4359 } 4360 } 4361 WindowInputEventReceiver mInputEventReceiver; 4362 4363 final class ConsumeBatchedInputRunnable implements Runnable { 4364 @Override 4365 public void run() { 4366 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos()); 4367 } 4368 } 4369 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable = 4370 new ConsumeBatchedInputRunnable(); 4371 boolean mConsumeBatchedInputScheduled; 4372 4373 final class InvalidateOnAnimationRunnable implements Runnable { 4374 private boolean mPosted; 4375 private ArrayList<View> mViews = new ArrayList<View>(); 4376 private ArrayList<AttachInfo.InvalidateInfo> mViewRects = 4377 new ArrayList<AttachInfo.InvalidateInfo>(); 4378 private View[] mTempViews; 4379 private AttachInfo.InvalidateInfo[] mTempViewRects; 4380 4381 public void addView(View view) { 4382 synchronized (this) { 4383 mViews.add(view); 4384 postIfNeededLocked(); 4385 } 4386 } 4387 4388 public void addViewRect(AttachInfo.InvalidateInfo info) { 4389 synchronized (this) { 4390 mViewRects.add(info); 4391 postIfNeededLocked(); 4392 } 4393 } 4394 4395 public void removeView(View view) { 4396 synchronized (this) { 4397 mViews.remove(view); 4398 4399 for (int i = mViewRects.size(); i-- > 0; ) { 4400 AttachInfo.InvalidateInfo info = mViewRects.get(i); 4401 if (info.target == view) { 4402 mViewRects.remove(i); 4403 info.release(); 4404 } 4405 } 4406 4407 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) { 4408 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null); 4409 mPosted = false; 4410 } 4411 } 4412 } 4413 4414 @Override 4415 public void run() { 4416 final int viewCount; 4417 final int viewRectCount; 4418 synchronized (this) { 4419 mPosted = false; 4420 4421 viewCount = mViews.size(); 4422 if (viewCount != 0) { 4423 mTempViews = mViews.toArray(mTempViews != null 4424 ? mTempViews : new View[viewCount]); 4425 mViews.clear(); 4426 } 4427 4428 viewRectCount = mViewRects.size(); 4429 if (viewRectCount != 0) { 4430 mTempViewRects = mViewRects.toArray(mTempViewRects != null 4431 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]); 4432 mViewRects.clear(); 4433 } 4434 } 4435 4436 for (int i = 0; i < viewCount; i++) { 4437 mTempViews[i].invalidate(); 4438 mTempViews[i] = null; 4439 } 4440 4441 for (int i = 0; i < viewRectCount; i++) { 4442 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i]; 4443 info.target.invalidate(info.left, info.top, info.right, info.bottom); 4444 info.release(); 4445 } 4446 } 4447 4448 private void postIfNeededLocked() { 4449 if (!mPosted) { 4450 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 4451 mPosted = true; 4452 } 4453 } 4454 } 4455 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable = 4456 new InvalidateOnAnimationRunnable(); 4457 4458 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) { 4459 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 4460 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4461 } 4462 4463 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info, 4464 long delayMilliseconds) { 4465 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info); 4466 mHandler.sendMessageDelayed(msg, delayMilliseconds); 4467 } 4468 4469 public void dispatchInvalidateOnAnimation(View view) { 4470 mInvalidateOnAnimationRunnable.addView(view); 4471 } 4472 4473 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) { 4474 mInvalidateOnAnimationRunnable.addViewRect(info); 4475 } 4476 4477 public void enqueueDisplayList(DisplayList displayList) { 4478 mDisplayLists.add(displayList); 4479 4480 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4481 Message msg = mHandler.obtainMessage(MSG_INVALIDATE_DISPLAY_LIST); 4482 mHandler.sendMessage(msg); 4483 } 4484 4485 public void dequeueDisplayList(DisplayList displayList) { 4486 if (mDisplayLists.remove(displayList)) { 4487 displayList.invalidate(); 4488 if (mDisplayLists.size() == 0) { 4489 mHandler.removeMessages(MSG_INVALIDATE_DISPLAY_LIST); 4490 } 4491 } 4492 } 4493 4494 public void cancelInvalidate(View view) { 4495 mHandler.removeMessages(MSG_INVALIDATE, view); 4496 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning 4497 // them to the pool 4498 mHandler.removeMessages(MSG_INVALIDATE_RECT, view); 4499 mInvalidateOnAnimationRunnable.removeView(view); 4500 } 4501 4502 public void dispatchKey(KeyEvent event) { 4503 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY, event); 4504 msg.setAsynchronous(true); 4505 mHandler.sendMessage(msg); 4506 } 4507 4508 public void dispatchKeyFromIme(KeyEvent event) { 4509 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event); 4510 msg.setAsynchronous(true); 4511 mHandler.sendMessage(msg); 4512 } 4513 4514 public void dispatchUnhandledKey(KeyEvent event) { 4515 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { 4516 final KeyCharacterMap kcm = event.getKeyCharacterMap(); 4517 final int keyCode = event.getKeyCode(); 4518 final int metaState = event.getMetaState(); 4519 4520 // Check for fallback actions specified by the key character map. 4521 KeyCharacterMap.FallbackAction fallbackAction = 4522 kcm.getFallbackAction(keyCode, metaState); 4523 if (fallbackAction != null) { 4524 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; 4525 KeyEvent fallbackEvent = KeyEvent.obtain( 4526 event.getDownTime(), event.getEventTime(), 4527 event.getAction(), fallbackAction.keyCode, 4528 event.getRepeatCount(), fallbackAction.metaState, 4529 event.getDeviceId(), event.getScanCode(), 4530 flags, event.getSource(), null); 4531 fallbackAction.recycle(); 4532 4533 dispatchKey(fallbackEvent); 4534 } 4535 } 4536 } 4537 4538 public void dispatchAppVisibility(boolean visible) { 4539 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY); 4540 msg.arg1 = visible ? 1 : 0; 4541 mHandler.sendMessage(msg); 4542 } 4543 4544 public void dispatchScreenStateChange(boolean on) { 4545 Message msg = mHandler.obtainMessage(MSG_DISPATCH_SCREEN_STATE); 4546 msg.arg1 = on ? 1 : 0; 4547 mHandler.sendMessage(msg); 4548 } 4549 4550 public void dispatchGetNewSurface() { 4551 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE); 4552 mHandler.sendMessage(msg); 4553 } 4554 4555 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4556 Message msg = Message.obtain(); 4557 msg.what = MSG_WINDOW_FOCUS_CHANGED; 4558 msg.arg1 = hasFocus ? 1 : 0; 4559 msg.arg2 = inTouchMode ? 1 : 0; 4560 mHandler.sendMessage(msg); 4561 } 4562 4563 public void dispatchCloseSystemDialogs(String reason) { 4564 Message msg = Message.obtain(); 4565 msg.what = MSG_CLOSE_SYSTEM_DIALOGS; 4566 msg.obj = reason; 4567 mHandler.sendMessage(msg); 4568 } 4569 4570 public void dispatchDragEvent(DragEvent event) { 4571 final int what; 4572 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { 4573 what = MSG_DISPATCH_DRAG_LOCATION_EVENT; 4574 mHandler.removeMessages(what); 4575 } else { 4576 what = MSG_DISPATCH_DRAG_EVENT; 4577 } 4578 Message msg = mHandler.obtainMessage(what, event); 4579 mHandler.sendMessage(msg); 4580 } 4581 4582 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4583 int localValue, int localChanges) { 4584 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo(); 4585 args.seq = seq; 4586 args.globalVisibility = globalVisibility; 4587 args.localValue = localValue; 4588 args.localChanges = localChanges; 4589 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args)); 4590 } 4591 4592 public void dispatchDoneAnimating() { 4593 mHandler.sendEmptyMessage(MSG_DISPATCH_DONE_ANIMATING); 4594 } 4595 4596 public void dispatchCheckFocus() { 4597 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) { 4598 // This will result in a call to checkFocus() below. 4599 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS); 4600 } 4601 } 4602 4603 /** 4604 * Post a callback to send a 4605 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4606 * This event is send at most once every 4607 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 4608 */ 4609 private void postSendWindowContentChangedCallback(View source) { 4610 if (mSendWindowContentChangedAccessibilityEvent == null) { 4611 mSendWindowContentChangedAccessibilityEvent = 4612 new SendWindowContentChangedAccessibilityEvent(); 4613 } 4614 View oldSource = mSendWindowContentChangedAccessibilityEvent.mSource; 4615 if (oldSource == null) { 4616 mSendWindowContentChangedAccessibilityEvent.mSource = source; 4617 mHandler.postDelayed(mSendWindowContentChangedAccessibilityEvent, 4618 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 4619 } else { 4620 mSendWindowContentChangedAccessibilityEvent.mSource = 4621 getCommonPredecessor(oldSource, source); 4622 } 4623 } 4624 4625 /** 4626 * Remove a posted callback to send a 4627 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event. 4628 */ 4629 private void removeSendWindowContentChangedCallback() { 4630 if (mSendWindowContentChangedAccessibilityEvent != null) { 4631 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent); 4632 } 4633 } 4634 4635 public boolean showContextMenuForChild(View originalView) { 4636 return false; 4637 } 4638 4639 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 4640 return null; 4641 } 4642 4643 public void createContextMenu(ContextMenu menu) { 4644 } 4645 4646 public void childDrawableStateChanged(View child) { 4647 } 4648 4649 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 4650 if (mView == null) { 4651 return false; 4652 } 4653 // Intercept accessibility focus events fired by virtual nodes to keep 4654 // track of accessibility focus position in such nodes. 4655 final int eventType = event.getEventType(); 4656 switch (eventType) { 4657 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { 4658 final long sourceNodeId = event.getSourceNodeId(); 4659 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 4660 sourceNodeId); 4661 View source = mView.findViewByAccessibilityId(accessibilityViewId); 4662 if (source != null) { 4663 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 4664 if (provider != null) { 4665 AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo( 4666 AccessibilityNodeInfo.getVirtualDescendantId(sourceNodeId)); 4667 setAccessibilityFocus(source, node); 4668 } 4669 } 4670 } break; 4671 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { 4672 final long sourceNodeId = event.getSourceNodeId(); 4673 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId( 4674 sourceNodeId); 4675 View source = mView.findViewByAccessibilityId(accessibilityViewId); 4676 if (source != null) { 4677 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider(); 4678 if (provider != null) { 4679 setAccessibilityFocus(null, null); 4680 } 4681 } 4682 } break; 4683 } 4684 mAccessibilityManager.sendAccessibilityEvent(event); 4685 return true; 4686 } 4687 4688 @Override 4689 public void childAccessibilityStateChanged(View child) { 4690 postSendWindowContentChangedCallback(child); 4691 } 4692 4693 private View getCommonPredecessor(View first, View second) { 4694 if (mAttachInfo != null) { 4695 if (mTempHashSet == null) { 4696 mTempHashSet = new HashSet<View>(); 4697 } 4698 HashSet<View> seen = mTempHashSet; 4699 seen.clear(); 4700 View firstCurrent = first; 4701 while (firstCurrent != null) { 4702 seen.add(firstCurrent); 4703 ViewParent firstCurrentParent = firstCurrent.mParent; 4704 if (firstCurrentParent instanceof View) { 4705 firstCurrent = (View) firstCurrentParent; 4706 } else { 4707 firstCurrent = null; 4708 } 4709 } 4710 View secondCurrent = second; 4711 while (secondCurrent != null) { 4712 if (seen.contains(secondCurrent)) { 4713 seen.clear(); 4714 return secondCurrent; 4715 } 4716 ViewParent secondCurrentParent = secondCurrent.mParent; 4717 if (secondCurrentParent instanceof View) { 4718 secondCurrent = (View) secondCurrentParent; 4719 } else { 4720 secondCurrent = null; 4721 } 4722 } 4723 seen.clear(); 4724 } 4725 return null; 4726 } 4727 4728 void checkThread() { 4729 if (mThread != Thread.currentThread()) { 4730 throw new CalledFromWrongThreadException( 4731 "Only the original thread that created a view hierarchy can touch its views."); 4732 } 4733 } 4734 4735 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 4736 // ViewAncestor never intercepts touch event, so this can be a no-op 4737 } 4738 4739 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 4740 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate); 4741 if (rectangle != null) { 4742 mTempRect.set(rectangle); 4743 mTempRect.offset(0, -mCurScrollY); 4744 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4745 try { 4746 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect, immediate); 4747 } catch (RemoteException re) { 4748 /* ignore */ 4749 } 4750 } 4751 return scrolled; 4752 } 4753 4754 public void childHasTransientStateChanged(View child, boolean hasTransientState) { 4755 // Do nothing. 4756 } 4757 4758 class TakenSurfaceHolder extends BaseSurfaceHolder { 4759 @Override 4760 public boolean onAllowLockCanvas() { 4761 return mDrawingAllowed; 4762 } 4763 4764 @Override 4765 public void onRelayoutContainer() { 4766 // Not currently interesting -- from changing between fixed and layout size. 4767 } 4768 4769 public void setFormat(int format) { 4770 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format); 4771 } 4772 4773 public void setType(int type) { 4774 ((RootViewSurfaceTaker)mView).setSurfaceType(type); 4775 } 4776 4777 @Override 4778 public void onUpdateSurface() { 4779 // We take care of format and type changes on our own. 4780 throw new IllegalStateException("Shouldn't be here"); 4781 } 4782 4783 public boolean isCreating() { 4784 return mIsCreating; 4785 } 4786 4787 @Override 4788 public void setFixedSize(int width, int height) { 4789 throw new UnsupportedOperationException( 4790 "Currently only support sizing from layout"); 4791 } 4792 4793 public void setKeepScreenOn(boolean screenOn) { 4794 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn); 4795 } 4796 } 4797 4798 static final class InputMethodCallback implements InputMethodManager.FinishedEventCallback { 4799 private WeakReference<ViewRootImpl> mViewAncestor; 4800 4801 public InputMethodCallback(ViewRootImpl viewAncestor) { 4802 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4803 } 4804 4805 @Override 4806 public void finishedEvent(int seq, boolean handled) { 4807 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4808 if (viewAncestor != null) { 4809 viewAncestor.dispatchImeFinishedEvent(seq, handled); 4810 } 4811 } 4812 } 4813 4814 static class W extends IWindow.Stub { 4815 private final WeakReference<ViewRootImpl> mViewAncestor; 4816 private final IWindowSession mWindowSession; 4817 4818 W(ViewRootImpl viewAncestor) { 4819 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor); 4820 mWindowSession = viewAncestor.mWindowSession; 4821 } 4822 4823 public void resized(Rect frame, Rect contentInsets, 4824 Rect visibleInsets, boolean reportDraw, Configuration newConfig) { 4825 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4826 if (viewAncestor != null) { 4827 viewAncestor.dispatchResized(frame, contentInsets, 4828 visibleInsets, reportDraw, newConfig); 4829 } 4830 } 4831 4832 @Override 4833 public void moved(int newX, int newY) { 4834 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4835 if (viewAncestor != null) { 4836 viewAncestor.dispatchMoved(newX, newY); 4837 } 4838 } 4839 4840 public void dispatchAppVisibility(boolean visible) { 4841 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4842 if (viewAncestor != null) { 4843 viewAncestor.dispatchAppVisibility(visible); 4844 } 4845 } 4846 4847 public void dispatchScreenState(boolean on) { 4848 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4849 if (viewAncestor != null) { 4850 viewAncestor.dispatchScreenStateChange(on); 4851 } 4852 } 4853 4854 public void dispatchGetNewSurface() { 4855 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4856 if (viewAncestor != null) { 4857 viewAncestor.dispatchGetNewSurface(); 4858 } 4859 } 4860 4861 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) { 4862 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4863 if (viewAncestor != null) { 4864 viewAncestor.windowFocusChanged(hasFocus, inTouchMode); 4865 } 4866 } 4867 4868 private static int checkCallingPermission(String permission) { 4869 try { 4870 return ActivityManagerNative.getDefault().checkPermission( 4871 permission, Binder.getCallingPid(), Binder.getCallingUid()); 4872 } catch (RemoteException e) { 4873 return PackageManager.PERMISSION_DENIED; 4874 } 4875 } 4876 4877 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 4878 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4879 if (viewAncestor != null) { 4880 final View view = viewAncestor.mView; 4881 if (view != null) { 4882 if (checkCallingPermission(Manifest.permission.DUMP) != 4883 PackageManager.PERMISSION_GRANTED) { 4884 throw new SecurityException("Insufficient permissions to invoke" 4885 + " executeCommand() from pid=" + Binder.getCallingPid() 4886 + ", uid=" + Binder.getCallingUid()); 4887 } 4888 4889 OutputStream clientStream = null; 4890 try { 4891 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out); 4892 ViewDebug.dispatchCommand(view, command, parameters, clientStream); 4893 } catch (IOException e) { 4894 e.printStackTrace(); 4895 } finally { 4896 if (clientStream != null) { 4897 try { 4898 clientStream.close(); 4899 } catch (IOException e) { 4900 e.printStackTrace(); 4901 } 4902 } 4903 } 4904 } 4905 } 4906 } 4907 4908 public void closeSystemDialogs(String reason) { 4909 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4910 if (viewAncestor != null) { 4911 viewAncestor.dispatchCloseSystemDialogs(reason); 4912 } 4913 } 4914 4915 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, 4916 boolean sync) { 4917 if (sync) { 4918 try { 4919 mWindowSession.wallpaperOffsetsComplete(asBinder()); 4920 } catch (RemoteException e) { 4921 } 4922 } 4923 } 4924 4925 public void dispatchWallpaperCommand(String action, int x, int y, 4926 int z, Bundle extras, boolean sync) { 4927 if (sync) { 4928 try { 4929 mWindowSession.wallpaperCommandComplete(asBinder(), null); 4930 } catch (RemoteException e) { 4931 } 4932 } 4933 } 4934 4935 /* Drag/drop */ 4936 public void dispatchDragEvent(DragEvent event) { 4937 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4938 if (viewAncestor != null) { 4939 viewAncestor.dispatchDragEvent(event); 4940 } 4941 } 4942 4943 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility, 4944 int localValue, int localChanges) { 4945 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4946 if (viewAncestor != null) { 4947 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility, 4948 localValue, localChanges); 4949 } 4950 } 4951 4952 public void doneAnimating() { 4953 final ViewRootImpl viewAncestor = mViewAncestor.get(); 4954 if (viewAncestor != null) { 4955 viewAncestor.dispatchDoneAnimating(); 4956 } 4957 } 4958 } 4959 4960 /** 4961 * Maintains state information for a single trackball axis, generating 4962 * discrete (DPAD) movements based on raw trackball motion. 4963 */ 4964 static final class TrackballAxis { 4965 /** 4966 * The maximum amount of acceleration we will apply. 4967 */ 4968 static final float MAX_ACCELERATION = 20; 4969 4970 /** 4971 * The maximum amount of time (in milliseconds) between events in order 4972 * for us to consider the user to be doing fast trackball movements, 4973 * and thus apply an acceleration. 4974 */ 4975 static final long FAST_MOVE_TIME = 150; 4976 4977 /** 4978 * Scaling factor to the time (in milliseconds) between events to how 4979 * much to multiple/divide the current acceleration. When movement 4980 * is < FAST_MOVE_TIME this multiplies the acceleration; when > 4981 * FAST_MOVE_TIME it divides it. 4982 */ 4983 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40); 4984 4985 float position; 4986 float absPosition; 4987 float acceleration = 1; 4988 long lastMoveTime = 0; 4989 int step; 4990 int dir; 4991 int nonAccelMovement; 4992 4993 void reset(int _step) { 4994 position = 0; 4995 acceleration = 1; 4996 lastMoveTime = 0; 4997 step = _step; 4998 dir = 0; 4999 } 5000 5001 /** 5002 * Add trackball movement into the state. If the direction of movement 5003 * has been reversed, the state is reset before adding the 5004 * movement (so that you don't have to compensate for any previously 5005 * collected movement before see the result of the movement in the 5006 * new direction). 5007 * 5008 * @return Returns the absolute value of the amount of movement 5009 * collected so far. 5010 */ 5011 float collect(float off, long time, String axis) { 5012 long normTime; 5013 if (off > 0) { 5014 normTime = (long)(off * FAST_MOVE_TIME); 5015 if (dir < 0) { 5016 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!"); 5017 position = 0; 5018 step = 0; 5019 acceleration = 1; 5020 lastMoveTime = 0; 5021 } 5022 dir = 1; 5023 } else if (off < 0) { 5024 normTime = (long)((-off) * FAST_MOVE_TIME); 5025 if (dir > 0) { 5026 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!"); 5027 position = 0; 5028 step = 0; 5029 acceleration = 1; 5030 lastMoveTime = 0; 5031 } 5032 dir = -1; 5033 } else { 5034 normTime = 0; 5035 } 5036 5037 // The number of milliseconds between each movement that is 5038 // considered "normal" and will not result in any acceleration 5039 // or deceleration, scaled by the offset we have here. 5040 if (normTime > 0) { 5041 long delta = time - lastMoveTime; 5042 lastMoveTime = time; 5043 float acc = acceleration; 5044 if (delta < normTime) { 5045 // The user is scrolling rapidly, so increase acceleration. 5046 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR; 5047 if (scale > 1) acc *= scale; 5048 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off=" 5049 + off + " normTime=" + normTime + " delta=" + delta 5050 + " scale=" + scale + " acc=" + acc); 5051 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION; 5052 } else { 5053 // The user is scrolling slowly, so decrease acceleration. 5054 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR; 5055 if (scale > 1) acc /= scale; 5056 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off=" 5057 + off + " normTime=" + normTime + " delta=" + delta 5058 + " scale=" + scale + " acc=" + acc); 5059 acceleration = acc > 1 ? acc : 1; 5060 } 5061 } 5062 position += off; 5063 return (absPosition = Math.abs(position)); 5064 } 5065 5066 /** 5067 * Generate the number of discrete movement events appropriate for 5068 * the currently collected trackball movement. 5069 * 5070 * @param precision The minimum movement required to generate the 5071 * first discrete movement. 5072 * 5073 * @return Returns the number of discrete movements, either positive 5074 * or negative, or 0 if there is not enough trackball movement yet 5075 * for a discrete movement. 5076 */ 5077 int generate(float precision) { 5078 int movement = 0; 5079 nonAccelMovement = 0; 5080 do { 5081 final int dir = position >= 0 ? 1 : -1; 5082 switch (step) { 5083 // If we are going to execute the first step, then we want 5084 // to do this as soon as possible instead of waiting for 5085 // a full movement, in order to make things look responsive. 5086 case 0: 5087 if (absPosition < precision) { 5088 return movement; 5089 } 5090 movement += dir; 5091 nonAccelMovement += dir; 5092 step = 1; 5093 break; 5094 // If we have generated the first movement, then we need 5095 // to wait for the second complete trackball motion before 5096 // generating the second discrete movement. 5097 case 1: 5098 if (absPosition < 2) { 5099 return movement; 5100 } 5101 movement += dir; 5102 nonAccelMovement += dir; 5103 position += dir > 0 ? -2 : 2; 5104 absPosition = Math.abs(position); 5105 step = 2; 5106 break; 5107 // After the first two, we generate discrete movements 5108 // consistently with the trackball, applying an acceleration 5109 // if the trackball is moving quickly. This is a simple 5110 // acceleration on top of what we already compute based 5111 // on how quickly the wheel is being turned, to apply 5112 // a longer increasing acceleration to continuous movement 5113 // in one direction. 5114 default: 5115 if (absPosition < 1) { 5116 return movement; 5117 } 5118 movement += dir; 5119 position += dir >= 0 ? -1 : 1; 5120 absPosition = Math.abs(position); 5121 float acc = acceleration; 5122 acc *= 1.1f; 5123 acceleration = acc < MAX_ACCELERATION ? acc : acceleration; 5124 break; 5125 } 5126 } while (true); 5127 } 5128 } 5129 5130 public static final class CalledFromWrongThreadException extends AndroidRuntimeException { 5131 public CalledFromWrongThreadException(String msg) { 5132 super(msg); 5133 } 5134 } 5135 5136 private SurfaceHolder mHolder = new SurfaceHolder() { 5137 // we only need a SurfaceHolder for opengl. it would be nice 5138 // to implement everything else though, especially the callback 5139 // support (opengl doesn't make use of it right now, but eventually 5140 // will). 5141 public Surface getSurface() { 5142 return mSurface; 5143 } 5144 5145 public boolean isCreating() { 5146 return false; 5147 } 5148 5149 public void addCallback(Callback callback) { 5150 } 5151 5152 public void removeCallback(Callback callback) { 5153 } 5154 5155 public void setFixedSize(int width, int height) { 5156 } 5157 5158 public void setSizeFromLayout() { 5159 } 5160 5161 public void setFormat(int format) { 5162 } 5163 5164 public void setType(int type) { 5165 } 5166 5167 public void setKeepScreenOn(boolean screenOn) { 5168 } 5169 5170 public Canvas lockCanvas() { 5171 return null; 5172 } 5173 5174 public Canvas lockCanvas(Rect dirty) { 5175 return null; 5176 } 5177 5178 public void unlockCanvasAndPost(Canvas canvas) { 5179 } 5180 public Rect getSurfaceFrame() { 5181 return null; 5182 } 5183 }; 5184 5185 static RunQueue getRunQueue() { 5186 RunQueue rq = sRunQueues.get(); 5187 if (rq != null) { 5188 return rq; 5189 } 5190 rq = new RunQueue(); 5191 sRunQueues.set(rq); 5192 return rq; 5193 } 5194 5195 /** 5196 * The run queue is used to enqueue pending work from Views when no Handler is 5197 * attached. The work is executed during the next call to performTraversals on 5198 * the thread. 5199 * @hide 5200 */ 5201 static final class RunQueue { 5202 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); 5203 5204 void post(Runnable action) { 5205 postDelayed(action, 0); 5206 } 5207 5208 void postDelayed(Runnable action, long delayMillis) { 5209 HandlerAction handlerAction = new HandlerAction(); 5210 handlerAction.action = action; 5211 handlerAction.delay = delayMillis; 5212 5213 synchronized (mActions) { 5214 mActions.add(handlerAction); 5215 } 5216 } 5217 5218 void removeCallbacks(Runnable action) { 5219 final HandlerAction handlerAction = new HandlerAction(); 5220 handlerAction.action = action; 5221 5222 synchronized (mActions) { 5223 final ArrayList<HandlerAction> actions = mActions; 5224 5225 while (actions.remove(handlerAction)) { 5226 // Keep going 5227 } 5228 } 5229 } 5230 5231 void executeActions(Handler handler) { 5232 synchronized (mActions) { 5233 final ArrayList<HandlerAction> actions = mActions; 5234 final int count = actions.size(); 5235 5236 for (int i = 0; i < count; i++) { 5237 final HandlerAction handlerAction = actions.get(i); 5238 handler.postDelayed(handlerAction.action, handlerAction.delay); 5239 } 5240 5241 actions.clear(); 5242 } 5243 } 5244 5245 private static class HandlerAction { 5246 Runnable action; 5247 long delay; 5248 5249 @Override 5250 public boolean equals(Object o) { 5251 if (this == o) return true; 5252 if (o == null || getClass() != o.getClass()) return false; 5253 5254 HandlerAction that = (HandlerAction) o; 5255 return !(action != null ? !action.equals(that.action) : that.action != null); 5256 5257 } 5258 5259 @Override 5260 public int hashCode() { 5261 int result = action != null ? action.hashCode() : 0; 5262 result = 31 * result + (int) (delay ^ (delay >>> 32)); 5263 return result; 5264 } 5265 } 5266 } 5267 5268 /** 5269 * Class for managing the accessibility interaction connection 5270 * based on the global accessibility state. 5271 */ 5272 final class AccessibilityInteractionConnectionManager 5273 implements AccessibilityStateChangeListener { 5274 public void onAccessibilityStateChanged(boolean enabled) { 5275 if (enabled) { 5276 ensureConnection(); 5277 if (mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 5278 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 5279 View focusedView = mView.findFocus(); 5280 if (focusedView != null && focusedView != mView) { 5281 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5282 } 5283 } 5284 } else { 5285 ensureNoConnection(); 5286 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget(); 5287 } 5288 } 5289 5290 public void ensureConnection() { 5291 if (mAttachInfo != null) { 5292 final boolean registered = 5293 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5294 if (!registered) { 5295 mAttachInfo.mAccessibilityWindowId = 5296 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow, 5297 new AccessibilityInteractionConnection(ViewRootImpl.this)); 5298 } 5299 } 5300 } 5301 5302 public void ensureNoConnection() { 5303 final boolean registered = 5304 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED; 5305 if (registered) { 5306 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED; 5307 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow); 5308 } 5309 } 5310 } 5311 5312 /** 5313 * This class is an interface this ViewAncestor provides to the 5314 * AccessibilityManagerService to the latter can interact with 5315 * the view hierarchy in this ViewAncestor. 5316 */ 5317 static final class AccessibilityInteractionConnection 5318 extends IAccessibilityInteractionConnection.Stub { 5319 private final WeakReference<ViewRootImpl> mViewRootImpl; 5320 5321 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) { 5322 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl); 5323 } 5324 5325 @Override 5326 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId, 5327 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5328 int interrogatingPid, long interrogatingTid) { 5329 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5330 if (viewRootImpl != null && viewRootImpl.mView != null) { 5331 viewRootImpl.getAccessibilityInteractionController() 5332 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId, 5333 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5334 } else { 5335 // We cannot make the call and notify the caller so it does not wait. 5336 try { 5337 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5338 } catch (RemoteException re) { 5339 /* best effort - ignore */ 5340 } 5341 } 5342 } 5343 5344 @Override 5345 public void performAccessibilityAction(long accessibilityNodeId, int action, 5346 Bundle arguments, int interactionId, 5347 IAccessibilityInteractionConnectionCallback callback, int flags, 5348 int interogatingPid, long interrogatingTid) { 5349 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5350 if (viewRootImpl != null && viewRootImpl.mView != null) { 5351 viewRootImpl.getAccessibilityInteractionController() 5352 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments, 5353 interactionId, callback, flags, interogatingPid, interrogatingTid); 5354 } else { 5355 // We cannot make the call and notify the caller so it does not wait. 5356 try { 5357 callback.setPerformAccessibilityActionResult(false, interactionId); 5358 } catch (RemoteException re) { 5359 /* best effort - ignore */ 5360 } 5361 } 5362 } 5363 5364 @Override 5365 public void findAccessibilityNodeInfoByViewId(long accessibilityNodeId, int viewId, 5366 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5367 int interrogatingPid, long interrogatingTid) { 5368 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5369 if (viewRootImpl != null && viewRootImpl.mView != null) { 5370 viewRootImpl.getAccessibilityInteractionController() 5371 .findAccessibilityNodeInfoByViewIdClientThread(accessibilityNodeId, viewId, 5372 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5373 } else { 5374 // We cannot make the call and notify the caller so it does not wait. 5375 try { 5376 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5377 } catch (RemoteException re) { 5378 /* best effort - ignore */ 5379 } 5380 } 5381 } 5382 5383 @Override 5384 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text, 5385 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags, 5386 int interrogatingPid, long interrogatingTid) { 5387 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5388 if (viewRootImpl != null && viewRootImpl.mView != null) { 5389 viewRootImpl.getAccessibilityInteractionController() 5390 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text, 5391 interactionId, callback, flags, interrogatingPid, interrogatingTid); 5392 } else { 5393 // We cannot make the call and notify the caller so it does not wait. 5394 try { 5395 callback.setFindAccessibilityNodeInfosResult(null, interactionId); 5396 } catch (RemoteException re) { 5397 /* best effort - ignore */ 5398 } 5399 } 5400 } 5401 5402 @Override 5403 public void findFocus(long accessibilityNodeId, int focusType, int interactionId, 5404 IAccessibilityInteractionConnectionCallback callback, int flags, 5405 int interrogatingPid, long interrogatingTid) { 5406 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5407 if (viewRootImpl != null && viewRootImpl.mView != null) { 5408 viewRootImpl.getAccessibilityInteractionController() 5409 .findFocusClientThread(accessibilityNodeId, focusType, interactionId, callback, 5410 flags, interrogatingPid, interrogatingTid); 5411 } else { 5412 // We cannot make the call and notify the caller so it does not wait. 5413 try { 5414 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5415 } catch (RemoteException re) { 5416 /* best effort - ignore */ 5417 } 5418 } 5419 } 5420 5421 @Override 5422 public void focusSearch(long accessibilityNodeId, int direction, int interactionId, 5423 IAccessibilityInteractionConnectionCallback callback, int flags, 5424 int interrogatingPid, long interrogatingTid) { 5425 ViewRootImpl viewRootImpl = mViewRootImpl.get(); 5426 if (viewRootImpl != null && viewRootImpl.mView != null) { 5427 viewRootImpl.getAccessibilityInteractionController() 5428 .focusSearchClientThread(accessibilityNodeId, direction, interactionId, 5429 callback, flags, interrogatingPid, interrogatingTid); 5430 } else { 5431 // We cannot make the call and notify the caller so it does not wait. 5432 try { 5433 callback.setFindAccessibilityNodeInfoResult(null, interactionId); 5434 } catch (RemoteException re) { 5435 /* best effort - ignore */ 5436 } 5437 } 5438 } 5439 } 5440 5441 private class SendWindowContentChangedAccessibilityEvent implements Runnable { 5442 public View mSource; 5443 5444 public void run() { 5445 if (mSource != null) { 5446 mSource.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 5447 mSource.resetAccessibilityStateChanged(); 5448 mSource = null; 5449 } 5450 } 5451 } 5452} 5453