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