blob: a6d644be201eb1285f6f472171b7f9cd86352651 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import com.android.internal.view.IInputMethodCallback;
20import com.android.internal.view.IInputMethodSession;
21
22import android.graphics.Canvas;
23import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.graphics.PorterDuff;
25import android.graphics.Rect;
26import android.graphics.Region;
27import android.os.*;
28import android.os.Process;
29import android.os.SystemProperties;
30import android.util.AndroidRuntimeException;
31import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070032import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.util.Log;
34import android.util.EventLog;
35import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070037import android.view.accessibility.AccessibilityEvent;
38import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.view.inputmethod.InputConnection;
40import android.view.inputmethod.InputMethodManager;
41import android.widget.Scroller;
42import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070043import android.content.res.CompatibilityInfo;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070044import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.Context;
46import android.app.ActivityManagerNative;
47import android.Manifest;
48import android.media.AudioManager;
49
50import java.lang.ref.WeakReference;
51import java.io.IOException;
52import java.io.OutputStream;
53import java.util.ArrayList;
54
55import javax.microedition.khronos.egl.*;
56import javax.microedition.khronos.opengles.*;
57import static javax.microedition.khronos.opengles.GL10.*;
58
59/**
60 * The top of a view hierarchy, implementing the needed protocol between View
61 * and the WindowManager. This is for the most part an internal implementation
62 * detail of {@link WindowManagerImpl}.
63 *
64 * {@hide}
65 */
66@SuppressWarnings({"EmptyCatchBlock"})
67public final class ViewRoot extends Handler implements ViewParent,
68 View.AttachInfo.Callbacks {
69 private static final String TAG = "ViewRoot";
70 private static final boolean DBG = false;
71 @SuppressWarnings({"ConstantConditionalExpression"})
72 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
73 /** @noinspection PointlessBooleanExpression*/
74 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
75 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
76 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
77 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
78 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
79 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
80 private static final boolean WATCH_POINTER = false;
81
Michael Chan53071d62009-05-13 17:29:48 -070082 private static final boolean MEASURE_LATENCY = false;
83 private static LatencyTimer lt;
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 /**
86 * Maximum time we allow the user to roll the trackball enough to generate
87 * a key event, before resetting the counters.
88 */
89 static final int MAX_TRACKBALL_DELAY = 250;
90
91 static long sInstanceCount = 0;
92
93 static IWindowSession sWindowSession;
94
95 static final Object mStaticInit = new Object();
96 static boolean mInitialized = false;
97
98 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
99
Romain Guy8506ab42009-06-11 17:35:47 -0700100 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 long mLastTrackballTime = 0;
103 final TrackballAxis mTrackballAxisX = new TrackballAxis();
104 final TrackballAxis mTrackballAxisY = new TrackballAxis();
105
106 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 final InputMethodCallback mInputMethodCallback;
109 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
110 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 final Thread mThread;
113
114 final WindowLeaked mLocation;
115
116 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
117
118 final W mWindow;
119
120 View mView;
121 View mFocusedView;
122 View mRealFocusedView; // this is not set to null in touch mode
123 int mViewVisibility;
124 boolean mAppVisible = true;
125
126 final Region mTransparentRegion;
127 final Region mPreviousTransparentRegion;
128
129 int mWidth;
130 int mHeight;
131 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700132 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700133
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700134 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
136 final View.AttachInfo mAttachInfo;
137
138 final Rect mTempRect; // used in the transaction to not thrash the heap.
139 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 boolean mTraversalScheduled;
142 boolean mWillDrawSoon;
143 boolean mLayoutRequested;
144 boolean mFirst;
145 boolean mReportNextDraw;
146 boolean mFullRedrawNeeded;
147 boolean mNewSurfaceNeeded;
148 boolean mHasHadWindowFocus;
149 boolean mLastWasImTarget;
150
151 boolean mWindowAttributesChanged = false;
152
153 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700154 // Surface can never be reassigned or cleared (use Surface.clear()).
155 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157 boolean mAdded;
158 boolean mAddedTouchMode;
159
160 /*package*/ int mAddNesting;
161
162 // These are accessed by multiple threads.
163 final Rect mWinFrame; // frame given by window manager.
164
165 final Rect mPendingVisibleInsets = new Rect();
166 final Rect mPendingContentInsets = new Rect();
167 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
168 = new ViewTreeObserver.InternalInsetsInfo();
169
170 boolean mScrollMayChange;
171 int mSoftInputMode;
172 View mLastScrolledFocus;
173 int mScrollY;
174 int mCurScrollY;
175 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 EGL10 mEgl;
178 EGLDisplay mEglDisplay;
179 EGLContext mEglContext;
180 EGLSurface mEglSurface;
181 GL11 mGL;
182 Canvas mGlCanvas;
183 boolean mUseGL;
184 boolean mGlWanted;
185
Romain Guy8506ab42009-06-11 17:35:47 -0700186 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 /**
189 * see {@link #playSoundEffect(int)}
190 */
191 AudioManager mAudioManager;
192
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700193 private final int mDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700195 public static IWindowSession getWindowSession(Looper mainLooper) {
196 synchronized (mStaticInit) {
197 if (!mInitialized) {
198 try {
199 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
200 sWindowSession = IWindowManager.Stub.asInterface(
201 ServiceManager.getService("window"))
202 .openSession(imm.getClient(), imm.getInputContext());
203 mInitialized = true;
204 } catch (RemoteException e) {
205 }
206 }
207 return sWindowSession;
208 }
209 }
210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 public ViewRoot(Context context) {
212 super();
213
Michael Chan53071d62009-05-13 17:29:48 -0700214 if (MEASURE_LATENCY && lt == null) {
215 lt = new LatencyTimer(100, 1000);
216 }
217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 ++sInstanceCount;
219
220 // Initialize the statics when this class is first instantiated. This is
221 // done here instead of in the static block because Zygote does not
222 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700223 getWindowSession(context.getMainLooper());
224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 mThread = Thread.currentThread();
226 mLocation = new WindowLeaked(null);
227 mLocation.fillInStackTrace();
228 mWidth = -1;
229 mHeight = -1;
230 mDirty = new Rect();
231 mTempRect = new Rect();
232 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700234 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 mInputMethodCallback = new InputMethodCallback(this);
236 mViewVisibility = View.GONE;
237 mTransparentRegion = new Region();
238 mPreviousTransparentRegion = new Region();
239 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 mAdded = false;
241 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
242 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700243 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
245
246 @Override
247 protected void finalize() throws Throwable {
248 super.finalize();
249 --sInstanceCount;
250 }
251
252 public static long getInstanceCount() {
253 return sInstanceCount;
254 }
255
256 // FIXME for perf testing only
257 private boolean mProfile = false;
258
259 /**
260 * Call this to profile the next traversal call.
261 * FIXME for perf testing only. Remove eventually
262 */
263 public void profile() {
264 mProfile = true;
265 }
266
267 /**
268 * Indicates whether we are in touch mode. Calling this method triggers an IPC
269 * call and should be avoided whenever possible.
270 *
271 * @return True, if the device is in touch mode, false otherwise.
272 *
273 * @hide
274 */
275 static boolean isInTouchMode() {
276 if (mInitialized) {
277 try {
278 return sWindowSession.getInTouchMode();
279 } catch (RemoteException e) {
280 }
281 }
282 return false;
283 }
284
285 private void initializeGL() {
286 initializeGLInner();
287 int err = mEgl.eglGetError();
288 if (err != EGL10.EGL_SUCCESS) {
289 // give-up on using GL
290 destroyGL();
291 mGlWanted = false;
292 }
293 }
294
295 private void initializeGLInner() {
296 final EGL10 egl = (EGL10) EGLContext.getEGL();
297 mEgl = egl;
298
299 /*
300 * Get to the default display.
301 */
302 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
303 mEglDisplay = eglDisplay;
304
305 /*
306 * We can now initialize EGL for that display
307 */
308 int[] version = new int[2];
309 egl.eglInitialize(eglDisplay, version);
310
311 /*
312 * Specify a configuration for our opengl session
313 * and grab the first configuration that matches is
314 */
315 final int[] configSpec = {
316 EGL10.EGL_RED_SIZE, 5,
317 EGL10.EGL_GREEN_SIZE, 6,
318 EGL10.EGL_BLUE_SIZE, 5,
319 EGL10.EGL_DEPTH_SIZE, 0,
320 EGL10.EGL_NONE
321 };
322 final EGLConfig[] configs = new EGLConfig[1];
323 final int[] num_config = new int[1];
324 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
325 final EGLConfig config = configs[0];
326
327 /*
328 * Create an OpenGL ES context. This must be done only once, an
329 * OpenGL context is a somewhat heavy object.
330 */
331 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
332 EGL10.EGL_NO_CONTEXT, null);
333 mEglContext = context;
334
335 /*
336 * Create an EGL surface we can render into.
337 */
338 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
339 mEglSurface = surface;
340
341 /*
342 * Before we can issue GL commands, we need to make sure
343 * the context is current and bound to a surface.
344 */
345 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
346
347 /*
348 * Get to the appropriate GL interface.
349 * This is simply done by casting the GL context to either
350 * GL10 or GL11.
351 */
352 final GL11 gl = (GL11) context.getGL();
353 mGL = gl;
354 mGlCanvas = new Canvas(gl);
355 mUseGL = true;
356 }
357
358 private void destroyGL() {
359 // inform skia that the context is gone
360 nativeAbandonGlCaches();
361
362 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
363 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
364 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
365 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
366 mEgl.eglTerminate(mEglDisplay);
367 mEglContext = null;
368 mEglSurface = null;
369 mEglDisplay = null;
370 mEgl = null;
371 mGlCanvas = null;
372 mGL = null;
373 mUseGL = false;
374 }
375
376 private void checkEglErrors() {
377 if (mUseGL) {
378 int err = mEgl.eglGetError();
379 if (err != EGL10.EGL_SUCCESS) {
380 // something bad has happened revert to
381 // normal rendering.
382 destroyGL();
383 if (err != EGL11.EGL_CONTEXT_LOST) {
384 // we'll try again if it was context lost
385 mGlWanted = false;
386 }
387 }
388 }
389 }
390
391 /**
392 * We have one child
393 */
394 public void setView(View view, WindowManager.LayoutParams attrs,
395 View panelParentView) {
396 synchronized (this) {
397 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700398 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700399 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700400 attrs = mWindowAttributes;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700401 Resources resources = mView.getContext().getResources();
402 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700403 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700404
405 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700406 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
407 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700408 }
409
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700410 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700411 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700412 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700413 attrs.backup();
414 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700415 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700416 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
417
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700418 if (!compatibilityInfo.supportsScreen()) {
419 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
420 }
421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 mSoftInputMode = attrs.softInputMode;
423 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700425 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700426 mAttachInfo.mApplicationScale =
427 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 if (panelParentView != null) {
429 mAttachInfo.mPanelParentWindowToken
430 = panelParentView.getApplicationWindowToken();
431 }
432 mAdded = true;
433 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 // Schedule the first layout -before- adding to the window
436 // manager, to make sure we do the relayout before receiving
437 // any other events from the system.
438 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700440 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 getHostVisibility(), mAttachInfo.mContentInsets);
442 } catch (RemoteException e) {
443 mAdded = false;
444 mView = null;
445 mAttachInfo.mRootView = null;
446 unscheduleTraversals();
447 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700448 } finally {
449 if (restore) {
450 attrs.restore();
451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700453
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700454 if (mTranslator != null) {
455 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 mPendingContentInsets.set(mAttachInfo.mContentInsets);
458 mPendingVisibleInsets.set(0, 0, 0, 0);
459 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
460 if (res < WindowManagerImpl.ADD_OKAY) {
461 mView = null;
462 mAttachInfo.mRootView = null;
463 mAdded = false;
464 unscheduleTraversals();
465 switch (res) {
466 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
467 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
468 throw new WindowManagerImpl.BadTokenException(
469 "Unable to add window -- token " + attrs.token
470 + " is not valid; is your activity running?");
471 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
472 throw new WindowManagerImpl.BadTokenException(
473 "Unable to add window -- token " + attrs.token
474 + " is not for an application");
475 case WindowManagerImpl.ADD_APP_EXITING:
476 throw new WindowManagerImpl.BadTokenException(
477 "Unable to add window -- app for token " + attrs.token
478 + " is exiting");
479 case WindowManagerImpl.ADD_DUPLICATE_ADD:
480 throw new WindowManagerImpl.BadTokenException(
481 "Unable to add window -- window " + mWindow
482 + " has already been added");
483 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
484 // Silently ignore -- we would have just removed it
485 // right away, anyway.
486 return;
487 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
488 throw new WindowManagerImpl.BadTokenException(
489 "Unable to add window " + mWindow +
490 " -- another window of this type already exists");
491 case WindowManagerImpl.ADD_PERMISSION_DENIED:
492 throw new WindowManagerImpl.BadTokenException(
493 "Unable to add window " + mWindow +
494 " -- permission denied for this window type");
495 }
496 throw new RuntimeException(
497 "Unable to add window -- unknown error code " + res);
498 }
499 view.assignParent(this);
500 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
501 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
502 }
503 }
504 }
505
506 public View getView() {
507 return mView;
508 }
509
510 final WindowLeaked getLocation() {
511 return mLocation;
512 }
513
514 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
515 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700516 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700517 // preserve compatible window flag if exists.
518 int compatibleWindowFlag =
519 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700521 mWindowAttributes.flags |= compatibleWindowFlag;
522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 if (newView) {
524 mSoftInputMode = attrs.softInputMode;
525 requestLayout();
526 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700527 // Don't lose the mode we last auto-computed.
528 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
529 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
530 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
531 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
532 | (oldSoftInputMode
533 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 mWindowAttributesChanged = true;
536 scheduleTraversals();
537 }
538 }
539
540 void handleAppVisibility(boolean visible) {
541 if (mAppVisible != visible) {
542 mAppVisible = visible;
543 scheduleTraversals();
544 }
545 }
546
547 void handleGetNewSurface() {
548 mNewSurfaceNeeded = true;
549 mFullRedrawNeeded = true;
550 scheduleTraversals();
551 }
552
553 /**
554 * {@inheritDoc}
555 */
556 public void requestLayout() {
557 checkThread();
558 mLayoutRequested = true;
559 scheduleTraversals();
560 }
561
562 /**
563 * {@inheritDoc}
564 */
565 public boolean isLayoutRequested() {
566 return mLayoutRequested;
567 }
568
569 public void invalidateChild(View child, Rect dirty) {
570 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700571 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
572 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700574 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700575 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700576 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700577 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700578 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700579 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700580 }
Romain Guy1e095972009-07-07 11:22:45 -0700581 if (mAttachInfo.mScalingRequired) {
582 dirty.inset(-1, -1);
583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 }
585 mDirty.union(dirty);
586 if (!mWillDrawSoon) {
587 scheduleTraversals();
588 }
589 }
590
591 public ViewParent getParent() {
592 return null;
593 }
594
595 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
596 invalidateChild(null, dirty);
597 return null;
598 }
599
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700600 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 if (child != mView) {
602 throw new RuntimeException("child is not mine, honest!");
603 }
604 // Note: don't apply scroll offset, because we want to know its
605 // visibility in the virtual canvas being given to the view hierarchy.
606 return r.intersect(0, 0, mWidth, mHeight);
607 }
608
609 public void bringChildToFront(View child) {
610 }
611
612 public void scheduleTraversals() {
613 if (!mTraversalScheduled) {
614 mTraversalScheduled = true;
615 sendEmptyMessage(DO_TRAVERSAL);
616 }
617 }
618
619 public void unscheduleTraversals() {
620 if (mTraversalScheduled) {
621 mTraversalScheduled = false;
622 removeMessages(DO_TRAVERSAL);
623 }
624 }
625
626 int getHostVisibility() {
627 return mAppVisible ? mView.getVisibility() : View.GONE;
628 }
Romain Guy8506ab42009-06-11 17:35:47 -0700629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 private void performTraversals() {
631 // cache mView since it is used so much below...
632 final View host = mView;
633
634 if (DBG) {
635 System.out.println("======================================");
636 System.out.println("performTraversals");
637 host.debug();
638 }
639
640 if (host == null || !mAdded)
641 return;
642
643 mTraversalScheduled = false;
644 mWillDrawSoon = true;
645 boolean windowResizesToFitContent = false;
646 boolean fullRedrawNeeded = mFullRedrawNeeded;
647 boolean newSurface = false;
648 WindowManager.LayoutParams lp = mWindowAttributes;
649
650 int desiredWindowWidth;
651 int desiredWindowHeight;
652 int childWidthMeasureSpec;
653 int childHeightMeasureSpec;
654
655 final View.AttachInfo attachInfo = mAttachInfo;
656
657 final int viewVisibility = getHostVisibility();
658 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
659 || mNewSurfaceNeeded;
660
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700661 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 WindowManager.LayoutParams params = null;
664 if (mWindowAttributesChanged) {
665 mWindowAttributesChanged = false;
666 params = lp;
667 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700668 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 if (mFirst) {
670 fullRedrawNeeded = true;
671 mLayoutRequested = true;
672
Romain Guy8506ab42009-06-11 17:35:47 -0700673 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700674 mView.getContext().getResources().getDisplayMetrics();
675 desiredWindowWidth = packageMetrics.widthPixels;
676 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677
678 // For the very first time, tell the view hierarchy that it
679 // is attached to the window. Note that at this point the surface
680 // object is not initialized to its backing store, but soon it
681 // will be (assuming the window is visible).
682 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700683 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 attachInfo.mHasWindowFocus = false;
685 attachInfo.mWindowVisibility = viewVisibility;
686 attachInfo.mRecomputeGlobalAttributes = false;
687 attachInfo.mKeepScreenOn = false;
688 viewVisibilityChanged = false;
689 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700693 desiredWindowWidth = frame.width();
694 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
696 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700697 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 fullRedrawNeeded = true;
699 mLayoutRequested = true;
700 windowResizesToFitContent = true;
701 }
702 }
703
704 if (viewVisibilityChanged) {
705 attachInfo.mWindowVisibility = viewVisibility;
706 host.dispatchWindowVisibilityChanged(viewVisibility);
707 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
708 if (mUseGL) {
709 destroyGL();
710 }
711 }
712 if (viewVisibility == View.GONE) {
713 // After making a window gone, we will count it as being
714 // shown for the first time the next time it gets focus.
715 mHasHadWindowFocus = false;
716 }
717 }
718
719 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700722 // Execute enqueued actions on every layout in case a view that was detached
723 // enqueued an action after being detached
724 getRunQueue().executeActions(attachInfo.mHandler);
725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 if (mFirst) {
727 host.fitSystemWindows(mAttachInfo.mContentInsets);
728 // make sure touch mode code executes by setting cached value
729 // to opposite of the added touch mode.
730 mAttachInfo.mInTouchMode = !mAddedTouchMode;
731 ensureTouchModeLocally(mAddedTouchMode);
732 } else {
733 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
734 mAttachInfo.mContentInsets.set(mPendingContentInsets);
735 host.fitSystemWindows(mAttachInfo.mContentInsets);
736 insetsChanged = true;
737 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
738 + mAttachInfo.mContentInsets);
739 }
740 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
741 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
742 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
743 + mAttachInfo.mVisibleInsets);
744 }
745 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
746 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
747 windowResizesToFitContent = true;
748
Romain Guy8506ab42009-06-11 17:35:47 -0700749 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700750 mView.getContext().getResources().getDisplayMetrics();
751 desiredWindowWidth = packageMetrics.widthPixels;
752 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754 }
755
756 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
757 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
758
759 // Ask host how big it wants to be
760 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
761 "Measuring " + host + " in display " + desiredWindowWidth
762 + "x" + desiredWindowHeight + "...");
763 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
764
765 if (DBG) {
766 System.out.println("======================================");
767 System.out.println("performTraversals -- after measure");
768 host.debug();
769 }
770 }
771
772 if (attachInfo.mRecomputeGlobalAttributes) {
773 //Log.i(TAG, "Computing screen on!");
774 attachInfo.mRecomputeGlobalAttributes = false;
775 boolean oldVal = attachInfo.mKeepScreenOn;
776 attachInfo.mKeepScreenOn = false;
777 host.dispatchCollectViewAttributes(0);
778 if (attachInfo.mKeepScreenOn != oldVal) {
779 params = lp;
780 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
781 }
782 }
783
784 if (mFirst || attachInfo.mViewVisibilityChanged) {
785 attachInfo.mViewVisibilityChanged = false;
786 int resizeMode = mSoftInputMode &
787 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
788 // If we are in auto resize mode, then we need to determine
789 // what mode to use now.
790 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
791 final int N = attachInfo.mScrollContainers.size();
792 for (int i=0; i<N; i++) {
793 if (attachInfo.mScrollContainers.get(i).isShown()) {
794 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
795 }
796 }
797 if (resizeMode == 0) {
798 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
799 }
800 if ((lp.softInputMode &
801 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
802 lp.softInputMode = (lp.softInputMode &
803 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
804 resizeMode;
805 params = lp;
806 }
807 }
808 }
Romain Guy8506ab42009-06-11 17:35:47 -0700809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
811 if (!PixelFormat.formatHasAlpha(params.format)) {
812 params.format = PixelFormat.TRANSLUCENT;
813 }
814 }
815
816 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
817 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
818
819 final boolean computesInternalInsets =
820 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
821 boolean insetsPending = false;
822 int relayoutResult = 0;
823 if (mFirst || windowShouldResize || insetsChanged
824 || viewVisibilityChanged || params != null) {
825
826 if (viewVisibility == View.VISIBLE) {
827 // If this window is giving internal insets to the window
828 // manager, and it is being added or changing its visibility,
829 // then we want to first give the window manager "fake"
830 // insets to cause it to effectively ignore the content of
831 // the window during layout. This avoids it briefly causing
832 // other windows to resize/move based on the raw frame of the
833 // window, waiting until we can finish laying out this window
834 // and get back to the window manager with the ultimately
835 // computed insets.
836 insetsPending = computesInternalInsets
837 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
840 if (params == null) {
841 params = mWindowAttributes;
842 }
843 mGlWanted = true;
844 }
845 }
846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 boolean initialized = false;
848 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700849 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 try {
851 boolean hadSurface = mSurface.isValid();
852 int fl = 0;
853 if (params != null) {
854 fl = params.flags;
855 if (attachInfo.mKeepScreenOn) {
856 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
857 }
858 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700859 if (DEBUG_LAYOUT) {
860 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
861 host.mMeasuredHeight + ", params=" + params);
862 }
863 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 if (params != null) {
866 params.flags = fl;
867 }
868
869 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
870 + " content=" + mPendingContentInsets.toShortString()
871 + " visible=" + mPendingVisibleInsets.toShortString()
872 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 contentInsetsChanged = !mPendingContentInsets.equals(
875 mAttachInfo.mContentInsets);
876 visibleInsetsChanged = !mPendingVisibleInsets.equals(
877 mAttachInfo.mVisibleInsets);
878 if (contentInsetsChanged) {
879 mAttachInfo.mContentInsets.set(mPendingContentInsets);
880 host.fitSystemWindows(mAttachInfo.mContentInsets);
881 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
882 + mAttachInfo.mContentInsets);
883 }
884 if (visibleInsetsChanged) {
885 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
886 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
887 + mAttachInfo.mVisibleInsets);
888 }
889
890 if (!hadSurface) {
891 if (mSurface.isValid()) {
892 // If we are creating a new surface, then we need to
893 // completely redraw it. Also, when we get to the
894 // point of drawing it we will hold off and schedule
895 // a new traversal instead. This is so we can tell the
896 // window manager about all of the windows being displayed
897 // before actually drawing them, so it can display then
898 // all at once.
899 newSurface = true;
900 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 if (mGlWanted && !mUseGL) {
903 initializeGL();
904 initialized = mGlCanvas != null;
905 }
906 }
907 } else if (!mSurface.isValid()) {
908 // If the surface has been removed, then reset the scroll
909 // positions.
910 mLastScrolledFocus = null;
911 mScrollY = mCurScrollY = 0;
912 if (mScroller != null) {
913 mScroller.abortAnimation();
914 }
915 }
916 } catch (RemoteException e) {
917 }
918 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700919 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920
921 attachInfo.mWindowLeft = frame.left;
922 attachInfo.mWindowTop = frame.top;
923
924 // !!FIXME!! This next section handles the case where we did not get the
925 // window size we asked for. We should avoid this by getting a maximum size from
926 // the window session beforehand.
927 mWidth = frame.width();
928 mHeight = frame.height();
929
930 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -0700931 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
932 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
934
935 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
936 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
937 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
938 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
939 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
940 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
941
942 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
943 + mWidth + " measuredWidth=" + host.mMeasuredWidth
944 + " mHeight=" + mHeight
945 + " measuredHeight" + host.mMeasuredHeight
946 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 // Ask host how big it wants to be
949 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
950
951 // Implementation of weights from WindowManager.LayoutParams
952 // We just grow the dimensions as needed and re-measure if
953 // needs be
954 int width = host.mMeasuredWidth;
955 int height = host.mMeasuredHeight;
956 boolean measureAgain = false;
957
958 if (lp.horizontalWeight > 0.0f) {
959 width += (int) ((mWidth - width) * lp.horizontalWeight);
960 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
961 MeasureSpec.EXACTLY);
962 measureAgain = true;
963 }
964 if (lp.verticalWeight > 0.0f) {
965 height += (int) ((mHeight - height) * lp.verticalWeight);
966 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
967 MeasureSpec.EXACTLY);
968 measureAgain = true;
969 }
970
971 if (measureAgain) {
972 if (DEBUG_LAYOUT) Log.v(TAG,
973 "And hey let's measure once more: width=" + width
974 + " height=" + height);
975 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
976 }
977
978 mLayoutRequested = true;
979 }
980 }
981
982 final boolean didLayout = mLayoutRequested;
983 boolean triggerGlobalLayoutListener = didLayout
984 || attachInfo.mRecomputeGlobalAttributes;
985 if (didLayout) {
986 mLayoutRequested = false;
987 mScrollMayChange = true;
988 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
989 "ViewRoot", "Laying out " + host + " to (" +
990 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700991 long startTime = 0L;
992 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 startTime = SystemClock.elapsedRealtime();
994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
996
Romain Guy13922e02009-05-12 17:56:14 -0700997 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
998 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
999 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1000 + "please refer to the logs with the tag "
1001 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1002 }
1003 }
1004
1005 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1007 }
1008
1009 // By this point all views have been sized and positionned
1010 // We can compute the transparent area
1011
1012 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1013 // start out transparent
1014 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1015 host.getLocationInWindow(mTmpLocation);
1016 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1017 mTmpLocation[0] + host.mRight - host.mLeft,
1018 mTmpLocation[1] + host.mBottom - host.mTop);
1019
1020 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001021 if (mTranslator != null) {
1022 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1023 }
1024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1026 mPreviousTransparentRegion.set(mTransparentRegion);
1027 // reconfigure window manager
1028 try {
1029 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1030 } catch (RemoteException e) {
1031 }
1032 }
1033 }
1034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 if (DBG) {
1036 System.out.println("======================================");
1037 System.out.println("performTraversals -- after setFrame");
1038 host.debug();
1039 }
1040 }
1041
1042 if (triggerGlobalLayoutListener) {
1043 attachInfo.mRecomputeGlobalAttributes = false;
1044 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1045 }
1046
1047 if (computesInternalInsets) {
1048 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1049 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1050 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1051 givenContent.left = givenContent.top = givenContent.right
1052 = givenContent.bottom = givenVisible.left = givenVisible.top
1053 = givenVisible.right = givenVisible.bottom = 0;
1054 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001055 Rect contentInsets = insets.contentInsets;
1056 Rect visibleInsets = insets.visibleInsets;
1057 if (mTranslator != null) {
1058 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1059 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1062 mLastGivenInsets.set(insets);
1063 try {
1064 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001065 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 } catch (RemoteException e) {
1067 }
1068 }
1069 }
Romain Guy8506ab42009-06-11 17:35:47 -07001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (mFirst) {
1072 // handle first focus request
1073 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1074 + mView.hasFocus());
1075 if (mView != null) {
1076 if (!mView.hasFocus()) {
1077 mView.requestFocus(View.FOCUS_FORWARD);
1078 mFocusedView = mRealFocusedView = mView.findFocus();
1079 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1080 + mFocusedView);
1081 } else {
1082 mRealFocusedView = mView.findFocus();
1083 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1084 + mRealFocusedView);
1085 }
1086 }
1087 }
1088
1089 mFirst = false;
1090 mWillDrawSoon = false;
1091 mNewSurfaceNeeded = false;
1092 mViewVisibility = viewVisibility;
1093
1094 if (mAttachInfo.mHasWindowFocus) {
1095 final boolean imTarget = WindowManager.LayoutParams
1096 .mayUseInputMethod(mWindowAttributes.flags);
1097 if (imTarget != mLastWasImTarget) {
1098 mLastWasImTarget = imTarget;
1099 InputMethodManager imm = InputMethodManager.peekInstance();
1100 if (imm != null && imTarget) {
1101 imm.startGettingWindowFocus(mView);
1102 imm.onWindowFocus(mView, mView.findFocus(),
1103 mWindowAttributes.softInputMode,
1104 !mHasHadWindowFocus, mWindowAttributes.flags);
1105 }
1106 }
1107 }
Romain Guy8506ab42009-06-11 17:35:47 -07001108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1110
1111 if (!cancelDraw && !newSurface) {
1112 mFullRedrawNeeded = false;
1113 draw(fullRedrawNeeded);
1114
1115 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1116 || mReportNextDraw) {
1117 if (LOCAL_LOGV) {
1118 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1119 }
1120 mReportNextDraw = false;
1121 try {
1122 sWindowSession.finishDrawing(mWindow);
1123 } catch (RemoteException e) {
1124 }
1125 }
1126 } else {
1127 // We were supposed to report when we are done drawing. Since we canceled the
1128 // draw, remember it here.
1129 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1130 mReportNextDraw = true;
1131 }
1132 if (fullRedrawNeeded) {
1133 mFullRedrawNeeded = true;
1134 }
1135 // Try again
1136 scheduleTraversals();
1137 }
1138 }
1139
1140 public void requestTransparentRegion(View child) {
1141 // the test below should not fail unless someone is messing with us
1142 checkThread();
1143 if (mView == child) {
1144 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1145 // Need to make sure we re-evaluate the window attributes next
1146 // time around, to ensure the window has the correct format.
1147 mWindowAttributesChanged = true;
1148 }
1149 }
1150
1151 /**
1152 * Figures out the measure spec for the root view in a window based on it's
1153 * layout params.
1154 *
1155 * @param windowSize
1156 * The available width or height of the window
1157 *
1158 * @param rootDimension
1159 * The layout params for one dimension (width or height) of the
1160 * window.
1161 *
1162 * @return The measure spec to use to measure the root view.
1163 */
1164 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1165 int measureSpec;
1166 switch (rootDimension) {
1167
1168 case ViewGroup.LayoutParams.FILL_PARENT:
1169 // Window can't resize. Force root view to be windowSize.
1170 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1171 break;
1172 case ViewGroup.LayoutParams.WRAP_CONTENT:
1173 // Window can resize. Set max size for root view.
1174 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1175 break;
1176 default:
1177 // Window wants to be an exact size. Force root view to be that size.
1178 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1179 break;
1180 }
1181 return measureSpec;
1182 }
1183
1184 private void draw(boolean fullRedrawNeeded) {
1185 Surface surface = mSurface;
1186 if (surface == null || !surface.isValid()) {
1187 return;
1188 }
1189
1190 scrollToRectOrFocus(null, false);
1191
1192 if (mAttachInfo.mViewScrollChanged) {
1193 mAttachInfo.mViewScrollChanged = false;
1194 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1195 }
Romain Guy8506ab42009-06-11 17:35:47 -07001196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001198 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 if (scrolling) {
1200 yoff = mScroller.getCurrY();
1201 } else {
1202 yoff = mScrollY;
1203 }
1204 if (mCurScrollY != yoff) {
1205 mCurScrollY = yoff;
1206 fullRedrawNeeded = true;
1207 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001208 float appScale = mAttachInfo.mApplicationScale;
1209 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210
1211 Rect dirty = mDirty;
1212 if (mUseGL) {
1213 if (!dirty.isEmpty()) {
1214 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001215 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 mGL.glDisable(GL_SCISSOR_TEST);
1217 mGL.glClearColor(0, 0, 0, 0);
1218 mGL.glClear(GL_COLOR_BUFFER_BIT);
1219 mGL.glEnable(GL_SCISSOR_TEST);
1220
1221 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001222 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001224
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001225 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1226 try {
1227 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001228 if (mTranslator != null) {
1229 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001230 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001231 canvas.setScreenDensity(scalingRequired
1232 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001233 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001234 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1235 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1236 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001237 } finally {
1238 canvas.restoreToCount(saveCount);
1239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240
Romain Guy5bcdff42009-05-14 21:27:18 -07001241 mAttachInfo.mIgnoreDirtyState = false;
1242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1244 checkEglErrors();
1245
Romain Guy13922e02009-05-12 17:56:14 -07001246 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 int now = (int)SystemClock.elapsedRealtime();
1248 if (sDrawTime != 0) {
1249 nativeShowFPS(canvas, now - sDrawTime);
1250 }
1251 sDrawTime = now;
1252 }
1253 }
1254 }
1255 if (scrolling) {
1256 mFullRedrawNeeded = true;
1257 scheduleTraversals();
1258 }
1259 return;
1260 }
1261
Romain Guy5bcdff42009-05-14 21:27:18 -07001262 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001263 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001264 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266
1267 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1268 Log.v("ViewRoot", "Draw " + mView + "/"
1269 + mWindowAttributes.getTitle()
1270 + ": dirty={" + dirty.left + "," + dirty.top
1271 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001272 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1273 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
1275
1276 Canvas canvas;
1277 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001278 int left = dirty.left;
1279 int top = dirty.top;
1280 int right = dirty.right;
1281 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001283
1284 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1285 bottom != dirty.bottom) {
1286 mAttachInfo.mIgnoreDirtyState = true;
1287 }
1288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 // TODO: Do this in native
Dianne Hackborn11ea3342009-07-22 21:48:55 -07001290 canvas.setDensity(mDensity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 } catch (Surface.OutOfResourcesException e) {
1292 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1293 // TODO: we should ask the window manager to do something!
1294 // for now we just do nothing
1295 return;
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001296 } catch (IllegalArgumentException e) {
1297 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1298 // TODO: we should ask the window manager to do something!
1299 // for now we just do nothing
1300 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302
1303 try {
Romain Guybb93d552009-03-24 21:04:15 -07001304 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001305 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306
1307 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1308 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1309 + canvas.getWidth() + ", h=" + canvas.getHeight());
1310 //canvas.drawARGB(255, 255, 0, 0);
1311 }
1312
Romain Guy13922e02009-05-12 17:56:14 -07001313 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 startTime = SystemClock.elapsedRealtime();
1315 }
1316
1317 // If this bitmap's format includes an alpha channel, we
1318 // need to clear it before drawing so that the child will
1319 // properly re-composite its drawing on a transparent
1320 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001321 // or
1322 // If we are applying an offset, we need to clear the area
1323 // where the offset doesn't appear to avoid having garbage
1324 // left in the blank areas.
1325 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1327 }
1328
1329 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001330 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001332 mView.mPrivateFlags |= View.DRAWN;
1333
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001334 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001335 Context cxt = mView.getContext();
1336 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -07001337 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1338 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001339 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001340 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001341 try {
1342 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001343 if (mTranslator != null) {
1344 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001345 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001346 canvas.setScreenDensity(scalingRequired
1347 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001348 mView.draw(canvas);
1349 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001350 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001351 canvas.restoreToCount(saveCount);
1352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353
Romain Guy5bcdff42009-05-14 21:27:18 -07001354 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1355 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1356 }
1357
Romain Guy13922e02009-05-12 17:56:14 -07001358 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 int now = (int)SystemClock.elapsedRealtime();
1360 if (sDrawTime != 0) {
1361 nativeShowFPS(canvas, now - sDrawTime);
1362 }
1363 sDrawTime = now;
1364 }
1365
Romain Guy13922e02009-05-12 17:56:14 -07001366 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1368 }
1369 }
Romain Guy8506ab42009-06-11 17:35:47 -07001370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 } finally {
1372 surface.unlockCanvasAndPost(canvas);
1373 }
1374
1375 if (LOCAL_LOGV) {
1376 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1377 }
Romain Guy8506ab42009-06-11 17:35:47 -07001378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 if (scrolling) {
1380 mFullRedrawNeeded = true;
1381 scheduleTraversals();
1382 }
1383 }
1384
1385 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1386 final View.AttachInfo attachInfo = mAttachInfo;
1387 final Rect ci = attachInfo.mContentInsets;
1388 final Rect vi = attachInfo.mVisibleInsets;
1389 int scrollY = 0;
1390 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 if (vi.left > ci.left || vi.top > ci.top
1393 || vi.right > ci.right || vi.bottom > ci.bottom) {
1394 // We'll assume that we aren't going to change the scroll
1395 // offset, since we want to avoid that unless it is actually
1396 // going to make the focus visible... otherwise we scroll
1397 // all over the place.
1398 scrollY = mScrollY;
1399 // We can be called for two different situations: during a draw,
1400 // to update the scroll position if the focus has changed (in which
1401 // case 'rectangle' is null), or in response to a
1402 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1403 // is non-null and we just want to scroll to whatever that
1404 // rectangle is).
1405 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001406
1407 // When in touch mode, focus points to the previously focused view,
1408 // which may have been removed from the view hierarchy. The following
1409 // line checks whether the view is still in the hierarchy
1410 if (focus == null || focus.getParent() == null) {
1411 mRealFocusedView = null;
1412 return false;
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 if (focus != mLastScrolledFocus) {
1416 // If the focus has changed, then ignore any requests to scroll
1417 // to a rectangle; first we want to make sure the entire focus
1418 // view is visible.
1419 rectangle = null;
1420 }
1421 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1422 + " rectangle=" + rectangle + " ci=" + ci
1423 + " vi=" + vi);
1424 if (focus == mLastScrolledFocus && !mScrollMayChange
1425 && rectangle == null) {
1426 // Optimization: if the focus hasn't changed since last
1427 // time, and no layout has happened, then just leave things
1428 // as they are.
1429 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1430 + mScrollY + " vi=" + vi.toShortString());
1431 } else if (focus != null) {
1432 // We need to determine if the currently focused view is
1433 // within the visible part of the window and, if not, apply
1434 // a pan so it can be seen.
1435 mLastScrolledFocus = focus;
1436 mScrollMayChange = false;
1437 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1438 // Try to find the rectangle from the focus view.
1439 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1440 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1441 + mView.getWidth() + " h=" + mView.getHeight()
1442 + " ci=" + ci.toShortString()
1443 + " vi=" + vi.toShortString());
1444 if (rectangle == null) {
1445 focus.getFocusedRect(mTempRect);
1446 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1447 + ": focusRect=" + mTempRect.toShortString());
1448 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1449 focus, mTempRect);
1450 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1451 "Focus in window: focusRect="
1452 + mTempRect.toShortString()
1453 + " visRect=" + mVisRect.toShortString());
1454 } else {
1455 mTempRect.set(rectangle);
1456 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1457 "Request scroll to rect: "
1458 + mTempRect.toShortString()
1459 + " visRect=" + mVisRect.toShortString());
1460 }
1461 if (mTempRect.intersect(mVisRect)) {
1462 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1463 "Focus window visible rect: "
1464 + mTempRect.toShortString());
1465 if (mTempRect.height() >
1466 (mView.getHeight()-vi.top-vi.bottom)) {
1467 // If the focus simply is not going to fit, then
1468 // best is probably just to leave things as-is.
1469 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1470 "Too tall; leaving scrollY=" + scrollY);
1471 } else if ((mTempRect.top-scrollY) < vi.top) {
1472 scrollY -= vi.top - (mTempRect.top-scrollY);
1473 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1474 "Top covered; scrollY=" + scrollY);
1475 } else if ((mTempRect.bottom-scrollY)
1476 > (mView.getHeight()-vi.bottom)) {
1477 scrollY += (mTempRect.bottom-scrollY)
1478 - (mView.getHeight()-vi.bottom);
1479 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1480 "Bottom covered; scrollY=" + scrollY);
1481 }
1482 handled = true;
1483 }
1484 }
1485 }
1486 }
Romain Guy8506ab42009-06-11 17:35:47 -07001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 if (scrollY != mScrollY) {
1489 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1490 + mScrollY + " , new=" + scrollY);
1491 if (!immediate) {
1492 if (mScroller == null) {
1493 mScroller = new Scroller(mView.getContext());
1494 }
1495 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1496 } else if (mScroller != null) {
1497 mScroller.abortAnimation();
1498 }
1499 mScrollY = scrollY;
1500 }
Romain Guy8506ab42009-06-11 17:35:47 -07001501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 return handled;
1503 }
Romain Guy8506ab42009-06-11 17:35:47 -07001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 public void requestChildFocus(View child, View focused) {
1506 checkThread();
1507 if (mFocusedView != focused) {
1508 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1509 scheduleTraversals();
1510 }
1511 mFocusedView = mRealFocusedView = focused;
1512 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1513 + mFocusedView);
1514 }
1515
1516 public void clearChildFocus(View child) {
1517 checkThread();
1518
1519 View oldFocus = mFocusedView;
1520
1521 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1522 mFocusedView = mRealFocusedView = null;
1523 if (mView != null && !mView.hasFocus()) {
1524 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1525 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1526 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1527 }
1528 } else if (oldFocus != null) {
1529 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1530 }
1531 }
1532
1533
1534 public void focusableViewAvailable(View v) {
1535 checkThread();
1536
1537 if (mView != null && !mView.hasFocus()) {
1538 v.requestFocus();
1539 } else {
1540 // the one case where will transfer focus away from the current one
1541 // is if the current view is a view group that prefers to give focus
1542 // to its children first AND the view is a descendant of it.
1543 mFocusedView = mView.findFocus();
1544 boolean descendantsHaveDibsOnFocus =
1545 (mFocusedView instanceof ViewGroup) &&
1546 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1547 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1548 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1549 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1550 v.requestFocus();
1551 }
1552 }
1553 }
1554
1555 public void recomputeViewAttributes(View child) {
1556 checkThread();
1557 if (mView == child) {
1558 mAttachInfo.mRecomputeGlobalAttributes = true;
1559 if (!mWillDrawSoon) {
1560 scheduleTraversals();
1561 }
1562 }
1563 }
1564
1565 void dispatchDetachedFromWindow() {
1566 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1567
1568 if (mView != null) {
1569 mView.dispatchDetachedFromWindow();
1570 }
1571
1572 mView = null;
1573 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001574 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575
1576 if (mUseGL) {
1577 destroyGL();
1578 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001579 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580
1581 try {
1582 sWindowSession.remove(mWindow);
1583 } catch (RemoteException e) {
1584 }
1585 }
Romain Guy8506ab42009-06-11 17:35:47 -07001586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 /**
1588 * Return true if child is an ancestor of parent, (or equal to the parent).
1589 */
1590 private static boolean isViewDescendantOf(View child, View parent) {
1591 if (child == parent) {
1592 return true;
1593 }
1594
1595 final ViewParent theParent = child.getParent();
1596 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1597 }
1598
1599
1600 public final static int DO_TRAVERSAL = 1000;
1601 public final static int DIE = 1001;
1602 public final static int RESIZED = 1002;
1603 public final static int RESIZED_REPORT = 1003;
1604 public final static int WINDOW_FOCUS_CHANGED = 1004;
1605 public final static int DISPATCH_KEY = 1005;
1606 public final static int DISPATCH_POINTER = 1006;
1607 public final static int DISPATCH_TRACKBALL = 1007;
1608 public final static int DISPATCH_APP_VISIBILITY = 1008;
1609 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1610 public final static int FINISHED_EVENT = 1010;
1611 public final static int DISPATCH_KEY_FROM_IME = 1011;
1612 public final static int FINISH_INPUT_CONNECTION = 1012;
1613 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001614 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615
1616 @Override
1617 public void handleMessage(Message msg) {
1618 switch (msg.what) {
1619 case View.AttachInfo.INVALIDATE_MSG:
1620 ((View) msg.obj).invalidate();
1621 break;
1622 case View.AttachInfo.INVALIDATE_RECT_MSG:
1623 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1624 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1625 info.release();
1626 break;
1627 case DO_TRAVERSAL:
1628 if (mProfile) {
1629 Debug.startMethodTracing("ViewRoot");
1630 }
1631
1632 performTraversals();
1633
1634 if (mProfile) {
1635 Debug.stopMethodTracing();
1636 mProfile = false;
1637 }
1638 break;
1639 case FINISHED_EVENT:
1640 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1641 break;
1642 case DISPATCH_KEY:
1643 if (LOCAL_LOGV) Log.v(
1644 "ViewRoot", "Dispatching key "
1645 + msg.obj + " to " + mView);
1646 deliverKeyEvent((KeyEvent)msg.obj, true);
1647 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001648 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001650 boolean callWhenDone = msg.arg1 != 0;
1651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if (event == null) {
1653 try {
Michael Chan53071d62009-05-13 17:29:48 -07001654 long timeBeforeGettingEvents;
1655 if (MEASURE_LATENCY) {
1656 timeBeforeGettingEvents = System.nanoTime();
1657 }
1658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001660
1661 if (MEASURE_LATENCY && event != null) {
1662 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1663 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 } catch (RemoteException e) {
1666 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001667 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001669 if (event != null && mTranslator != null) {
1670 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 try {
1673 boolean handled;
1674 if (mView != null && mAdded && event != null) {
1675
1676 // enter touch mode on the down
1677 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1678 if (isDown) {
1679 ensureTouchMode(true);
1680 }
1681 if(Config.LOGV) {
1682 captureMotionLog("captureDispatchPointer", event);
1683 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001684 if (mCurScrollY != 0) {
1685 event.offsetLocation(0, mCurScrollY);
1686 }
Michael Chan53071d62009-05-13 17:29:48 -07001687 if (MEASURE_LATENCY) {
1688 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001691 if (MEASURE_LATENCY) {
1692 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (!handled && isDown) {
1695 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1696
1697 final int edgeFlags = event.getEdgeFlags();
1698 int direction = View.FOCUS_UP;
1699 int x = (int)event.getX();
1700 int y = (int)event.getY();
1701 final int[] deltas = new int[2];
1702
1703 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1704 direction = View.FOCUS_DOWN;
1705 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1706 deltas[0] = edgeSlop;
1707 x += edgeSlop;
1708 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1709 deltas[0] = -edgeSlop;
1710 x -= edgeSlop;
1711 }
1712 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1713 direction = View.FOCUS_UP;
1714 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1715 deltas[0] = edgeSlop;
1716 x += edgeSlop;
1717 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1718 deltas[0] = -edgeSlop;
1719 x -= edgeSlop;
1720 }
1721 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1722 direction = View.FOCUS_RIGHT;
1723 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1724 direction = View.FOCUS_LEFT;
1725 }
1726
1727 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1728 View nearest = FocusFinder.getInstance().findNearestTouchable(
1729 ((ViewGroup) mView), x, y, direction, deltas);
1730 if (nearest != null) {
1731 event.offsetLocation(deltas[0], deltas[1]);
1732 event.setEdgeFlags(0);
1733 mView.dispatchTouchEvent(event);
1734 }
1735 }
1736 }
1737 }
1738 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001739 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 try {
1741 sWindowSession.finishKey(mWindow);
1742 } catch (RemoteException e) {
1743 }
1744 }
1745 if (event != null) {
1746 event.recycle();
1747 }
1748 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1749 // Let the exception fall through -- the looper will catch
1750 // it and take care of the bad app for us.
1751 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001752 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001754 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 break;
1756 case DISPATCH_APP_VISIBILITY:
1757 handleAppVisibility(msg.arg1 != 0);
1758 break;
1759 case DISPATCH_GET_NEW_SURFACE:
1760 handleGetNewSurface();
1761 break;
1762 case RESIZED:
1763 Rect coveredInsets = ((Rect[])msg.obj)[0];
1764 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1767 && mPendingContentInsets.equals(coveredInsets)
1768 && mPendingVisibleInsets.equals(visibleInsets)) {
1769 break;
1770 }
1771 // fall through...
1772 case RESIZED_REPORT:
1773 if (mAdded) {
1774 mWinFrame.left = 0;
1775 mWinFrame.right = msg.arg1;
1776 mWinFrame.top = 0;
1777 mWinFrame.bottom = msg.arg2;
1778 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1779 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1780 if (msg.what == RESIZED_REPORT) {
1781 mReportNextDraw = true;
1782 }
1783 requestLayout();
1784 }
1785 break;
1786 case WINDOW_FOCUS_CHANGED: {
1787 if (mAdded) {
1788 boolean hasWindowFocus = msg.arg1 != 0;
1789 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1790 if (hasWindowFocus) {
1791 boolean inTouchMode = msg.arg2 != 0;
1792 ensureTouchModeLocally(inTouchMode);
1793
1794 if (mGlWanted) {
1795 checkEglErrors();
1796 // we lost the gl context, so recreate it.
1797 if (mGlWanted && !mUseGL) {
1798 initializeGL();
1799 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001800 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001801 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001802 (int) (mWidth * appScale + 0.5f),
1803 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805 }
1806 }
1807 }
Romain Guy8506ab42009-06-11 17:35:47 -07001808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 mLastWasImTarget = WindowManager.LayoutParams
1810 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 InputMethodManager imm = InputMethodManager.peekInstance();
1813 if (mView != null) {
1814 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1815 imm.startGettingWindowFocus(mView);
1816 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001817 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 mView.dispatchWindowFocusChanged(hasWindowFocus);
1819 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 // Note: must be done after the focus change callbacks,
1822 // so all of the view state is set up correctly.
1823 if (hasWindowFocus) {
1824 if (imm != null && mLastWasImTarget) {
1825 imm.onWindowFocus(mView, mView.findFocus(),
1826 mWindowAttributes.softInputMode,
1827 !mHasHadWindowFocus, mWindowAttributes.flags);
1828 }
1829 // Clear the forward bit. We can just do this directly, since
1830 // the window manager doesn't care about it.
1831 mWindowAttributes.softInputMode &=
1832 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1833 ((WindowManager.LayoutParams)mView.getLayoutParams())
1834 .softInputMode &=
1835 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1836 mHasHadWindowFocus = true;
1837 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001838
1839 if (hasWindowFocus && mView != null) {
1840 sendAccessibilityEvents();
1841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843 } break;
1844 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001845 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001847 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 if (LOCAL_LOGV) Log.v(
1849 "ViewRoot", "Dispatching key "
1850 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001851 KeyEvent event = (KeyEvent)msg.obj;
1852 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1853 // The IME is trying to say this event is from the
1854 // system! Bad bad bad!
1855 event = KeyEvent.changeFlags(event,
1856 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001859 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 case FINISH_INPUT_CONNECTION: {
1861 InputMethodManager imm = InputMethodManager.peekInstance();
1862 if (imm != null) {
1863 imm.reportFinishInputConnection((InputConnection)msg.obj);
1864 }
1865 } break;
1866 case CHECK_FOCUS: {
1867 InputMethodManager imm = InputMethodManager.peekInstance();
1868 if (imm != null) {
1869 imm.checkFocus();
1870 }
1871 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001872 case CLOSE_SYSTEM_DIALOGS: {
1873 if (mView != null) {
1874 mView.onCloseSystemDialogs((String)msg.obj);
1875 }
1876 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 }
1878 }
1879
1880 /**
1881 * Something in the current window tells us we need to change the touch mode. For
1882 * example, we are not in touch mode, and the user touches the screen.
1883 *
1884 * If the touch mode has changed, tell the window manager, and handle it locally.
1885 *
1886 * @param inTouchMode Whether we want to be in touch mode.
1887 * @return True if the touch mode changed and focus changed was changed as a result
1888 */
1889 boolean ensureTouchMode(boolean inTouchMode) {
1890 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1891 + "touch mode is " + mAttachInfo.mInTouchMode);
1892 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1893
1894 // tell the window manager
1895 try {
1896 sWindowSession.setInTouchMode(inTouchMode);
1897 } catch (RemoteException e) {
1898 throw new RuntimeException(e);
1899 }
1900
1901 // handle the change
1902 return ensureTouchModeLocally(inTouchMode);
1903 }
1904
1905 /**
1906 * Ensure that the touch mode for this window is set, and if it is changing,
1907 * take the appropriate action.
1908 * @param inTouchMode Whether we want to be in touch mode.
1909 * @return True if the touch mode changed and focus changed was changed as a result
1910 */
1911 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1912 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1913 + "touch mode is " + mAttachInfo.mInTouchMode);
1914
1915 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1916
1917 mAttachInfo.mInTouchMode = inTouchMode;
1918 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1919
1920 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1921 }
1922
1923 private boolean enterTouchMode() {
1924 if (mView != null) {
1925 if (mView.hasFocus()) {
1926 // note: not relying on mFocusedView here because this could
1927 // be when the window is first being added, and mFocused isn't
1928 // set yet.
1929 final View focused = mView.findFocus();
1930 if (focused != null && !focused.isFocusableInTouchMode()) {
1931
1932 final ViewGroup ancestorToTakeFocus =
1933 findAncestorToTakeFocusInTouchMode(focused);
1934 if (ancestorToTakeFocus != null) {
1935 // there is an ancestor that wants focus after its descendants that
1936 // is focusable in touch mode.. give it focus
1937 return ancestorToTakeFocus.requestFocus();
1938 } else {
1939 // nothing appropriate to have focus in touch mode, clear it out
1940 mView.unFocus();
1941 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1942 mFocusedView = null;
1943 return true;
1944 }
1945 }
1946 }
1947 }
1948 return false;
1949 }
1950
1951
1952 /**
1953 * Find an ancestor of focused that wants focus after its descendants and is
1954 * focusable in touch mode.
1955 * @param focused The currently focused view.
1956 * @return An appropriate view, or null if no such view exists.
1957 */
1958 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1959 ViewParent parent = focused.getParent();
1960 while (parent instanceof ViewGroup) {
1961 final ViewGroup vgParent = (ViewGroup) parent;
1962 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1963 && vgParent.isFocusableInTouchMode()) {
1964 return vgParent;
1965 }
1966 if (vgParent.isRootNamespace()) {
1967 return null;
1968 } else {
1969 parent = vgParent.getParent();
1970 }
1971 }
1972 return null;
1973 }
1974
1975 private boolean leaveTouchMode() {
1976 if (mView != null) {
1977 if (mView.hasFocus()) {
1978 // i learned the hard way to not trust mFocusedView :)
1979 mFocusedView = mView.findFocus();
1980 if (!(mFocusedView instanceof ViewGroup)) {
1981 // some view has focus, let it keep it
1982 return false;
1983 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1984 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1985 // some view group has focus, and doesn't prefer its children
1986 // over itself for focus, so let them keep it.
1987 return false;
1988 }
1989 }
1990
1991 // find the best view to give focus to in this brave new non-touch-mode
1992 // world
1993 final View focused = focusSearch(null, View.FOCUS_DOWN);
1994 if (focused != null) {
1995 return focused.requestFocus(View.FOCUS_DOWN);
1996 }
1997 }
1998 return false;
1999 }
2000
2001
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002002 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if (event == null) {
2004 try {
2005 event = sWindowSession.getPendingTrackballMove(mWindow);
2006 } catch (RemoteException e) {
2007 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002008 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010
2011 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2012
2013 boolean handled = false;
2014 try {
2015 if (event == null) {
2016 handled = true;
2017 } else if (mView != null && mAdded) {
2018 handled = mView.dispatchTrackballEvent(event);
2019 if (!handled) {
2020 // we could do something here, like changing the focus
2021 // or something?
2022 }
2023 }
2024 } finally {
2025 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002026 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 try {
2028 sWindowSession.finishKey(mWindow);
2029 } catch (RemoteException e) {
2030 }
2031 }
2032 if (event != null) {
2033 event.recycle();
2034 }
2035 // If we reach this, we delivered a trackball event to mView and
2036 // mView consumed it. Because we will not translate the trackball
2037 // event into a key event, touch mode will not exit, so we exit
2038 // touch mode here.
2039 ensureTouchMode(false);
2040 //noinspection ReturnInsideFinallyBlock
2041 return;
2042 }
2043 // Let the exception fall through -- the looper will catch
2044 // it and take care of the bad app for us.
2045 }
2046
2047 final TrackballAxis x = mTrackballAxisX;
2048 final TrackballAxis y = mTrackballAxisY;
2049
2050 long curTime = SystemClock.uptimeMillis();
2051 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2052 // It has been too long since the last movement,
2053 // so restart at the beginning.
2054 x.reset(0);
2055 y.reset(0);
2056 mLastTrackballTime = curTime;
2057 }
2058
2059 try {
2060 final int action = event.getAction();
2061 final int metastate = event.getMetaState();
2062 switch (action) {
2063 case MotionEvent.ACTION_DOWN:
2064 x.reset(2);
2065 y.reset(2);
2066 deliverKeyEvent(new KeyEvent(curTime, curTime,
2067 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2068 0, metastate), false);
2069 break;
2070 case MotionEvent.ACTION_UP:
2071 x.reset(2);
2072 y.reset(2);
2073 deliverKeyEvent(new KeyEvent(curTime, curTime,
2074 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2075 0, metastate), false);
2076 break;
2077 }
2078
2079 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2080 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2081 + " move=" + event.getX()
2082 + " / Y=" + y.position + " step="
2083 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2084 + " move=" + event.getY());
2085 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2086 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2087
2088 // Generate DPAD events based on the trackball movement.
2089 // We pick the axis that has moved the most as the direction of
2090 // the DPAD. When we generate DPAD events for one axis, then the
2091 // other axis is reset -- we don't want to perform DPAD jumps due
2092 // to slight movements in the trackball when making major movements
2093 // along the other axis.
2094 int keycode = 0;
2095 int movement = 0;
2096 float accel = 1;
2097 if (xOff > yOff) {
2098 movement = x.generate((2/event.getXPrecision()));
2099 if (movement != 0) {
2100 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2101 : KeyEvent.KEYCODE_DPAD_LEFT;
2102 accel = x.acceleration;
2103 y.reset(2);
2104 }
2105 } else if (yOff > 0) {
2106 movement = y.generate((2/event.getYPrecision()));
2107 if (movement != 0) {
2108 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2109 : KeyEvent.KEYCODE_DPAD_UP;
2110 accel = y.acceleration;
2111 x.reset(2);
2112 }
2113 }
2114
2115 if (keycode != 0) {
2116 if (movement < 0) movement = -movement;
2117 int accelMovement = (int)(movement * accel);
2118 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2119 + " accelMovement=" + accelMovement
2120 + " accel=" + accel);
2121 if (accelMovement > movement) {
2122 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2123 + keycode);
2124 movement--;
2125 deliverKeyEvent(new KeyEvent(curTime, curTime,
2126 KeyEvent.ACTION_MULTIPLE, keycode,
2127 accelMovement-movement, metastate), false);
2128 }
2129 while (movement > 0) {
2130 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2131 + keycode);
2132 movement--;
2133 curTime = SystemClock.uptimeMillis();
2134 deliverKeyEvent(new KeyEvent(curTime, curTime,
2135 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2136 deliverKeyEvent(new KeyEvent(curTime, curTime,
2137 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2138 }
2139 mLastTrackballTime = curTime;
2140 }
2141 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002142 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 try {
2144 sWindowSession.finishKey(mWindow);
2145 } catch (RemoteException e) {
2146 }
2147 if (event != null) {
2148 event.recycle();
2149 }
2150 }
2151 // Let the exception fall through -- the looper will catch
2152 // it and take care of the bad app for us.
2153 }
2154 }
2155
2156 /**
2157 * @param keyCode The key code
2158 * @return True if the key is directional.
2159 */
2160 static boolean isDirectional(int keyCode) {
2161 switch (keyCode) {
2162 case KeyEvent.KEYCODE_DPAD_LEFT:
2163 case KeyEvent.KEYCODE_DPAD_RIGHT:
2164 case KeyEvent.KEYCODE_DPAD_UP:
2165 case KeyEvent.KEYCODE_DPAD_DOWN:
2166 return true;
2167 }
2168 return false;
2169 }
2170
2171 /**
2172 * Returns true if this key is a keyboard key.
2173 * @param keyEvent The key event.
2174 * @return whether this key is a keyboard key.
2175 */
2176 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2177 final int convertedKey = keyEvent.getUnicodeChar();
2178 return convertedKey > 0;
2179 }
2180
2181
2182
2183 /**
2184 * See if the key event means we should leave touch mode (and leave touch
2185 * mode if so).
2186 * @param event The key event.
2187 * @return Whether this key event should be consumed (meaning the act of
2188 * leaving touch mode alone is considered the event).
2189 */
2190 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2191 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2192 return false;
2193 }
2194 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2195 return false;
2196 }
2197
2198 // only relevant if we are in touch mode
2199 if (!mAttachInfo.mInTouchMode) {
2200 return false;
2201 }
2202
2203 // if something like an edit text has focus and the user is typing,
2204 // leave touch mode
2205 //
2206 // note: the condition of not being a keyboard key is kind of a hacky
2207 // approximation of whether we think the focused view will want the
2208 // key; if we knew for sure whether the focused view would consume
2209 // the event, that would be better.
2210 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2211 mFocusedView = mView.findFocus();
2212 if ((mFocusedView instanceof ViewGroup)
2213 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2214 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2215 // something has focus, but is holding it weakly as a container
2216 return false;
2217 }
2218 if (ensureTouchMode(false)) {
2219 throw new IllegalStateException("should not have changed focus "
2220 + "when leaving touch mode while a view has focus.");
2221 }
2222 return false;
2223 }
2224
2225 if (isDirectional(event.getKeyCode())) {
2226 // no view has focus, so we leave touch mode (and find something
2227 // to give focus to). the event is consumed if we were able to
2228 // find something to give focus to.
2229 return ensureTouchMode(false);
2230 }
2231 return false;
2232 }
2233
2234 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002235 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 */
2237 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002238 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 if (ev == null ||
2240 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2241 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
Romain Guy8506ab42009-06-11 17:35:47 -07002243
2244 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 sb.append(ev.getDownTime()).append(',');
2246 sb.append(ev.getEventTime()).append(',');
2247 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002248 sb.append(ev.getX()).append(',');
2249 sb.append(ev.getY()).append(',');
2250 sb.append(ev.getPressure()).append(',');
2251 sb.append(ev.getSize()).append(',');
2252 sb.append(ev.getMetaState()).append(',');
2253 sb.append(ev.getXPrecision()).append(',');
2254 sb.append(ev.getYPrecision()).append(',');
2255 sb.append(ev.getDeviceId()).append(',');
2256 sb.append(ev.getEdgeFlags());
2257 Log.d(TAG, sb.toString());
2258 }
2259 /**
2260 * log motion events
2261 */
2262 private static void captureKeyLog(String subTag, KeyEvent ev) {
2263 //check dynamic switch
2264 if (ev == null ||
2265 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2266 return;
2267 }
2268 StringBuilder sb = new StringBuilder(subTag + ": ");
2269 sb.append(ev.getDownTime()).append(',');
2270 sb.append(ev.getEventTime()).append(',');
2271 sb.append(ev.getAction()).append(',');
2272 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 sb.append(ev.getRepeatCount()).append(',');
2274 sb.append(ev.getMetaState()).append(',');
2275 sb.append(ev.getDeviceId()).append(',');
2276 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002277 Log.d(TAG, sb.toString());
2278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279
2280 int enqueuePendingEvent(Object event, boolean sendDone) {
2281 int seq = mPendingEventSeq+1;
2282 if (seq < 0) seq = 0;
2283 mPendingEventSeq = seq;
2284 mPendingEvents.put(seq, event);
2285 return sendDone ? seq : -seq;
2286 }
2287
2288 Object retrievePendingEvent(int seq) {
2289 if (seq < 0) seq = -seq;
2290 Object event = mPendingEvents.get(seq);
2291 if (event != null) {
2292 mPendingEvents.remove(seq);
2293 }
2294 return event;
2295 }
Romain Guy8506ab42009-06-11 17:35:47 -07002296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2298 // If mView is null, we just consume the key event because it doesn't
2299 // make sense to do anything else with it.
2300 boolean handled = mView != null
2301 ? mView.dispatchKeyEventPreIme(event) : true;
2302 if (handled) {
2303 if (sendDone) {
2304 if (LOCAL_LOGV) Log.v(
2305 "ViewRoot", "Telling window manager key is finished");
2306 try {
2307 sWindowSession.finishKey(mWindow);
2308 } catch (RemoteException e) {
2309 }
2310 }
2311 return;
2312 }
2313 // If it is possible for this window to interact with the input
2314 // method window, then we want to first dispatch our key events
2315 // to the input method.
2316 if (mLastWasImTarget) {
2317 InputMethodManager imm = InputMethodManager.peekInstance();
2318 if (imm != null && mView != null) {
2319 int seq = enqueuePendingEvent(event, sendDone);
2320 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2321 + seq + " event=" + event);
2322 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2323 mInputMethodCallback);
2324 return;
2325 }
2326 }
2327 deliverKeyEventToViewHierarchy(event, sendDone);
2328 }
2329
2330 void handleFinishedEvent(int seq, boolean handled) {
2331 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2332 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2333 + " handled=" + handled + " event=" + event);
2334 if (event != null) {
2335 final boolean sendDone = seq >= 0;
2336 if (!handled) {
2337 deliverKeyEventToViewHierarchy(event, sendDone);
2338 return;
2339 } else if (sendDone) {
2340 if (LOCAL_LOGV) Log.v(
2341 "ViewRoot", "Telling window manager key is finished");
2342 try {
2343 sWindowSession.finishKey(mWindow);
2344 } catch (RemoteException e) {
2345 }
2346 } else {
2347 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2348 + " handled=" + handled + " ev=" + event
2349 + ") neither delivering nor finishing key");
2350 }
2351 }
2352 }
Romain Guy8506ab42009-06-11 17:35:47 -07002353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2355 try {
2356 if (mView != null && mAdded) {
2357 final int action = event.getAction();
2358 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2359
2360 if (checkForLeavingTouchModeAndConsume(event)) {
2361 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002362 }
2363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 if (Config.LOGV) {
2365 captureKeyLog("captureDispatchKeyEvent", event);
2366 }
2367 boolean keyHandled = mView.dispatchKeyEvent(event);
2368
2369 if (!keyHandled && isDown) {
2370 int direction = 0;
2371 switch (event.getKeyCode()) {
2372 case KeyEvent.KEYCODE_DPAD_LEFT:
2373 direction = View.FOCUS_LEFT;
2374 break;
2375 case KeyEvent.KEYCODE_DPAD_RIGHT:
2376 direction = View.FOCUS_RIGHT;
2377 break;
2378 case KeyEvent.KEYCODE_DPAD_UP:
2379 direction = View.FOCUS_UP;
2380 break;
2381 case KeyEvent.KEYCODE_DPAD_DOWN:
2382 direction = View.FOCUS_DOWN;
2383 break;
2384 }
2385
2386 if (direction != 0) {
2387
2388 View focused = mView != null ? mView.findFocus() : null;
2389 if (focused != null) {
2390 View v = focused.focusSearch(direction);
2391 boolean focusPassed = false;
2392 if (v != null && v != focused) {
2393 // do the math the get the interesting rect
2394 // of previous focused into the coord system of
2395 // newly focused view
2396 focused.getFocusedRect(mTempRect);
2397 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2398 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2399 focusPassed = v.requestFocus(direction, mTempRect);
2400 }
2401
2402 if (!focusPassed) {
2403 mView.dispatchUnhandledMove(focused, direction);
2404 } else {
2405 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2406 }
2407 }
2408 }
2409 }
2410 }
2411
2412 } finally {
2413 if (sendDone) {
2414 if (LOCAL_LOGV) Log.v(
2415 "ViewRoot", "Telling window manager key is finished");
2416 try {
2417 sWindowSession.finishKey(mWindow);
2418 } catch (RemoteException e) {
2419 }
2420 }
2421 // Let the exception fall through -- the looper will catch
2422 // it and take care of the bad app for us.
2423 }
2424 }
2425
2426 private AudioManager getAudioManager() {
2427 if (mView == null) {
2428 throw new IllegalStateException("getAudioManager called when there is no mView");
2429 }
2430 if (mAudioManager == null) {
2431 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2432 }
2433 return mAudioManager;
2434 }
2435
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002436 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2437 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002438
2439 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002440 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002441 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002442 restore = true;
2443 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002444 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002445 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002446 if (params != null) {
2447 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002448 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002449 int relayoutResult = sWindowSession.relayout(
2450 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002451 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2452 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002453 viewVisibility, insetsPending, mWinFrame,
2454 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002455 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002456 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002457 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002458
2459 if (mTranslator != null) {
2460 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2461 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2462 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002463 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002464 return relayoutResult;
2465 }
Romain Guy8506ab42009-06-11 17:35:47 -07002466
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002467 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 * {@inheritDoc}
2469 */
2470 public void playSoundEffect(int effectId) {
2471 checkThread();
2472
2473 final AudioManager audioManager = getAudioManager();
2474
2475 switch (effectId) {
2476 case SoundEffectConstants.CLICK:
2477 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2478 return;
2479 case SoundEffectConstants.NAVIGATION_DOWN:
2480 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2481 return;
2482 case SoundEffectConstants.NAVIGATION_LEFT:
2483 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2484 return;
2485 case SoundEffectConstants.NAVIGATION_RIGHT:
2486 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2487 return;
2488 case SoundEffectConstants.NAVIGATION_UP:
2489 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2490 return;
2491 default:
2492 throw new IllegalArgumentException("unknown effect id " + effectId +
2493 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2494 }
2495 }
2496
2497 /**
2498 * {@inheritDoc}
2499 */
2500 public boolean performHapticFeedback(int effectId, boolean always) {
2501 try {
2502 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2503 } catch (RemoteException e) {
2504 return false;
2505 }
2506 }
2507
2508 /**
2509 * {@inheritDoc}
2510 */
2511 public View focusSearch(View focused, int direction) {
2512 checkThread();
2513 if (!(mView instanceof ViewGroup)) {
2514 return null;
2515 }
2516 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2517 }
2518
2519 public void debug() {
2520 mView.debug();
2521 }
2522
2523 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002524 if (immediate) {
2525 doDie();
2526 } else {
2527 sendEmptyMessage(DIE);
2528 }
2529 }
2530
2531 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 checkThread();
2533 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2534 synchronized (this) {
2535 if (mAdded && !mFirst) {
2536 int viewVisibility = mView.getVisibility();
2537 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2538 if (mWindowAttributesChanged || viewVisibilityChanged) {
2539 // If layout params have been changed, first give them
2540 // to the window manager to make sure it has the correct
2541 // animation info.
2542 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002543 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2544 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 sWindowSession.finishDrawing(mWindow);
2546 }
2547 } catch (RemoteException e) {
2548 }
2549 }
2550
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002551 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
2553 if (mAdded) {
2554 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002555 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
2557 }
2558 }
2559
2560 public void dispatchFinishedEvent(int seq, boolean handled) {
2561 Message msg = obtainMessage(FINISHED_EVENT);
2562 msg.arg1 = seq;
2563 msg.arg2 = handled ? 1 : 0;
2564 sendMessage(msg);
2565 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 public void dispatchResized(int w, int h, Rect coveredInsets,
2568 Rect visibleInsets, boolean reportDraw) {
2569 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2570 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2571 + " visibleInsets=" + visibleInsets.toShortString()
2572 + " reportDraw=" + reportDraw);
2573 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002574 if (mTranslator != null) {
2575 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2576 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2577 w *= mTranslator.applicationInvertedScale;
2578 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002579 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002580 msg.arg1 = w;
2581 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2583 sendMessage(msg);
2584 }
2585
2586 public void dispatchKey(KeyEvent event) {
2587 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2588 //noinspection ConstantConditions
2589 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2590 if (Config.LOGD) Log.d("keydisp",
2591 "===================================================");
2592 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2593 debug();
2594
2595 if (Config.LOGD) Log.d("keydisp",
2596 "===================================================");
2597 }
2598 }
2599
2600 Message msg = obtainMessage(DISPATCH_KEY);
2601 msg.obj = event;
2602
2603 if (LOCAL_LOGV) Log.v(
2604 "ViewRoot", "sending key " + event + " to " + mView);
2605
2606 sendMessageAtTime(msg, event.getEventTime());
2607 }
2608
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002609 public void dispatchPointer(MotionEvent event, long eventTime,
2610 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 Message msg = obtainMessage(DISPATCH_POINTER);
2612 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002613 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 sendMessageAtTime(msg, eventTime);
2615 }
2616
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002617 public void dispatchTrackball(MotionEvent event, long eventTime,
2618 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2620 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002621 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 sendMessageAtTime(msg, eventTime);
2623 }
2624
2625 public void dispatchAppVisibility(boolean visible) {
2626 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2627 msg.arg1 = visible ? 1 : 0;
2628 sendMessage(msg);
2629 }
2630
2631 public void dispatchGetNewSurface() {
2632 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2633 sendMessage(msg);
2634 }
2635
2636 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2637 Message msg = Message.obtain();
2638 msg.what = WINDOW_FOCUS_CHANGED;
2639 msg.arg1 = hasFocus ? 1 : 0;
2640 msg.arg2 = inTouchMode ? 1 : 0;
2641 sendMessage(msg);
2642 }
2643
Dianne Hackbornffa42482009-09-23 22:20:11 -07002644 public void dispatchCloseSystemDialogs(String reason) {
2645 Message msg = Message.obtain();
2646 msg.what = CLOSE_SYSTEM_DIALOGS;
2647 msg.obj = reason;
2648 sendMessage(msg);
2649 }
2650
svetoslavganov75986cf2009-05-14 22:28:01 -07002651 /**
2652 * The window is getting focus so if there is anything focused/selected
2653 * send an {@link AccessibilityEvent} to announce that.
2654 */
2655 private void sendAccessibilityEvents() {
2656 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2657 return;
2658 }
2659 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2660 View focusedView = mView.findFocus();
2661 if (focusedView != null && focusedView != mView) {
2662 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2663 }
2664 }
2665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 public boolean showContextMenuForChild(View originalView) {
2667 return false;
2668 }
2669
2670 public void createContextMenu(ContextMenu menu) {
2671 }
2672
2673 public void childDrawableStateChanged(View child) {
2674 }
2675
2676 protected Rect getWindowFrame() {
2677 return mWinFrame;
2678 }
2679
2680 void checkThread() {
2681 if (mThread != Thread.currentThread()) {
2682 throw new CalledFromWrongThreadException(
2683 "Only the original thread that created a view hierarchy can touch its views.");
2684 }
2685 }
2686
2687 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2688 // ViewRoot never intercepts touch event, so this can be a no-op
2689 }
2690
2691 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2692 boolean immediate) {
2693 return scrollToRectOrFocus(rectangle, immediate);
2694 }
Romain Guy8506ab42009-06-11 17:35:47 -07002695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 static class InputMethodCallback extends IInputMethodCallback.Stub {
2697 private WeakReference<ViewRoot> mViewRoot;
2698
2699 public InputMethodCallback(ViewRoot viewRoot) {
2700 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2701 }
Romain Guy8506ab42009-06-11 17:35:47 -07002702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 public void finishedEvent(int seq, boolean handled) {
2704 final ViewRoot viewRoot = mViewRoot.get();
2705 if (viewRoot != null) {
2706 viewRoot.dispatchFinishedEvent(seq, handled);
2707 }
2708 }
2709
2710 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2711 // Stub -- not for use in the client.
2712 }
2713 }
Romain Guy8506ab42009-06-11 17:35:47 -07002714
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002715 static class EventCompletion extends Handler {
2716 final IWindow mWindow;
2717 final KeyEvent mKeyEvent;
2718 final boolean mIsPointer;
2719 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002720
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002721 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2722 boolean isPointer, MotionEvent motion) {
2723 super(looper);
2724 mWindow = window;
2725 mKeyEvent = key;
2726 mIsPointer = isPointer;
2727 mMotionEvent = motion;
2728 sendEmptyMessage(0);
2729 }
Romain Guy8506ab42009-06-11 17:35:47 -07002730
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002731 @Override
2732 public void handleMessage(Message msg) {
2733 if (mKeyEvent != null) {
2734 try {
2735 sWindowSession.finishKey(mWindow);
2736 } catch (RemoteException e) {
2737 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002738 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002739 boolean didFinish;
2740 MotionEvent event = mMotionEvent;
2741 if (event == null) {
2742 try {
2743 event = sWindowSession.getPendingPointerMove(mWindow);
2744 } catch (RemoteException e) {
2745 }
2746 didFinish = true;
2747 } else {
2748 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2749 }
2750 if (!didFinish) {
2751 try {
2752 sWindowSession.finishKey(mWindow);
2753 } catch (RemoteException e) {
2754 }
2755 }
2756 } else {
2757 MotionEvent event = mMotionEvent;
2758 if (event == null) {
2759 try {
2760 event = sWindowSession.getPendingTrackballMove(mWindow);
2761 } catch (RemoteException e) {
2762 }
2763 } else {
2764 try {
2765 sWindowSession.finishKey(mWindow);
2766 } catch (RemoteException e) {
2767 }
2768 }
2769 }
2770 }
2771 }
Romain Guy8506ab42009-06-11 17:35:47 -07002772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002774 private final WeakReference<ViewRoot> mViewRoot;
2775 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002777 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002779 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 }
2781
2782 public void resized(int w, int h, Rect coveredInsets,
2783 Rect visibleInsets, boolean reportDraw) {
2784 final ViewRoot viewRoot = mViewRoot.get();
2785 if (viewRoot != null) {
2786 viewRoot.dispatchResized(w, h, coveredInsets,
2787 visibleInsets, reportDraw);
2788 }
2789 }
2790
2791 public void dispatchKey(KeyEvent event) {
2792 final ViewRoot viewRoot = mViewRoot.get();
2793 if (viewRoot != null) {
2794 viewRoot.dispatchKey(event);
2795 } else {
2796 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002797 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 }
2799 }
2800
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002801 public void dispatchPointer(MotionEvent event, long eventTime,
2802 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002804 if (viewRoot != null) {
2805 if (MEASURE_LATENCY) {
2806 // Note: eventTime is in milliseconds
2807 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2808 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002809 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002810 } else {
2811 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
2813 }
2814
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002815 public void dispatchTrackball(MotionEvent event, long eventTime,
2816 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 final ViewRoot viewRoot = mViewRoot.get();
2818 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002819 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002820 } else {
2821 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 }
2823 }
2824
2825 public void dispatchAppVisibility(boolean visible) {
2826 final ViewRoot viewRoot = mViewRoot.get();
2827 if (viewRoot != null) {
2828 viewRoot.dispatchAppVisibility(visible);
2829 }
2830 }
2831
2832 public void dispatchGetNewSurface() {
2833 final ViewRoot viewRoot = mViewRoot.get();
2834 if (viewRoot != null) {
2835 viewRoot.dispatchGetNewSurface();
2836 }
2837 }
2838
2839 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2840 final ViewRoot viewRoot = mViewRoot.get();
2841 if (viewRoot != null) {
2842 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2843 }
2844 }
2845
2846 private static int checkCallingPermission(String permission) {
2847 if (!Process.supportsProcesses()) {
2848 return PackageManager.PERMISSION_GRANTED;
2849 }
2850
2851 try {
2852 return ActivityManagerNative.getDefault().checkPermission(
2853 permission, Binder.getCallingPid(), Binder.getCallingUid());
2854 } catch (RemoteException e) {
2855 return PackageManager.PERMISSION_DENIED;
2856 }
2857 }
2858
2859 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2860 final ViewRoot viewRoot = mViewRoot.get();
2861 if (viewRoot != null) {
2862 final View view = viewRoot.mView;
2863 if (view != null) {
2864 if (checkCallingPermission(Manifest.permission.DUMP) !=
2865 PackageManager.PERMISSION_GRANTED) {
2866 throw new SecurityException("Insufficient permissions to invoke"
2867 + " executeCommand() from pid=" + Binder.getCallingPid()
2868 + ", uid=" + Binder.getCallingUid());
2869 }
2870
2871 OutputStream clientStream = null;
2872 try {
2873 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2874 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2875 } catch (IOException e) {
2876 e.printStackTrace();
2877 } finally {
2878 if (clientStream != null) {
2879 try {
2880 clientStream.close();
2881 } catch (IOException e) {
2882 e.printStackTrace();
2883 }
2884 }
2885 }
2886 }
2887 }
2888 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002889
Dianne Hackbornffa42482009-09-23 22:20:11 -07002890 public void closeSystemDialogs(String reason) {
2891 final ViewRoot viewRoot = mViewRoot.get();
2892 if (viewRoot != null) {
2893 viewRoot.dispatchCloseSystemDialogs(reason);
2894 }
2895 }
2896
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002897 public void dispatchWallpaperOffsets(float x, float y, boolean sync) {
2898 if (sync) {
2899 try {
2900 sWindowSession.wallpaperOffsetsComplete(asBinder());
2901 } catch (RemoteException e) {
2902 }
2903 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 }
2906
2907 /**
2908 * Maintains state information for a single trackball axis, generating
2909 * discrete (DPAD) movements based on raw trackball motion.
2910 */
2911 static final class TrackballAxis {
2912 /**
2913 * The maximum amount of acceleration we will apply.
2914 */
2915 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 /**
2918 * The maximum amount of time (in milliseconds) between events in order
2919 * for us to consider the user to be doing fast trackball movements,
2920 * and thus apply an acceleration.
2921 */
2922 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 /**
2925 * Scaling factor to the time (in milliseconds) between events to how
2926 * much to multiple/divide the current acceleration. When movement
2927 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2928 * FAST_MOVE_TIME it divides it.
2929 */
2930 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 float position;
2933 float absPosition;
2934 float acceleration = 1;
2935 long lastMoveTime = 0;
2936 int step;
2937 int dir;
2938 int nonAccelMovement;
2939
2940 void reset(int _step) {
2941 position = 0;
2942 acceleration = 1;
2943 lastMoveTime = 0;
2944 step = _step;
2945 dir = 0;
2946 }
2947
2948 /**
2949 * Add trackball movement into the state. If the direction of movement
2950 * has been reversed, the state is reset before adding the
2951 * movement (so that you don't have to compensate for any previously
2952 * collected movement before see the result of the movement in the
2953 * new direction).
2954 *
2955 * @return Returns the absolute value of the amount of movement
2956 * collected so far.
2957 */
2958 float collect(float off, long time, String axis) {
2959 long normTime;
2960 if (off > 0) {
2961 normTime = (long)(off * FAST_MOVE_TIME);
2962 if (dir < 0) {
2963 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2964 position = 0;
2965 step = 0;
2966 acceleration = 1;
2967 lastMoveTime = 0;
2968 }
2969 dir = 1;
2970 } else if (off < 0) {
2971 normTime = (long)((-off) * FAST_MOVE_TIME);
2972 if (dir > 0) {
2973 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2974 position = 0;
2975 step = 0;
2976 acceleration = 1;
2977 lastMoveTime = 0;
2978 }
2979 dir = -1;
2980 } else {
2981 normTime = 0;
2982 }
Romain Guy8506ab42009-06-11 17:35:47 -07002983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 // The number of milliseconds between each movement that is
2985 // considered "normal" and will not result in any acceleration
2986 // or deceleration, scaled by the offset we have here.
2987 if (normTime > 0) {
2988 long delta = time - lastMoveTime;
2989 lastMoveTime = time;
2990 float acc = acceleration;
2991 if (delta < normTime) {
2992 // The user is scrolling rapidly, so increase acceleration.
2993 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2994 if (scale > 1) acc *= scale;
2995 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2996 + off + " normTime=" + normTime + " delta=" + delta
2997 + " scale=" + scale + " acc=" + acc);
2998 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2999 } else {
3000 // The user is scrolling slowly, so decrease acceleration.
3001 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3002 if (scale > 1) acc /= scale;
3003 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3004 + off + " normTime=" + normTime + " delta=" + delta
3005 + " scale=" + scale + " acc=" + acc);
3006 acceleration = acc > 1 ? acc : 1;
3007 }
3008 }
3009 position += off;
3010 return (absPosition = Math.abs(position));
3011 }
3012
3013 /**
3014 * Generate the number of discrete movement events appropriate for
3015 * the currently collected trackball movement.
3016 *
3017 * @param precision The minimum movement required to generate the
3018 * first discrete movement.
3019 *
3020 * @return Returns the number of discrete movements, either positive
3021 * or negative, or 0 if there is not enough trackball movement yet
3022 * for a discrete movement.
3023 */
3024 int generate(float precision) {
3025 int movement = 0;
3026 nonAccelMovement = 0;
3027 do {
3028 final int dir = position >= 0 ? 1 : -1;
3029 switch (step) {
3030 // If we are going to execute the first step, then we want
3031 // to do this as soon as possible instead of waiting for
3032 // a full movement, in order to make things look responsive.
3033 case 0:
3034 if (absPosition < precision) {
3035 return movement;
3036 }
3037 movement += dir;
3038 nonAccelMovement += dir;
3039 step = 1;
3040 break;
3041 // If we have generated the first movement, then we need
3042 // to wait for the second complete trackball motion before
3043 // generating the second discrete movement.
3044 case 1:
3045 if (absPosition < 2) {
3046 return movement;
3047 }
3048 movement += dir;
3049 nonAccelMovement += dir;
3050 position += dir > 0 ? -2 : 2;
3051 absPosition = Math.abs(position);
3052 step = 2;
3053 break;
3054 // After the first two, we generate discrete movements
3055 // consistently with the trackball, applying an acceleration
3056 // if the trackball is moving quickly. This is a simple
3057 // acceleration on top of what we already compute based
3058 // on how quickly the wheel is being turned, to apply
3059 // a longer increasing acceleration to continuous movement
3060 // in one direction.
3061 default:
3062 if (absPosition < 1) {
3063 return movement;
3064 }
3065 movement += dir;
3066 position += dir >= 0 ? -1 : 1;
3067 absPosition = Math.abs(position);
3068 float acc = acceleration;
3069 acc *= 1.1f;
3070 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3071 break;
3072 }
3073 } while (true);
3074 }
3075 }
3076
3077 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3078 public CalledFromWrongThreadException(String msg) {
3079 super(msg);
3080 }
3081 }
3082
3083 private SurfaceHolder mHolder = new SurfaceHolder() {
3084 // we only need a SurfaceHolder for opengl. it would be nice
3085 // to implement everything else though, especially the callback
3086 // support (opengl doesn't make use of it right now, but eventually
3087 // will).
3088 public Surface getSurface() {
3089 return mSurface;
3090 }
3091
3092 public boolean isCreating() {
3093 return false;
3094 }
3095
3096 public void addCallback(Callback callback) {
3097 }
3098
3099 public void removeCallback(Callback callback) {
3100 }
3101
3102 public void setFixedSize(int width, int height) {
3103 }
3104
3105 public void setSizeFromLayout() {
3106 }
3107
3108 public void setFormat(int format) {
3109 }
3110
3111 public void setType(int type) {
3112 }
3113
3114 public void setKeepScreenOn(boolean screenOn) {
3115 }
3116
3117 public Canvas lockCanvas() {
3118 return null;
3119 }
3120
3121 public Canvas lockCanvas(Rect dirty) {
3122 return null;
3123 }
3124
3125 public void unlockCanvasAndPost(Canvas canvas) {
3126 }
3127 public Rect getSurfaceFrame() {
3128 return null;
3129 }
3130 };
3131
3132 static RunQueue getRunQueue() {
3133 RunQueue rq = sRunQueues.get();
3134 if (rq != null) {
3135 return rq;
3136 }
3137 rq = new RunQueue();
3138 sRunQueues.set(rq);
3139 return rq;
3140 }
Romain Guy8506ab42009-06-11 17:35:47 -07003141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 /**
3143 * @hide
3144 */
3145 static final class RunQueue {
3146 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3147
3148 void post(Runnable action) {
3149 postDelayed(action, 0);
3150 }
3151
3152 void postDelayed(Runnable action, long delayMillis) {
3153 HandlerAction handlerAction = new HandlerAction();
3154 handlerAction.action = action;
3155 handlerAction.delay = delayMillis;
3156
3157 synchronized (mActions) {
3158 mActions.add(handlerAction);
3159 }
3160 }
3161
3162 void removeCallbacks(Runnable action) {
3163 final HandlerAction handlerAction = new HandlerAction();
3164 handlerAction.action = action;
3165
3166 synchronized (mActions) {
3167 final ArrayList<HandlerAction> actions = mActions;
3168
3169 while (actions.remove(handlerAction)) {
3170 // Keep going
3171 }
3172 }
3173 }
3174
3175 void executeActions(Handler handler) {
3176 synchronized (mActions) {
3177 final ArrayList<HandlerAction> actions = mActions;
3178 final int count = actions.size();
3179
3180 for (int i = 0; i < count; i++) {
3181 final HandlerAction handlerAction = actions.get(i);
3182 handler.postDelayed(handlerAction.action, handlerAction.delay);
3183 }
3184
Romain Guy15df6702009-08-17 20:17:30 -07003185 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 }
3187 }
3188
3189 private static class HandlerAction {
3190 Runnable action;
3191 long delay;
3192
3193 @Override
3194 public boolean equals(Object o) {
3195 if (this == o) return true;
3196 if (o == null || getClass() != o.getClass()) return false;
3197
3198 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 return !(action != null ? !action.equals(that.action) : that.action != null);
3200
3201 }
3202
3203 @Override
3204 public int hashCode() {
3205 int result = action != null ? action.hashCode() : 0;
3206 result = 31 * result + (int) (delay ^ (delay >>> 32));
3207 return result;
3208 }
3209 }
3210 }
3211
3212 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3213
3214 // inform skia to just abandon its texture cache IDs
3215 // doesn't call glDeleteTextures
3216 private static native void nativeAbandonGlCaches();
3217}