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