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