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