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