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