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