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