blob: 5c2b3c94856725f07fbe7561213c9d1a8c3dcdc6 [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;
Mike Reedfd716532009-10-12 14:42:56 -040071 private static final boolean SHOW_FPS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 @SuppressWarnings({"ConstantConditionalExpression"})
73 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
74 /** @noinspection PointlessBooleanExpression*/
75 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
76 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
77 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
78 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
79 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
80 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
81 private static final boolean WATCH_POINTER = false;
82
Michael Chan53071d62009-05-13 17:29:48 -070083 private static final boolean MEASURE_LATENCY = false;
84 private static LatencyTimer lt;
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 /**
87 * Maximum time we allow the user to roll the trackball enough to generate
88 * a key event, before resetting the counters.
89 */
90 static final int MAX_TRACKBALL_DELAY = 250;
91
92 static long sInstanceCount = 0;
93
94 static IWindowSession sWindowSession;
95
96 static final Object mStaticInit = new Object();
97 static boolean mInitialized = false;
98
99 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
100
Romain Guy8506ab42009-06-11 17:35:47 -0700101 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 long mLastTrackballTime = 0;
104 final TrackballAxis mTrackballAxisX = new TrackballAxis();
105 final TrackballAxis mTrackballAxisY = new TrackballAxis();
106
107 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 final InputMethodCallback mInputMethodCallback;
110 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
111 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 final Thread mThread;
114
115 final WindowLeaked mLocation;
116
117 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
118
119 final W mWindow;
120
121 View mView;
122 View mFocusedView;
123 View mRealFocusedView; // this is not set to null in touch mode
124 int mViewVisibility;
125 boolean mAppVisible = true;
126
127 final Region mTransparentRegion;
128 final Region mPreviousTransparentRegion;
129
130 int mWidth;
131 int mHeight;
132 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700133 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700134
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700135 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
137 final View.AttachInfo mAttachInfo;
138
139 final Rect mTempRect; // used in the transaction to not thrash the heap.
140 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 boolean mTraversalScheduled;
143 boolean mWillDrawSoon;
144 boolean mLayoutRequested;
145 boolean mFirst;
146 boolean mReportNextDraw;
147 boolean mFullRedrawNeeded;
148 boolean mNewSurfaceNeeded;
149 boolean mHasHadWindowFocus;
150 boolean mLastWasImTarget;
151
152 boolean mWindowAttributesChanged = false;
153
154 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700155 // Surface can never be reassigned or cleared (use Surface.clear()).
156 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
158 boolean mAdded;
159 boolean mAddedTouchMode;
160
161 /*package*/ int mAddNesting;
162
163 // These are accessed by multiple threads.
164 final Rect mWinFrame; // frame given by window manager.
165
166 final Rect mPendingVisibleInsets = new Rect();
167 final Rect mPendingContentInsets = new Rect();
168 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
169 = new ViewTreeObserver.InternalInsetsInfo();
170
171 boolean mScrollMayChange;
172 int mSoftInputMode;
173 View mLastScrolledFocus;
174 int mScrollY;
175 int mCurScrollY;
176 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 EGL10 mEgl;
179 EGLDisplay mEglDisplay;
180 EGLContext mEglContext;
181 EGLSurface mEglSurface;
182 GL11 mGL;
183 Canvas mGlCanvas;
184 boolean mUseGL;
185 boolean mGlWanted;
186
Romain Guy8506ab42009-06-11 17:35:47 -0700187 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
189 /**
190 * see {@link #playSoundEffect(int)}
191 */
192 AudioManager mAudioManager;
193
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700194 private final int mDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700196 public static IWindowSession getWindowSession(Looper mainLooper) {
197 synchronized (mStaticInit) {
198 if (!mInitialized) {
199 try {
200 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
201 sWindowSession = IWindowManager.Stub.asInterface(
202 ServiceManager.getService("window"))
203 .openSession(imm.getClient(), imm.getInputContext());
204 mInitialized = true;
205 } catch (RemoteException e) {
206 }
207 }
208 return sWindowSession;
209 }
210 }
211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 public ViewRoot(Context context) {
213 super();
214
Michael Chan53071d62009-05-13 17:29:48 -0700215 if (MEASURE_LATENCY && lt == null) {
216 lt = new LatencyTimer(100, 1000);
217 }
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 ++sInstanceCount;
220
221 // Initialize the statics when this class is first instantiated. This is
222 // done here instead of in the static block because Zygote does not
223 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700224 getWindowSession(context.getMainLooper());
225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 mThread = Thread.currentThread();
227 mLocation = new WindowLeaked(null);
228 mLocation.fillInStackTrace();
229 mWidth = -1;
230 mHeight = -1;
231 mDirty = new Rect();
232 mTempRect = new Rect();
233 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700235 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 mInputMethodCallback = new InputMethodCallback(this);
237 mViewVisibility = View.GONE;
238 mTransparentRegion = new Region();
239 mPreviousTransparentRegion = new Region();
240 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 mAdded = false;
242 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
243 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700244 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 }
246
247 @Override
248 protected void finalize() throws Throwable {
249 super.finalize();
250 --sInstanceCount;
251 }
252
253 public static long getInstanceCount() {
254 return sInstanceCount;
255 }
256
257 // FIXME for perf testing only
258 private boolean mProfile = false;
259
260 /**
261 * Call this to profile the next traversal call.
262 * FIXME for perf testing only. Remove eventually
263 */
264 public void profile() {
265 mProfile = true;
266 }
267
268 /**
269 * Indicates whether we are in touch mode. Calling this method triggers an IPC
270 * call and should be avoided whenever possible.
271 *
272 * @return True, if the device is in touch mode, false otherwise.
273 *
274 * @hide
275 */
276 static boolean isInTouchMode() {
277 if (mInitialized) {
278 try {
279 return sWindowSession.getInTouchMode();
280 } catch (RemoteException e) {
281 }
282 }
283 return false;
284 }
285
286 private void initializeGL() {
287 initializeGLInner();
288 int err = mEgl.eglGetError();
289 if (err != EGL10.EGL_SUCCESS) {
290 // give-up on using GL
291 destroyGL();
292 mGlWanted = false;
293 }
294 }
295
296 private void initializeGLInner() {
297 final EGL10 egl = (EGL10) EGLContext.getEGL();
298 mEgl = egl;
299
300 /*
301 * Get to the default display.
302 */
303 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
304 mEglDisplay = eglDisplay;
305
306 /*
307 * We can now initialize EGL for that display
308 */
309 int[] version = new int[2];
310 egl.eglInitialize(eglDisplay, version);
311
312 /*
313 * Specify a configuration for our opengl session
314 * and grab the first configuration that matches is
315 */
316 final int[] configSpec = {
317 EGL10.EGL_RED_SIZE, 5,
318 EGL10.EGL_GREEN_SIZE, 6,
319 EGL10.EGL_BLUE_SIZE, 5,
320 EGL10.EGL_DEPTH_SIZE, 0,
321 EGL10.EGL_NONE
322 };
323 final EGLConfig[] configs = new EGLConfig[1];
324 final int[] num_config = new int[1];
325 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
326 final EGLConfig config = configs[0];
327
328 /*
329 * Create an OpenGL ES context. This must be done only once, an
330 * OpenGL context is a somewhat heavy object.
331 */
332 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
333 EGL10.EGL_NO_CONTEXT, null);
334 mEglContext = context;
335
336 /*
337 * Create an EGL surface we can render into.
338 */
339 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
340 mEglSurface = surface;
341
342 /*
343 * Before we can issue GL commands, we need to make sure
344 * the context is current and bound to a surface.
345 */
346 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
347
348 /*
349 * Get to the appropriate GL interface.
350 * This is simply done by casting the GL context to either
351 * GL10 or GL11.
352 */
353 final GL11 gl = (GL11) context.getGL();
354 mGL = gl;
355 mGlCanvas = new Canvas(gl);
356 mUseGL = true;
357 }
358
359 private void destroyGL() {
360 // inform skia that the context is gone
361 nativeAbandonGlCaches();
362
363 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
364 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
365 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
366 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
367 mEgl.eglTerminate(mEglDisplay);
368 mEglContext = null;
369 mEglSurface = null;
370 mEglDisplay = null;
371 mEgl = null;
372 mGlCanvas = null;
373 mGL = null;
374 mUseGL = false;
375 }
376
377 private void checkEglErrors() {
378 if (mUseGL) {
379 int err = mEgl.eglGetError();
380 if (err != EGL10.EGL_SUCCESS) {
381 // something bad has happened revert to
382 // normal rendering.
383 destroyGL();
384 if (err != EGL11.EGL_CONTEXT_LOST) {
385 // we'll try again if it was context lost
386 mGlWanted = false;
387 }
388 }
389 }
390 }
391
392 /**
393 * We have one child
394 */
395 public void setView(View view, WindowManager.LayoutParams attrs,
396 View panelParentView) {
397 synchronized (this) {
398 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700399 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700400 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700401 attrs = mWindowAttributes;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700402 Resources resources = mView.getContext().getResources();
403 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700404 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700405
406 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700407 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
408 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700409 }
410
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700411 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700412 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700413 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700414 attrs.backup();
415 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700416 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700417 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
418
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700419 if (!compatibilityInfo.supportsScreen()) {
420 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
421 }
422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 mSoftInputMode = attrs.softInputMode;
424 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700426 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700427 mAttachInfo.mApplicationScale =
428 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 if (panelParentView != null) {
430 mAttachInfo.mPanelParentWindowToken
431 = panelParentView.getApplicationWindowToken();
432 }
433 mAdded = true;
434 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 // Schedule the first layout -before- adding to the window
437 // manager, to make sure we do the relayout before receiving
438 // any other events from the system.
439 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700441 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 getHostVisibility(), mAttachInfo.mContentInsets);
443 } catch (RemoteException e) {
444 mAdded = false;
445 mView = null;
446 mAttachInfo.mRootView = null;
447 unscheduleTraversals();
448 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700449 } finally {
450 if (restore) {
451 attrs.restore();
452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700454
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700455 if (mTranslator != null) {
456 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 mPendingContentInsets.set(mAttachInfo.mContentInsets);
459 mPendingVisibleInsets.set(0, 0, 0, 0);
460 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
461 if (res < WindowManagerImpl.ADD_OKAY) {
462 mView = null;
463 mAttachInfo.mRootView = null;
464 mAdded = false;
465 unscheduleTraversals();
466 switch (res) {
467 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
468 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
469 throw new WindowManagerImpl.BadTokenException(
470 "Unable to add window -- token " + attrs.token
471 + " is not valid; is your activity running?");
472 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
473 throw new WindowManagerImpl.BadTokenException(
474 "Unable to add window -- token " + attrs.token
475 + " is not for an application");
476 case WindowManagerImpl.ADD_APP_EXITING:
477 throw new WindowManagerImpl.BadTokenException(
478 "Unable to add window -- app for token " + attrs.token
479 + " is exiting");
480 case WindowManagerImpl.ADD_DUPLICATE_ADD:
481 throw new WindowManagerImpl.BadTokenException(
482 "Unable to add window -- window " + mWindow
483 + " has already been added");
484 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
485 // Silently ignore -- we would have just removed it
486 // right away, anyway.
487 return;
488 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
489 throw new WindowManagerImpl.BadTokenException(
490 "Unable to add window " + mWindow +
491 " -- another window of this type already exists");
492 case WindowManagerImpl.ADD_PERMISSION_DENIED:
493 throw new WindowManagerImpl.BadTokenException(
494 "Unable to add window " + mWindow +
495 " -- permission denied for this window type");
496 }
497 throw new RuntimeException(
498 "Unable to add window -- unknown error code " + res);
499 }
500 view.assignParent(this);
501 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
502 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
503 }
504 }
505 }
506
507 public View getView() {
508 return mView;
509 }
510
511 final WindowLeaked getLocation() {
512 return mLocation;
513 }
514
515 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
516 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700517 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700518 // preserve compatible window flag if exists.
519 int compatibleWindowFlag =
520 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700522 mWindowAttributes.flags |= compatibleWindowFlag;
523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 if (newView) {
525 mSoftInputMode = attrs.softInputMode;
526 requestLayout();
527 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700528 // Don't lose the mode we last auto-computed.
529 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
530 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
531 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
532 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
533 | (oldSoftInputMode
534 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 mWindowAttributesChanged = true;
537 scheduleTraversals();
538 }
539 }
540
541 void handleAppVisibility(boolean visible) {
542 if (mAppVisible != visible) {
543 mAppVisible = visible;
544 scheduleTraversals();
545 }
546 }
547
548 void handleGetNewSurface() {
549 mNewSurfaceNeeded = true;
550 mFullRedrawNeeded = true;
551 scheduleTraversals();
552 }
553
554 /**
555 * {@inheritDoc}
556 */
557 public void requestLayout() {
558 checkThread();
559 mLayoutRequested = true;
560 scheduleTraversals();
561 }
562
563 /**
564 * {@inheritDoc}
565 */
566 public boolean isLayoutRequested() {
567 return mLayoutRequested;
568 }
569
570 public void invalidateChild(View child, Rect dirty) {
571 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700572 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
573 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700575 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700576 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700577 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700578 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700579 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700580 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700581 }
Romain Guy1e095972009-07-07 11:22:45 -0700582 if (mAttachInfo.mScalingRequired) {
583 dirty.inset(-1, -1);
584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
586 mDirty.union(dirty);
587 if (!mWillDrawSoon) {
588 scheduleTraversals();
589 }
590 }
591
592 public ViewParent getParent() {
593 return null;
594 }
595
596 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
597 invalidateChild(null, dirty);
598 return null;
599 }
600
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700601 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 if (child != mView) {
603 throw new RuntimeException("child is not mine, honest!");
604 }
605 // Note: don't apply scroll offset, because we want to know its
606 // visibility in the virtual canvas being given to the view hierarchy.
607 return r.intersect(0, 0, mWidth, mHeight);
608 }
609
610 public void bringChildToFront(View child) {
611 }
612
613 public void scheduleTraversals() {
614 if (!mTraversalScheduled) {
615 mTraversalScheduled = true;
616 sendEmptyMessage(DO_TRAVERSAL);
617 }
618 }
619
620 public void unscheduleTraversals() {
621 if (mTraversalScheduled) {
622 mTraversalScheduled = false;
623 removeMessages(DO_TRAVERSAL);
624 }
625 }
626
627 int getHostVisibility() {
628 return mAppVisible ? mView.getVisibility() : View.GONE;
629 }
Romain Guy8506ab42009-06-11 17:35:47 -0700630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 private void performTraversals() {
632 // cache mView since it is used so much below...
633 final View host = mView;
634
635 if (DBG) {
636 System.out.println("======================================");
637 System.out.println("performTraversals");
638 host.debug();
639 }
640
641 if (host == null || !mAdded)
642 return;
643
644 mTraversalScheduled = false;
645 mWillDrawSoon = true;
646 boolean windowResizesToFitContent = false;
647 boolean fullRedrawNeeded = mFullRedrawNeeded;
648 boolean newSurface = false;
649 WindowManager.LayoutParams lp = mWindowAttributes;
650
651 int desiredWindowWidth;
652 int desiredWindowHeight;
653 int childWidthMeasureSpec;
654 int childHeightMeasureSpec;
655
656 final View.AttachInfo attachInfo = mAttachInfo;
657
658 final int viewVisibility = getHostVisibility();
659 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
660 || mNewSurfaceNeeded;
661
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700662 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 WindowManager.LayoutParams params = null;
665 if (mWindowAttributesChanged) {
666 mWindowAttributesChanged = false;
667 params = lp;
668 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700669 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 if (mFirst) {
671 fullRedrawNeeded = true;
672 mLayoutRequested = true;
673
Romain Guy8506ab42009-06-11 17:35:47 -0700674 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700675 mView.getContext().getResources().getDisplayMetrics();
676 desiredWindowWidth = packageMetrics.widthPixels;
677 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678
679 // For the very first time, tell the view hierarchy that it
680 // is attached to the window. Note that at this point the surface
681 // object is not initialized to its backing store, but soon it
682 // will be (assuming the window is visible).
683 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700684 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 attachInfo.mHasWindowFocus = false;
686 attachInfo.mWindowVisibility = viewVisibility;
687 attachInfo.mRecomputeGlobalAttributes = false;
688 attachInfo.mKeepScreenOn = false;
689 viewVisibilityChanged = false;
690 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700694 desiredWindowWidth = frame.width();
695 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
697 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700698 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 fullRedrawNeeded = true;
700 mLayoutRequested = true;
701 windowResizesToFitContent = true;
702 }
703 }
704
705 if (viewVisibilityChanged) {
706 attachInfo.mWindowVisibility = viewVisibility;
707 host.dispatchWindowVisibilityChanged(viewVisibility);
708 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
709 if (mUseGL) {
710 destroyGL();
711 }
712 }
713 if (viewVisibility == View.GONE) {
714 // After making a window gone, we will count it as being
715 // shown for the first time the next time it gets focus.
716 mHasHadWindowFocus = false;
717 }
718 }
719
720 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700723 // Execute enqueued actions on every layout in case a view that was detached
724 // enqueued an action after being detached
725 getRunQueue().executeActions(attachInfo.mHandler);
726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 if (mFirst) {
728 host.fitSystemWindows(mAttachInfo.mContentInsets);
729 // make sure touch mode code executes by setting cached value
730 // to opposite of the added touch mode.
731 mAttachInfo.mInTouchMode = !mAddedTouchMode;
732 ensureTouchModeLocally(mAddedTouchMode);
733 } else {
734 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
735 mAttachInfo.mContentInsets.set(mPendingContentInsets);
736 host.fitSystemWindows(mAttachInfo.mContentInsets);
737 insetsChanged = true;
738 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
739 + mAttachInfo.mContentInsets);
740 }
741 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
742 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
743 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
744 + mAttachInfo.mVisibleInsets);
745 }
746 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
747 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
748 windowResizesToFitContent = true;
749
Romain Guy8506ab42009-06-11 17:35:47 -0700750 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700751 mView.getContext().getResources().getDisplayMetrics();
752 desiredWindowWidth = packageMetrics.widthPixels;
753 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 }
755 }
756
757 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
758 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
759
760 // Ask host how big it wants to be
761 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
762 "Measuring " + host + " in display " + desiredWindowWidth
763 + "x" + desiredWindowHeight + "...");
764 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
765
766 if (DBG) {
767 System.out.println("======================================");
768 System.out.println("performTraversals -- after measure");
769 host.debug();
770 }
771 }
772
773 if (attachInfo.mRecomputeGlobalAttributes) {
774 //Log.i(TAG, "Computing screen on!");
775 attachInfo.mRecomputeGlobalAttributes = false;
776 boolean oldVal = attachInfo.mKeepScreenOn;
777 attachInfo.mKeepScreenOn = false;
778 host.dispatchCollectViewAttributes(0);
779 if (attachInfo.mKeepScreenOn != oldVal) {
780 params = lp;
781 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
782 }
783 }
784
785 if (mFirst || attachInfo.mViewVisibilityChanged) {
786 attachInfo.mViewVisibilityChanged = false;
787 int resizeMode = mSoftInputMode &
788 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
789 // If we are in auto resize mode, then we need to determine
790 // what mode to use now.
791 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
792 final int N = attachInfo.mScrollContainers.size();
793 for (int i=0; i<N; i++) {
794 if (attachInfo.mScrollContainers.get(i).isShown()) {
795 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
796 }
797 }
798 if (resizeMode == 0) {
799 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
800 }
801 if ((lp.softInputMode &
802 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
803 lp.softInputMode = (lp.softInputMode &
804 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
805 resizeMode;
806 params = lp;
807 }
808 }
809 }
Romain Guy8506ab42009-06-11 17:35:47 -0700810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
812 if (!PixelFormat.formatHasAlpha(params.format)) {
813 params.format = PixelFormat.TRANSLUCENT;
814 }
815 }
816
817 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
818 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
819
820 final boolean computesInternalInsets =
821 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
822 boolean insetsPending = false;
823 int relayoutResult = 0;
824 if (mFirst || windowShouldResize || insetsChanged
825 || viewVisibilityChanged || params != null) {
826
827 if (viewVisibility == View.VISIBLE) {
828 // If this window is giving internal insets to the window
829 // manager, and it is being added or changing its visibility,
830 // then we want to first give the window manager "fake"
831 // insets to cause it to effectively ignore the content of
832 // the window during layout. This avoids it briefly causing
833 // other windows to resize/move based on the raw frame of the
834 // window, waiting until we can finish laying out this window
835 // and get back to the window manager with the ultimately
836 // computed insets.
837 insetsPending = computesInternalInsets
838 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
841 if (params == null) {
842 params = mWindowAttributes;
843 }
844 mGlWanted = true;
845 }
846 }
847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 boolean initialized = false;
849 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700850 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 try {
852 boolean hadSurface = mSurface.isValid();
853 int fl = 0;
854 if (params != null) {
855 fl = params.flags;
856 if (attachInfo.mKeepScreenOn) {
857 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
858 }
859 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700860 if (DEBUG_LAYOUT) {
861 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
862 host.mMeasuredHeight + ", params=" + params);
863 }
864 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 if (params != null) {
867 params.flags = fl;
868 }
869
870 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
871 + " content=" + mPendingContentInsets.toShortString()
872 + " visible=" + mPendingVisibleInsets.toShortString()
873 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 contentInsetsChanged = !mPendingContentInsets.equals(
876 mAttachInfo.mContentInsets);
877 visibleInsetsChanged = !mPendingVisibleInsets.equals(
878 mAttachInfo.mVisibleInsets);
879 if (contentInsetsChanged) {
880 mAttachInfo.mContentInsets.set(mPendingContentInsets);
881 host.fitSystemWindows(mAttachInfo.mContentInsets);
882 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
883 + mAttachInfo.mContentInsets);
884 }
885 if (visibleInsetsChanged) {
886 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
887 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
888 + mAttachInfo.mVisibleInsets);
889 }
890
891 if (!hadSurface) {
892 if (mSurface.isValid()) {
893 // If we are creating a new surface, then we need to
894 // completely redraw it. Also, when we get to the
895 // point of drawing it we will hold off and schedule
896 // a new traversal instead. This is so we can tell the
897 // window manager about all of the windows being displayed
898 // before actually drawing them, so it can display then
899 // all at once.
900 newSurface = true;
901 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700902 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 if (mGlWanted && !mUseGL) {
905 initializeGL();
906 initialized = mGlCanvas != null;
907 }
908 }
909 } else if (!mSurface.isValid()) {
910 // If the surface has been removed, then reset the scroll
911 // positions.
912 mLastScrolledFocus = null;
913 mScrollY = mCurScrollY = 0;
914 if (mScroller != null) {
915 mScroller.abortAnimation();
916 }
917 }
918 } catch (RemoteException e) {
919 }
920 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700921 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922
923 attachInfo.mWindowLeft = frame.left;
924 attachInfo.mWindowTop = frame.top;
925
926 // !!FIXME!! This next section handles the case where we did not get the
927 // window size we asked for. We should avoid this by getting a maximum size from
928 // the window session beforehand.
929 mWidth = frame.width();
930 mHeight = frame.height();
931
932 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -0700933 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
934 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936
937 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
938 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
939 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
940 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
941 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
942 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
943
944 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
945 + mWidth + " measuredWidth=" + host.mMeasuredWidth
946 + " mHeight=" + mHeight
947 + " measuredHeight" + host.mMeasuredHeight
948 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 // Ask host how big it wants to be
951 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
952
953 // Implementation of weights from WindowManager.LayoutParams
954 // We just grow the dimensions as needed and re-measure if
955 // needs be
956 int width = host.mMeasuredWidth;
957 int height = host.mMeasuredHeight;
958 boolean measureAgain = false;
959
960 if (lp.horizontalWeight > 0.0f) {
961 width += (int) ((mWidth - width) * lp.horizontalWeight);
962 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
963 MeasureSpec.EXACTLY);
964 measureAgain = true;
965 }
966 if (lp.verticalWeight > 0.0f) {
967 height += (int) ((mHeight - height) * lp.verticalWeight);
968 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
969 MeasureSpec.EXACTLY);
970 measureAgain = true;
971 }
972
973 if (measureAgain) {
974 if (DEBUG_LAYOUT) Log.v(TAG,
975 "And hey let's measure once more: width=" + width
976 + " height=" + height);
977 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
978 }
979
980 mLayoutRequested = true;
981 }
982 }
983
984 final boolean didLayout = mLayoutRequested;
985 boolean triggerGlobalLayoutListener = didLayout
986 || attachInfo.mRecomputeGlobalAttributes;
987 if (didLayout) {
988 mLayoutRequested = false;
989 mScrollMayChange = true;
990 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
991 "ViewRoot", "Laying out " + host + " to (" +
992 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700993 long startTime = 0L;
994 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 startTime = SystemClock.elapsedRealtime();
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
998
Romain Guy13922e02009-05-12 17:56:14 -0700999 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1000 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1001 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1002 + "please refer to the logs with the tag "
1003 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1004 }
1005 }
1006
1007 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1009 }
1010
1011 // By this point all views have been sized and positionned
1012 // We can compute the transparent area
1013
1014 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1015 // start out transparent
1016 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1017 host.getLocationInWindow(mTmpLocation);
1018 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1019 mTmpLocation[0] + host.mRight - host.mLeft,
1020 mTmpLocation[1] + host.mBottom - host.mTop);
1021
1022 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001023 if (mTranslator != null) {
1024 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1025 }
1026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1028 mPreviousTransparentRegion.set(mTransparentRegion);
1029 // reconfigure window manager
1030 try {
1031 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1032 } catch (RemoteException e) {
1033 }
1034 }
1035 }
1036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 if (DBG) {
1038 System.out.println("======================================");
1039 System.out.println("performTraversals -- after setFrame");
1040 host.debug();
1041 }
1042 }
1043
1044 if (triggerGlobalLayoutListener) {
1045 attachInfo.mRecomputeGlobalAttributes = false;
1046 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1047 }
1048
1049 if (computesInternalInsets) {
1050 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1051 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1052 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1053 givenContent.left = givenContent.top = givenContent.right
1054 = givenContent.bottom = givenVisible.left = givenVisible.top
1055 = givenVisible.right = givenVisible.bottom = 0;
1056 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001057 Rect contentInsets = insets.contentInsets;
1058 Rect visibleInsets = insets.visibleInsets;
1059 if (mTranslator != null) {
1060 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1061 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1064 mLastGivenInsets.set(insets);
1065 try {
1066 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001067 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } catch (RemoteException e) {
1069 }
1070 }
1071 }
Romain Guy8506ab42009-06-11 17:35:47 -07001072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 if (mFirst) {
1074 // handle first focus request
1075 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1076 + mView.hasFocus());
1077 if (mView != null) {
1078 if (!mView.hasFocus()) {
1079 mView.requestFocus(View.FOCUS_FORWARD);
1080 mFocusedView = mRealFocusedView = mView.findFocus();
1081 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1082 + mFocusedView);
1083 } else {
1084 mRealFocusedView = mView.findFocus();
1085 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1086 + mRealFocusedView);
1087 }
1088 }
1089 }
1090
1091 mFirst = false;
1092 mWillDrawSoon = false;
1093 mNewSurfaceNeeded = false;
1094 mViewVisibility = viewVisibility;
1095
1096 if (mAttachInfo.mHasWindowFocus) {
1097 final boolean imTarget = WindowManager.LayoutParams
1098 .mayUseInputMethod(mWindowAttributes.flags);
1099 if (imTarget != mLastWasImTarget) {
1100 mLastWasImTarget = imTarget;
1101 InputMethodManager imm = InputMethodManager.peekInstance();
1102 if (imm != null && imTarget) {
1103 imm.startGettingWindowFocus(mView);
1104 imm.onWindowFocus(mView, mView.findFocus(),
1105 mWindowAttributes.softInputMode,
1106 !mHasHadWindowFocus, mWindowAttributes.flags);
1107 }
1108 }
1109 }
Romain Guy8506ab42009-06-11 17:35:47 -07001110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1112
1113 if (!cancelDraw && !newSurface) {
1114 mFullRedrawNeeded = false;
1115 draw(fullRedrawNeeded);
1116
1117 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1118 || mReportNextDraw) {
1119 if (LOCAL_LOGV) {
1120 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1121 }
1122 mReportNextDraw = false;
1123 try {
1124 sWindowSession.finishDrawing(mWindow);
1125 } catch (RemoteException e) {
1126 }
1127 }
1128 } else {
1129 // We were supposed to report when we are done drawing. Since we canceled the
1130 // draw, remember it here.
1131 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1132 mReportNextDraw = true;
1133 }
1134 if (fullRedrawNeeded) {
1135 mFullRedrawNeeded = true;
1136 }
1137 // Try again
1138 scheduleTraversals();
1139 }
1140 }
1141
1142 public void requestTransparentRegion(View child) {
1143 // the test below should not fail unless someone is messing with us
1144 checkThread();
1145 if (mView == child) {
1146 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1147 // Need to make sure we re-evaluate the window attributes next
1148 // time around, to ensure the window has the correct format.
1149 mWindowAttributesChanged = true;
1150 }
1151 }
1152
1153 /**
1154 * Figures out the measure spec for the root view in a window based on it's
1155 * layout params.
1156 *
1157 * @param windowSize
1158 * The available width or height of the window
1159 *
1160 * @param rootDimension
1161 * The layout params for one dimension (width or height) of the
1162 * window.
1163 *
1164 * @return The measure spec to use to measure the root view.
1165 */
1166 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1167 int measureSpec;
1168 switch (rootDimension) {
1169
1170 case ViewGroup.LayoutParams.FILL_PARENT:
1171 // Window can't resize. Force root view to be windowSize.
1172 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1173 break;
1174 case ViewGroup.LayoutParams.WRAP_CONTENT:
1175 // Window can resize. Set max size for root view.
1176 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1177 break;
1178 default:
1179 // Window wants to be an exact size. Force root view to be that size.
1180 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1181 break;
1182 }
1183 return measureSpec;
1184 }
1185
1186 private void draw(boolean fullRedrawNeeded) {
1187 Surface surface = mSurface;
1188 if (surface == null || !surface.isValid()) {
1189 return;
1190 }
1191
1192 scrollToRectOrFocus(null, false);
1193
1194 if (mAttachInfo.mViewScrollChanged) {
1195 mAttachInfo.mViewScrollChanged = false;
1196 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1197 }
Romain Guy8506ab42009-06-11 17:35:47 -07001198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001200 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 if (scrolling) {
1202 yoff = mScroller.getCurrY();
1203 } else {
1204 yoff = mScrollY;
1205 }
1206 if (mCurScrollY != yoff) {
1207 mCurScrollY = yoff;
1208 fullRedrawNeeded = true;
1209 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001210 float appScale = mAttachInfo.mApplicationScale;
1211 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212
1213 Rect dirty = mDirty;
1214 if (mUseGL) {
1215 if (!dirty.isEmpty()) {
1216 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001217 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 mGL.glDisable(GL_SCISSOR_TEST);
1219 mGL.glClearColor(0, 0, 0, 0);
1220 mGL.glClear(GL_COLOR_BUFFER_BIT);
1221 mGL.glEnable(GL_SCISSOR_TEST);
1222
1223 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001224 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001226
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001227 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1228 try {
1229 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001230 if (mTranslator != null) {
1231 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001232 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001233 canvas.setScreenDensity(scalingRequired
1234 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001235 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001236 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1237 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1238 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001239 } finally {
1240 canvas.restoreToCount(saveCount);
1241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242
Romain Guy5bcdff42009-05-14 21:27:18 -07001243 mAttachInfo.mIgnoreDirtyState = false;
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1246 checkEglErrors();
1247
Mike Reedfd716532009-10-12 14:42:56 -04001248 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 int now = (int)SystemClock.elapsedRealtime();
1250 if (sDrawTime != 0) {
1251 nativeShowFPS(canvas, now - sDrawTime);
1252 }
1253 sDrawTime = now;
1254 }
1255 }
1256 }
1257 if (scrolling) {
1258 mFullRedrawNeeded = true;
1259 scheduleTraversals();
1260 }
1261 return;
1262 }
1263
Romain Guy5bcdff42009-05-14 21:27:18 -07001264 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001265 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001266 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268
1269 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1270 Log.v("ViewRoot", "Draw " + mView + "/"
1271 + mWindowAttributes.getTitle()
1272 + ": dirty={" + dirty.left + "," + dirty.top
1273 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001274 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1275 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277
1278 Canvas canvas;
1279 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001280 int left = dirty.left;
1281 int top = dirty.top;
1282 int right = dirty.right;
1283 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001285
1286 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1287 bottom != dirty.bottom) {
1288 mAttachInfo.mIgnoreDirtyState = true;
1289 }
1290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 // TODO: Do this in native
Dianne Hackborn11ea3342009-07-22 21:48:55 -07001292 canvas.setDensity(mDensity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 } catch (Surface.OutOfResourcesException e) {
1294 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1295 // TODO: we should ask the window manager to do something!
1296 // for now we just do nothing
1297 return;
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001298 } catch (IllegalArgumentException e) {
1299 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1300 // TODO: we should ask the window manager to do something!
1301 // for now we just do nothing
1302 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304
1305 try {
Romain Guybb93d552009-03-24 21:04:15 -07001306 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001307 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308
1309 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1310 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1311 + canvas.getWidth() + ", h=" + canvas.getHeight());
1312 //canvas.drawARGB(255, 255, 0, 0);
1313 }
1314
Romain Guy13922e02009-05-12 17:56:14 -07001315 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 startTime = SystemClock.elapsedRealtime();
1317 }
1318
1319 // If this bitmap's format includes an alpha channel, we
1320 // need to clear it before drawing so that the child will
1321 // properly re-composite its drawing on a transparent
1322 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001323 // or
1324 // If we are applying an offset, we need to clear the area
1325 // where the offset doesn't appear to avoid having garbage
1326 // left in the blank areas.
1327 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1329 }
1330
1331 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001332 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001334 mView.mPrivateFlags |= View.DRAWN;
1335
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001336 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001337 Context cxt = mView.getContext();
1338 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -07001339 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1340 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001341 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001342 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001343 try {
1344 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001345 if (mTranslator != null) {
1346 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001347 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001348 canvas.setScreenDensity(scalingRequired
1349 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001350 mView.draw(canvas);
1351 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001352 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001353 canvas.restoreToCount(saveCount);
1354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355
Romain Guy5bcdff42009-05-14 21:27:18 -07001356 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1357 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1358 }
1359
Mike Reedfd716532009-10-12 14:42:56 -04001360 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 int now = (int)SystemClock.elapsedRealtime();
1362 if (sDrawTime != 0) {
1363 nativeShowFPS(canvas, now - sDrawTime);
1364 }
1365 sDrawTime = now;
1366 }
1367
Romain Guy13922e02009-05-12 17:56:14 -07001368 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1370 }
1371 }
Romain Guy8506ab42009-06-11 17:35:47 -07001372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 } finally {
1374 surface.unlockCanvasAndPost(canvas);
1375 }
1376
1377 if (LOCAL_LOGV) {
1378 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1379 }
Romain Guy8506ab42009-06-11 17:35:47 -07001380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 if (scrolling) {
1382 mFullRedrawNeeded = true;
1383 scheduleTraversals();
1384 }
1385 }
1386
1387 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1388 final View.AttachInfo attachInfo = mAttachInfo;
1389 final Rect ci = attachInfo.mContentInsets;
1390 final Rect vi = attachInfo.mVisibleInsets;
1391 int scrollY = 0;
1392 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 if (vi.left > ci.left || vi.top > ci.top
1395 || vi.right > ci.right || vi.bottom > ci.bottom) {
1396 // We'll assume that we aren't going to change the scroll
1397 // offset, since we want to avoid that unless it is actually
1398 // going to make the focus visible... otherwise we scroll
1399 // all over the place.
1400 scrollY = mScrollY;
1401 // We can be called for two different situations: during a draw,
1402 // to update the scroll position if the focus has changed (in which
1403 // case 'rectangle' is null), or in response to a
1404 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1405 // is non-null and we just want to scroll to whatever that
1406 // rectangle is).
1407 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001408
1409 // When in touch mode, focus points to the previously focused view,
1410 // which may have been removed from the view hierarchy. The following
1411 // line checks whether the view is still in the hierarchy
1412 if (focus == null || focus.getParent() == null) {
1413 mRealFocusedView = null;
1414 return false;
1415 }
1416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 if (focus != mLastScrolledFocus) {
1418 // If the focus has changed, then ignore any requests to scroll
1419 // to a rectangle; first we want to make sure the entire focus
1420 // view is visible.
1421 rectangle = null;
1422 }
1423 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1424 + " rectangle=" + rectangle + " ci=" + ci
1425 + " vi=" + vi);
1426 if (focus == mLastScrolledFocus && !mScrollMayChange
1427 && rectangle == null) {
1428 // Optimization: if the focus hasn't changed since last
1429 // time, and no layout has happened, then just leave things
1430 // as they are.
1431 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1432 + mScrollY + " vi=" + vi.toShortString());
1433 } else if (focus != null) {
1434 // We need to determine if the currently focused view is
1435 // within the visible part of the window and, if not, apply
1436 // a pan so it can be seen.
1437 mLastScrolledFocus = focus;
1438 mScrollMayChange = false;
1439 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1440 // Try to find the rectangle from the focus view.
1441 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1442 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1443 + mView.getWidth() + " h=" + mView.getHeight()
1444 + " ci=" + ci.toShortString()
1445 + " vi=" + vi.toShortString());
1446 if (rectangle == null) {
1447 focus.getFocusedRect(mTempRect);
1448 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1449 + ": focusRect=" + mTempRect.toShortString());
1450 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1451 focus, mTempRect);
1452 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1453 "Focus in window: focusRect="
1454 + mTempRect.toShortString()
1455 + " visRect=" + mVisRect.toShortString());
1456 } else {
1457 mTempRect.set(rectangle);
1458 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1459 "Request scroll to rect: "
1460 + mTempRect.toShortString()
1461 + " visRect=" + mVisRect.toShortString());
1462 }
1463 if (mTempRect.intersect(mVisRect)) {
1464 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1465 "Focus window visible rect: "
1466 + mTempRect.toShortString());
1467 if (mTempRect.height() >
1468 (mView.getHeight()-vi.top-vi.bottom)) {
1469 // If the focus simply is not going to fit, then
1470 // best is probably just to leave things as-is.
1471 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1472 "Too tall; leaving scrollY=" + scrollY);
1473 } else if ((mTempRect.top-scrollY) < vi.top) {
1474 scrollY -= vi.top - (mTempRect.top-scrollY);
1475 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1476 "Top covered; scrollY=" + scrollY);
1477 } else if ((mTempRect.bottom-scrollY)
1478 > (mView.getHeight()-vi.bottom)) {
1479 scrollY += (mTempRect.bottom-scrollY)
1480 - (mView.getHeight()-vi.bottom);
1481 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1482 "Bottom covered; scrollY=" + scrollY);
1483 }
1484 handled = true;
1485 }
1486 }
1487 }
1488 }
Romain Guy8506ab42009-06-11 17:35:47 -07001489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 if (scrollY != mScrollY) {
1491 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1492 + mScrollY + " , new=" + scrollY);
1493 if (!immediate) {
1494 if (mScroller == null) {
1495 mScroller = new Scroller(mView.getContext());
1496 }
1497 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1498 } else if (mScroller != null) {
1499 mScroller.abortAnimation();
1500 }
1501 mScrollY = scrollY;
1502 }
Romain Guy8506ab42009-06-11 17:35:47 -07001503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 return handled;
1505 }
Romain Guy8506ab42009-06-11 17:35:47 -07001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 public void requestChildFocus(View child, View focused) {
1508 checkThread();
1509 if (mFocusedView != focused) {
1510 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1511 scheduleTraversals();
1512 }
1513 mFocusedView = mRealFocusedView = focused;
1514 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1515 + mFocusedView);
1516 }
1517
1518 public void clearChildFocus(View child) {
1519 checkThread();
1520
1521 View oldFocus = mFocusedView;
1522
1523 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1524 mFocusedView = mRealFocusedView = null;
1525 if (mView != null && !mView.hasFocus()) {
1526 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1527 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1528 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1529 }
1530 } else if (oldFocus != null) {
1531 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1532 }
1533 }
1534
1535
1536 public void focusableViewAvailable(View v) {
1537 checkThread();
1538
1539 if (mView != null && !mView.hasFocus()) {
1540 v.requestFocus();
1541 } else {
1542 // the one case where will transfer focus away from the current one
1543 // is if the current view is a view group that prefers to give focus
1544 // to its children first AND the view is a descendant of it.
1545 mFocusedView = mView.findFocus();
1546 boolean descendantsHaveDibsOnFocus =
1547 (mFocusedView instanceof ViewGroup) &&
1548 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1549 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1550 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1551 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1552 v.requestFocus();
1553 }
1554 }
1555 }
1556
1557 public void recomputeViewAttributes(View child) {
1558 checkThread();
1559 if (mView == child) {
1560 mAttachInfo.mRecomputeGlobalAttributes = true;
1561 if (!mWillDrawSoon) {
1562 scheduleTraversals();
1563 }
1564 }
1565 }
1566
1567 void dispatchDetachedFromWindow() {
1568 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1569
1570 if (mView != null) {
1571 mView.dispatchDetachedFromWindow();
1572 }
1573
1574 mView = null;
1575 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001576 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577
1578 if (mUseGL) {
1579 destroyGL();
1580 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001581 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582
1583 try {
1584 sWindowSession.remove(mWindow);
1585 } catch (RemoteException e) {
1586 }
1587 }
Romain Guy8506ab42009-06-11 17:35:47 -07001588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 /**
1590 * Return true if child is an ancestor of parent, (or equal to the parent).
1591 */
1592 private static boolean isViewDescendantOf(View child, View parent) {
1593 if (child == parent) {
1594 return true;
1595 }
1596
1597 final ViewParent theParent = child.getParent();
1598 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1599 }
1600
1601
1602 public final static int DO_TRAVERSAL = 1000;
1603 public final static int DIE = 1001;
1604 public final static int RESIZED = 1002;
1605 public final static int RESIZED_REPORT = 1003;
1606 public final static int WINDOW_FOCUS_CHANGED = 1004;
1607 public final static int DISPATCH_KEY = 1005;
1608 public final static int DISPATCH_POINTER = 1006;
1609 public final static int DISPATCH_TRACKBALL = 1007;
1610 public final static int DISPATCH_APP_VISIBILITY = 1008;
1611 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1612 public final static int FINISHED_EVENT = 1010;
1613 public final static int DISPATCH_KEY_FROM_IME = 1011;
1614 public final static int FINISH_INPUT_CONNECTION = 1012;
1615 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001616 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617
1618 @Override
1619 public void handleMessage(Message msg) {
1620 switch (msg.what) {
1621 case View.AttachInfo.INVALIDATE_MSG:
1622 ((View) msg.obj).invalidate();
1623 break;
1624 case View.AttachInfo.INVALIDATE_RECT_MSG:
1625 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1626 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1627 info.release();
1628 break;
1629 case DO_TRAVERSAL:
1630 if (mProfile) {
1631 Debug.startMethodTracing("ViewRoot");
1632 }
1633
1634 performTraversals();
1635
1636 if (mProfile) {
1637 Debug.stopMethodTracing();
1638 mProfile = false;
1639 }
1640 break;
1641 case FINISHED_EVENT:
1642 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1643 break;
1644 case DISPATCH_KEY:
1645 if (LOCAL_LOGV) Log.v(
1646 "ViewRoot", "Dispatching key "
1647 + msg.obj + " to " + mView);
1648 deliverKeyEvent((KeyEvent)msg.obj, true);
1649 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001650 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001652 boolean callWhenDone = msg.arg1 != 0;
1653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 if (event == null) {
1655 try {
Michael Chan53071d62009-05-13 17:29:48 -07001656 long timeBeforeGettingEvents;
1657 if (MEASURE_LATENCY) {
1658 timeBeforeGettingEvents = System.nanoTime();
1659 }
1660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001662
1663 if (MEASURE_LATENCY && event != null) {
1664 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1665 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 } catch (RemoteException e) {
1668 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001669 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001671 if (event != null && mTranslator != null) {
1672 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 try {
1675 boolean handled;
1676 if (mView != null && mAdded && event != null) {
1677
1678 // enter touch mode on the down
1679 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1680 if (isDown) {
1681 ensureTouchMode(true);
1682 }
1683 if(Config.LOGV) {
1684 captureMotionLog("captureDispatchPointer", event);
1685 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001686 if (mCurScrollY != 0) {
1687 event.offsetLocation(0, mCurScrollY);
1688 }
Michael Chan53071d62009-05-13 17:29:48 -07001689 if (MEASURE_LATENCY) {
1690 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001693 if (MEASURE_LATENCY) {
1694 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (!handled && isDown) {
1697 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1698
1699 final int edgeFlags = event.getEdgeFlags();
1700 int direction = View.FOCUS_UP;
1701 int x = (int)event.getX();
1702 int y = (int)event.getY();
1703 final int[] deltas = new int[2];
1704
1705 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1706 direction = View.FOCUS_DOWN;
1707 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1708 deltas[0] = edgeSlop;
1709 x += edgeSlop;
1710 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1711 deltas[0] = -edgeSlop;
1712 x -= edgeSlop;
1713 }
1714 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1715 direction = View.FOCUS_UP;
1716 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1717 deltas[0] = edgeSlop;
1718 x += edgeSlop;
1719 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1720 deltas[0] = -edgeSlop;
1721 x -= edgeSlop;
1722 }
1723 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1724 direction = View.FOCUS_RIGHT;
1725 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1726 direction = View.FOCUS_LEFT;
1727 }
1728
1729 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1730 View nearest = FocusFinder.getInstance().findNearestTouchable(
1731 ((ViewGroup) mView), x, y, direction, deltas);
1732 if (nearest != null) {
1733 event.offsetLocation(deltas[0], deltas[1]);
1734 event.setEdgeFlags(0);
1735 mView.dispatchTouchEvent(event);
1736 }
1737 }
1738 }
1739 }
1740 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001741 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 try {
1743 sWindowSession.finishKey(mWindow);
1744 } catch (RemoteException e) {
1745 }
1746 }
1747 if (event != null) {
1748 event.recycle();
1749 }
1750 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1751 // Let the exception fall through -- the looper will catch
1752 // it and take care of the bad app for us.
1753 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001754 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001756 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 break;
1758 case DISPATCH_APP_VISIBILITY:
1759 handleAppVisibility(msg.arg1 != 0);
1760 break;
1761 case DISPATCH_GET_NEW_SURFACE:
1762 handleGetNewSurface();
1763 break;
1764 case RESIZED:
1765 Rect coveredInsets = ((Rect[])msg.obj)[0];
1766 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1769 && mPendingContentInsets.equals(coveredInsets)
1770 && mPendingVisibleInsets.equals(visibleInsets)) {
1771 break;
1772 }
1773 // fall through...
1774 case RESIZED_REPORT:
1775 if (mAdded) {
1776 mWinFrame.left = 0;
1777 mWinFrame.right = msg.arg1;
1778 mWinFrame.top = 0;
1779 mWinFrame.bottom = msg.arg2;
1780 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1781 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1782 if (msg.what == RESIZED_REPORT) {
1783 mReportNextDraw = true;
1784 }
1785 requestLayout();
1786 }
1787 break;
1788 case WINDOW_FOCUS_CHANGED: {
1789 if (mAdded) {
1790 boolean hasWindowFocus = msg.arg1 != 0;
1791 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1792 if (hasWindowFocus) {
1793 boolean inTouchMode = msg.arg2 != 0;
1794 ensureTouchModeLocally(inTouchMode);
1795
1796 if (mGlWanted) {
1797 checkEglErrors();
1798 // we lost the gl context, so recreate it.
1799 if (mGlWanted && !mUseGL) {
1800 initializeGL();
1801 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001802 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001803 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001804 (int) (mWidth * appScale + 0.5f),
1805 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
1807 }
1808 }
1809 }
Romain Guy8506ab42009-06-11 17:35:47 -07001810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 mLastWasImTarget = WindowManager.LayoutParams
1812 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 InputMethodManager imm = InputMethodManager.peekInstance();
1815 if (mView != null) {
1816 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1817 imm.startGettingWindowFocus(mView);
1818 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001819 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 mView.dispatchWindowFocusChanged(hasWindowFocus);
1821 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 // Note: must be done after the focus change callbacks,
1824 // so all of the view state is set up correctly.
1825 if (hasWindowFocus) {
1826 if (imm != null && mLastWasImTarget) {
1827 imm.onWindowFocus(mView, mView.findFocus(),
1828 mWindowAttributes.softInputMode,
1829 !mHasHadWindowFocus, mWindowAttributes.flags);
1830 }
1831 // Clear the forward bit. We can just do this directly, since
1832 // the window manager doesn't care about it.
1833 mWindowAttributes.softInputMode &=
1834 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1835 ((WindowManager.LayoutParams)mView.getLayoutParams())
1836 .softInputMode &=
1837 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1838 mHasHadWindowFocus = true;
1839 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001840
1841 if (hasWindowFocus && mView != null) {
1842 sendAccessibilityEvents();
1843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
1845 } break;
1846 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001847 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001849 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 if (LOCAL_LOGV) Log.v(
1851 "ViewRoot", "Dispatching key "
1852 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001853 KeyEvent event = (KeyEvent)msg.obj;
1854 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1855 // The IME is trying to say this event is from the
1856 // system! Bad bad bad!
1857 event = KeyEvent.changeFlags(event,
1858 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001861 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 case FINISH_INPUT_CONNECTION: {
1863 InputMethodManager imm = InputMethodManager.peekInstance();
1864 if (imm != null) {
1865 imm.reportFinishInputConnection((InputConnection)msg.obj);
1866 }
1867 } break;
1868 case CHECK_FOCUS: {
1869 InputMethodManager imm = InputMethodManager.peekInstance();
1870 if (imm != null) {
1871 imm.checkFocus();
1872 }
1873 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001874 case CLOSE_SYSTEM_DIALOGS: {
1875 if (mView != null) {
1876 mView.onCloseSystemDialogs((String)msg.obj);
1877 }
1878 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 }
1880 }
1881
1882 /**
1883 * Something in the current window tells us we need to change the touch mode. For
1884 * example, we are not in touch mode, and the user touches the screen.
1885 *
1886 * If the touch mode has changed, tell the window manager, and handle it locally.
1887 *
1888 * @param inTouchMode Whether we want to be in touch mode.
1889 * @return True if the touch mode changed and focus changed was changed as a result
1890 */
1891 boolean ensureTouchMode(boolean inTouchMode) {
1892 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1893 + "touch mode is " + mAttachInfo.mInTouchMode);
1894 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1895
1896 // tell the window manager
1897 try {
1898 sWindowSession.setInTouchMode(inTouchMode);
1899 } catch (RemoteException e) {
1900 throw new RuntimeException(e);
1901 }
1902
1903 // handle the change
1904 return ensureTouchModeLocally(inTouchMode);
1905 }
1906
1907 /**
1908 * Ensure that the touch mode for this window is set, and if it is changing,
1909 * take the appropriate action.
1910 * @param inTouchMode Whether we want to be in touch mode.
1911 * @return True if the touch mode changed and focus changed was changed as a result
1912 */
1913 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1914 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1915 + "touch mode is " + mAttachInfo.mInTouchMode);
1916
1917 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1918
1919 mAttachInfo.mInTouchMode = inTouchMode;
1920 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1921
1922 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1923 }
1924
1925 private boolean enterTouchMode() {
1926 if (mView != null) {
1927 if (mView.hasFocus()) {
1928 // note: not relying on mFocusedView here because this could
1929 // be when the window is first being added, and mFocused isn't
1930 // set yet.
1931 final View focused = mView.findFocus();
1932 if (focused != null && !focused.isFocusableInTouchMode()) {
1933
1934 final ViewGroup ancestorToTakeFocus =
1935 findAncestorToTakeFocusInTouchMode(focused);
1936 if (ancestorToTakeFocus != null) {
1937 // there is an ancestor that wants focus after its descendants that
1938 // is focusable in touch mode.. give it focus
1939 return ancestorToTakeFocus.requestFocus();
1940 } else {
1941 // nothing appropriate to have focus in touch mode, clear it out
1942 mView.unFocus();
1943 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1944 mFocusedView = null;
1945 return true;
1946 }
1947 }
1948 }
1949 }
1950 return false;
1951 }
1952
1953
1954 /**
1955 * Find an ancestor of focused that wants focus after its descendants and is
1956 * focusable in touch mode.
1957 * @param focused The currently focused view.
1958 * @return An appropriate view, or null if no such view exists.
1959 */
1960 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1961 ViewParent parent = focused.getParent();
1962 while (parent instanceof ViewGroup) {
1963 final ViewGroup vgParent = (ViewGroup) parent;
1964 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1965 && vgParent.isFocusableInTouchMode()) {
1966 return vgParent;
1967 }
1968 if (vgParent.isRootNamespace()) {
1969 return null;
1970 } else {
1971 parent = vgParent.getParent();
1972 }
1973 }
1974 return null;
1975 }
1976
1977 private boolean leaveTouchMode() {
1978 if (mView != null) {
1979 if (mView.hasFocus()) {
1980 // i learned the hard way to not trust mFocusedView :)
1981 mFocusedView = mView.findFocus();
1982 if (!(mFocusedView instanceof ViewGroup)) {
1983 // some view has focus, let it keep it
1984 return false;
1985 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1986 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1987 // some view group has focus, and doesn't prefer its children
1988 // over itself for focus, so let them keep it.
1989 return false;
1990 }
1991 }
1992
1993 // find the best view to give focus to in this brave new non-touch-mode
1994 // world
1995 final View focused = focusSearch(null, View.FOCUS_DOWN);
1996 if (focused != null) {
1997 return focused.requestFocus(View.FOCUS_DOWN);
1998 }
1999 }
2000 return false;
2001 }
2002
2003
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002004 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 if (event == null) {
2006 try {
2007 event = sWindowSession.getPendingTrackballMove(mWindow);
2008 } catch (RemoteException e) {
2009 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002010 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 }
2012
2013 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2014
2015 boolean handled = false;
2016 try {
2017 if (event == null) {
2018 handled = true;
2019 } else if (mView != null && mAdded) {
2020 handled = mView.dispatchTrackballEvent(event);
2021 if (!handled) {
2022 // we could do something here, like changing the focus
2023 // or something?
2024 }
2025 }
2026 } finally {
2027 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002028 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 try {
2030 sWindowSession.finishKey(mWindow);
2031 } catch (RemoteException e) {
2032 }
2033 }
2034 if (event != null) {
2035 event.recycle();
2036 }
2037 // If we reach this, we delivered a trackball event to mView and
2038 // mView consumed it. Because we will not translate the trackball
2039 // event into a key event, touch mode will not exit, so we exit
2040 // touch mode here.
2041 ensureTouchMode(false);
2042 //noinspection ReturnInsideFinallyBlock
2043 return;
2044 }
2045 // Let the exception fall through -- the looper will catch
2046 // it and take care of the bad app for us.
2047 }
2048
2049 final TrackballAxis x = mTrackballAxisX;
2050 final TrackballAxis y = mTrackballAxisY;
2051
2052 long curTime = SystemClock.uptimeMillis();
2053 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2054 // It has been too long since the last movement,
2055 // so restart at the beginning.
2056 x.reset(0);
2057 y.reset(0);
2058 mLastTrackballTime = curTime;
2059 }
2060
2061 try {
2062 final int action = event.getAction();
2063 final int metastate = event.getMetaState();
2064 switch (action) {
2065 case MotionEvent.ACTION_DOWN:
2066 x.reset(2);
2067 y.reset(2);
2068 deliverKeyEvent(new KeyEvent(curTime, curTime,
2069 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2070 0, metastate), false);
2071 break;
2072 case MotionEvent.ACTION_UP:
2073 x.reset(2);
2074 y.reset(2);
2075 deliverKeyEvent(new KeyEvent(curTime, curTime,
2076 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2077 0, metastate), false);
2078 break;
2079 }
2080
2081 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2082 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2083 + " move=" + event.getX()
2084 + " / Y=" + y.position + " step="
2085 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2086 + " move=" + event.getY());
2087 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2088 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2089
2090 // Generate DPAD events based on the trackball movement.
2091 // We pick the axis that has moved the most as the direction of
2092 // the DPAD. When we generate DPAD events for one axis, then the
2093 // other axis is reset -- we don't want to perform DPAD jumps due
2094 // to slight movements in the trackball when making major movements
2095 // along the other axis.
2096 int keycode = 0;
2097 int movement = 0;
2098 float accel = 1;
2099 if (xOff > yOff) {
2100 movement = x.generate((2/event.getXPrecision()));
2101 if (movement != 0) {
2102 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2103 : KeyEvent.KEYCODE_DPAD_LEFT;
2104 accel = x.acceleration;
2105 y.reset(2);
2106 }
2107 } else if (yOff > 0) {
2108 movement = y.generate((2/event.getYPrecision()));
2109 if (movement != 0) {
2110 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2111 : KeyEvent.KEYCODE_DPAD_UP;
2112 accel = y.acceleration;
2113 x.reset(2);
2114 }
2115 }
2116
2117 if (keycode != 0) {
2118 if (movement < 0) movement = -movement;
2119 int accelMovement = (int)(movement * accel);
2120 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2121 + " accelMovement=" + accelMovement
2122 + " accel=" + accel);
2123 if (accelMovement > movement) {
2124 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2125 + keycode);
2126 movement--;
2127 deliverKeyEvent(new KeyEvent(curTime, curTime,
2128 KeyEvent.ACTION_MULTIPLE, keycode,
2129 accelMovement-movement, metastate), false);
2130 }
2131 while (movement > 0) {
2132 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2133 + keycode);
2134 movement--;
2135 curTime = SystemClock.uptimeMillis();
2136 deliverKeyEvent(new KeyEvent(curTime, curTime,
2137 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2138 deliverKeyEvent(new KeyEvent(curTime, curTime,
2139 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2140 }
2141 mLastTrackballTime = curTime;
2142 }
2143 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002144 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 try {
2146 sWindowSession.finishKey(mWindow);
2147 } catch (RemoteException e) {
2148 }
2149 if (event != null) {
2150 event.recycle();
2151 }
2152 }
2153 // Let the exception fall through -- the looper will catch
2154 // it and take care of the bad app for us.
2155 }
2156 }
2157
2158 /**
2159 * @param keyCode The key code
2160 * @return True if the key is directional.
2161 */
2162 static boolean isDirectional(int keyCode) {
2163 switch (keyCode) {
2164 case KeyEvent.KEYCODE_DPAD_LEFT:
2165 case KeyEvent.KEYCODE_DPAD_RIGHT:
2166 case KeyEvent.KEYCODE_DPAD_UP:
2167 case KeyEvent.KEYCODE_DPAD_DOWN:
2168 return true;
2169 }
2170 return false;
2171 }
2172
2173 /**
2174 * Returns true if this key is a keyboard key.
2175 * @param keyEvent The key event.
2176 * @return whether this key is a keyboard key.
2177 */
2178 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2179 final int convertedKey = keyEvent.getUnicodeChar();
2180 return convertedKey > 0;
2181 }
2182
2183
2184
2185 /**
2186 * See if the key event means we should leave touch mode (and leave touch
2187 * mode if so).
2188 * @param event The key event.
2189 * @return Whether this key event should be consumed (meaning the act of
2190 * leaving touch mode alone is considered the event).
2191 */
2192 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2193 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2194 return false;
2195 }
2196 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2197 return false;
2198 }
2199
2200 // only relevant if we are in touch mode
2201 if (!mAttachInfo.mInTouchMode) {
2202 return false;
2203 }
2204
2205 // if something like an edit text has focus and the user is typing,
2206 // leave touch mode
2207 //
2208 // note: the condition of not being a keyboard key is kind of a hacky
2209 // approximation of whether we think the focused view will want the
2210 // key; if we knew for sure whether the focused view would consume
2211 // the event, that would be better.
2212 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2213 mFocusedView = mView.findFocus();
2214 if ((mFocusedView instanceof ViewGroup)
2215 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2216 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2217 // something has focus, but is holding it weakly as a container
2218 return false;
2219 }
2220 if (ensureTouchMode(false)) {
2221 throw new IllegalStateException("should not have changed focus "
2222 + "when leaving touch mode while a view has focus.");
2223 }
2224 return false;
2225 }
2226
2227 if (isDirectional(event.getKeyCode())) {
2228 // no view has focus, so we leave touch mode (and find something
2229 // to give focus to). the event is consumed if we were able to
2230 // find something to give focus to.
2231 return ensureTouchMode(false);
2232 }
2233 return false;
2234 }
2235
2236 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002237 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 */
2239 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002240 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 if (ev == null ||
2242 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2243 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
Romain Guy8506ab42009-06-11 17:35:47 -07002245
2246 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 sb.append(ev.getDownTime()).append(',');
2248 sb.append(ev.getEventTime()).append(',');
2249 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002250 sb.append(ev.getX()).append(',');
2251 sb.append(ev.getY()).append(',');
2252 sb.append(ev.getPressure()).append(',');
2253 sb.append(ev.getSize()).append(',');
2254 sb.append(ev.getMetaState()).append(',');
2255 sb.append(ev.getXPrecision()).append(',');
2256 sb.append(ev.getYPrecision()).append(',');
2257 sb.append(ev.getDeviceId()).append(',');
2258 sb.append(ev.getEdgeFlags());
2259 Log.d(TAG, sb.toString());
2260 }
2261 /**
2262 * log motion events
2263 */
2264 private static void captureKeyLog(String subTag, KeyEvent ev) {
2265 //check dynamic switch
2266 if (ev == null ||
2267 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2268 return;
2269 }
2270 StringBuilder sb = new StringBuilder(subTag + ": ");
2271 sb.append(ev.getDownTime()).append(',');
2272 sb.append(ev.getEventTime()).append(',');
2273 sb.append(ev.getAction()).append(',');
2274 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 sb.append(ev.getRepeatCount()).append(',');
2276 sb.append(ev.getMetaState()).append(',');
2277 sb.append(ev.getDeviceId()).append(',');
2278 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002279 Log.d(TAG, sb.toString());
2280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281
2282 int enqueuePendingEvent(Object event, boolean sendDone) {
2283 int seq = mPendingEventSeq+1;
2284 if (seq < 0) seq = 0;
2285 mPendingEventSeq = seq;
2286 mPendingEvents.put(seq, event);
2287 return sendDone ? seq : -seq;
2288 }
2289
2290 Object retrievePendingEvent(int seq) {
2291 if (seq < 0) seq = -seq;
2292 Object event = mPendingEvents.get(seq);
2293 if (event != null) {
2294 mPendingEvents.remove(seq);
2295 }
2296 return event;
2297 }
Romain Guy8506ab42009-06-11 17:35:47 -07002298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2300 // If mView is null, we just consume the key event because it doesn't
2301 // make sense to do anything else with it.
2302 boolean handled = mView != null
2303 ? mView.dispatchKeyEventPreIme(event) : true;
2304 if (handled) {
2305 if (sendDone) {
2306 if (LOCAL_LOGV) Log.v(
2307 "ViewRoot", "Telling window manager key is finished");
2308 try {
2309 sWindowSession.finishKey(mWindow);
2310 } catch (RemoteException e) {
2311 }
2312 }
2313 return;
2314 }
2315 // If it is possible for this window to interact with the input
2316 // method window, then we want to first dispatch our key events
2317 // to the input method.
2318 if (mLastWasImTarget) {
2319 InputMethodManager imm = InputMethodManager.peekInstance();
2320 if (imm != null && mView != null) {
2321 int seq = enqueuePendingEvent(event, sendDone);
2322 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2323 + seq + " event=" + event);
2324 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2325 mInputMethodCallback);
2326 return;
2327 }
2328 }
2329 deliverKeyEventToViewHierarchy(event, sendDone);
2330 }
2331
2332 void handleFinishedEvent(int seq, boolean handled) {
2333 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2334 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2335 + " handled=" + handled + " event=" + event);
2336 if (event != null) {
2337 final boolean sendDone = seq >= 0;
2338 if (!handled) {
2339 deliverKeyEventToViewHierarchy(event, sendDone);
2340 return;
2341 } else if (sendDone) {
2342 if (LOCAL_LOGV) Log.v(
2343 "ViewRoot", "Telling window manager key is finished");
2344 try {
2345 sWindowSession.finishKey(mWindow);
2346 } catch (RemoteException e) {
2347 }
2348 } else {
2349 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2350 + " handled=" + handled + " ev=" + event
2351 + ") neither delivering nor finishing key");
2352 }
2353 }
2354 }
Romain Guy8506ab42009-06-11 17:35:47 -07002355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2357 try {
2358 if (mView != null && mAdded) {
2359 final int action = event.getAction();
2360 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2361
2362 if (checkForLeavingTouchModeAndConsume(event)) {
2363 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002364 }
2365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 if (Config.LOGV) {
2367 captureKeyLog("captureDispatchKeyEvent", event);
2368 }
2369 boolean keyHandled = mView.dispatchKeyEvent(event);
2370
2371 if (!keyHandled && isDown) {
2372 int direction = 0;
2373 switch (event.getKeyCode()) {
2374 case KeyEvent.KEYCODE_DPAD_LEFT:
2375 direction = View.FOCUS_LEFT;
2376 break;
2377 case KeyEvent.KEYCODE_DPAD_RIGHT:
2378 direction = View.FOCUS_RIGHT;
2379 break;
2380 case KeyEvent.KEYCODE_DPAD_UP:
2381 direction = View.FOCUS_UP;
2382 break;
2383 case KeyEvent.KEYCODE_DPAD_DOWN:
2384 direction = View.FOCUS_DOWN;
2385 break;
2386 }
2387
2388 if (direction != 0) {
2389
2390 View focused = mView != null ? mView.findFocus() : null;
2391 if (focused != null) {
2392 View v = focused.focusSearch(direction);
2393 boolean focusPassed = false;
2394 if (v != null && v != focused) {
2395 // do the math the get the interesting rect
2396 // of previous focused into the coord system of
2397 // newly focused view
2398 focused.getFocusedRect(mTempRect);
2399 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2400 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2401 focusPassed = v.requestFocus(direction, mTempRect);
2402 }
2403
2404 if (!focusPassed) {
2405 mView.dispatchUnhandledMove(focused, direction);
2406 } else {
2407 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2408 }
2409 }
2410 }
2411 }
2412 }
2413
2414 } finally {
2415 if (sendDone) {
2416 if (LOCAL_LOGV) Log.v(
2417 "ViewRoot", "Telling window manager key is finished");
2418 try {
2419 sWindowSession.finishKey(mWindow);
2420 } catch (RemoteException e) {
2421 }
2422 }
2423 // Let the exception fall through -- the looper will catch
2424 // it and take care of the bad app for us.
2425 }
2426 }
2427
2428 private AudioManager getAudioManager() {
2429 if (mView == null) {
2430 throw new IllegalStateException("getAudioManager called when there is no mView");
2431 }
2432 if (mAudioManager == null) {
2433 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2434 }
2435 return mAudioManager;
2436 }
2437
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002438 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2439 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002440
2441 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002442 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002443 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002444 restore = true;
2445 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002446 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002447 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002448 if (params != null) {
2449 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002450 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002451 int relayoutResult = sWindowSession.relayout(
2452 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002453 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2454 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002455 viewVisibility, insetsPending, mWinFrame,
2456 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002457 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002458 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002459 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002460
2461 if (mTranslator != null) {
2462 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2463 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2464 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002465 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002466 return relayoutResult;
2467 }
Romain Guy8506ab42009-06-11 17:35:47 -07002468
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002469 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 * {@inheritDoc}
2471 */
2472 public void playSoundEffect(int effectId) {
2473 checkThread();
2474
2475 final AudioManager audioManager = getAudioManager();
2476
2477 switch (effectId) {
2478 case SoundEffectConstants.CLICK:
2479 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2480 return;
2481 case SoundEffectConstants.NAVIGATION_DOWN:
2482 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2483 return;
2484 case SoundEffectConstants.NAVIGATION_LEFT:
2485 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2486 return;
2487 case SoundEffectConstants.NAVIGATION_RIGHT:
2488 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2489 return;
2490 case SoundEffectConstants.NAVIGATION_UP:
2491 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2492 return;
2493 default:
2494 throw new IllegalArgumentException("unknown effect id " + effectId +
2495 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2496 }
2497 }
2498
2499 /**
2500 * {@inheritDoc}
2501 */
2502 public boolean performHapticFeedback(int effectId, boolean always) {
2503 try {
2504 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2505 } catch (RemoteException e) {
2506 return false;
2507 }
2508 }
2509
2510 /**
2511 * {@inheritDoc}
2512 */
2513 public View focusSearch(View focused, int direction) {
2514 checkThread();
2515 if (!(mView instanceof ViewGroup)) {
2516 return null;
2517 }
2518 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2519 }
2520
2521 public void debug() {
2522 mView.debug();
2523 }
2524
2525 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002526 if (immediate) {
2527 doDie();
2528 } else {
2529 sendEmptyMessage(DIE);
2530 }
2531 }
2532
2533 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 checkThread();
2535 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2536 synchronized (this) {
2537 if (mAdded && !mFirst) {
2538 int viewVisibility = mView.getVisibility();
2539 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2540 if (mWindowAttributesChanged || viewVisibilityChanged) {
2541 // If layout params have been changed, first give them
2542 // to the window manager to make sure it has the correct
2543 // animation info.
2544 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002545 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2546 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 sWindowSession.finishDrawing(mWindow);
2548 }
2549 } catch (RemoteException e) {
2550 }
2551 }
2552
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002553 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
2555 if (mAdded) {
2556 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002557 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 }
2559 }
2560 }
2561
2562 public void dispatchFinishedEvent(int seq, boolean handled) {
2563 Message msg = obtainMessage(FINISHED_EVENT);
2564 msg.arg1 = seq;
2565 msg.arg2 = handled ? 1 : 0;
2566 sendMessage(msg);
2567 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 public void dispatchResized(int w, int h, Rect coveredInsets,
2570 Rect visibleInsets, boolean reportDraw) {
2571 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2572 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2573 + " visibleInsets=" + visibleInsets.toShortString()
2574 + " reportDraw=" + reportDraw);
2575 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002576 if (mTranslator != null) {
2577 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2578 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2579 w *= mTranslator.applicationInvertedScale;
2580 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002581 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002582 msg.arg1 = w;
2583 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2585 sendMessage(msg);
2586 }
2587
2588 public void dispatchKey(KeyEvent event) {
2589 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2590 //noinspection ConstantConditions
2591 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2592 if (Config.LOGD) Log.d("keydisp",
2593 "===================================================");
2594 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2595 debug();
2596
2597 if (Config.LOGD) Log.d("keydisp",
2598 "===================================================");
2599 }
2600 }
2601
2602 Message msg = obtainMessage(DISPATCH_KEY);
2603 msg.obj = event;
2604
2605 if (LOCAL_LOGV) Log.v(
2606 "ViewRoot", "sending key " + event + " to " + mView);
2607
2608 sendMessageAtTime(msg, event.getEventTime());
2609 }
2610
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002611 public void dispatchPointer(MotionEvent event, long eventTime,
2612 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 Message msg = obtainMessage(DISPATCH_POINTER);
2614 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002615 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 sendMessageAtTime(msg, eventTime);
2617 }
2618
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002619 public void dispatchTrackball(MotionEvent event, long eventTime,
2620 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2622 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002623 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 sendMessageAtTime(msg, eventTime);
2625 }
2626
2627 public void dispatchAppVisibility(boolean visible) {
2628 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2629 msg.arg1 = visible ? 1 : 0;
2630 sendMessage(msg);
2631 }
2632
2633 public void dispatchGetNewSurface() {
2634 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2635 sendMessage(msg);
2636 }
2637
2638 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2639 Message msg = Message.obtain();
2640 msg.what = WINDOW_FOCUS_CHANGED;
2641 msg.arg1 = hasFocus ? 1 : 0;
2642 msg.arg2 = inTouchMode ? 1 : 0;
2643 sendMessage(msg);
2644 }
2645
Dianne Hackbornffa42482009-09-23 22:20:11 -07002646 public void dispatchCloseSystemDialogs(String reason) {
2647 Message msg = Message.obtain();
2648 msg.what = CLOSE_SYSTEM_DIALOGS;
2649 msg.obj = reason;
2650 sendMessage(msg);
2651 }
2652
svetoslavganov75986cf2009-05-14 22:28:01 -07002653 /**
2654 * The window is getting focus so if there is anything focused/selected
2655 * send an {@link AccessibilityEvent} to announce that.
2656 */
2657 private void sendAccessibilityEvents() {
2658 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2659 return;
2660 }
2661 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2662 View focusedView = mView.findFocus();
2663 if (focusedView != null && focusedView != mView) {
2664 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2665 }
2666 }
2667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 public boolean showContextMenuForChild(View originalView) {
2669 return false;
2670 }
2671
2672 public void createContextMenu(ContextMenu menu) {
2673 }
2674
2675 public void childDrawableStateChanged(View child) {
2676 }
2677
2678 protected Rect getWindowFrame() {
2679 return mWinFrame;
2680 }
2681
2682 void checkThread() {
2683 if (mThread != Thread.currentThread()) {
2684 throw new CalledFromWrongThreadException(
2685 "Only the original thread that created a view hierarchy can touch its views.");
2686 }
2687 }
2688
2689 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2690 // ViewRoot never intercepts touch event, so this can be a no-op
2691 }
2692
2693 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2694 boolean immediate) {
2695 return scrollToRectOrFocus(rectangle, immediate);
2696 }
Romain Guy8506ab42009-06-11 17:35:47 -07002697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 static class InputMethodCallback extends IInputMethodCallback.Stub {
2699 private WeakReference<ViewRoot> mViewRoot;
2700
2701 public InputMethodCallback(ViewRoot viewRoot) {
2702 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2703 }
Romain Guy8506ab42009-06-11 17:35:47 -07002704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 public void finishedEvent(int seq, boolean handled) {
2706 final ViewRoot viewRoot = mViewRoot.get();
2707 if (viewRoot != null) {
2708 viewRoot.dispatchFinishedEvent(seq, handled);
2709 }
2710 }
2711
2712 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2713 // Stub -- not for use in the client.
2714 }
2715 }
Romain Guy8506ab42009-06-11 17:35:47 -07002716
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002717 static class EventCompletion extends Handler {
2718 final IWindow mWindow;
2719 final KeyEvent mKeyEvent;
2720 final boolean mIsPointer;
2721 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002722
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002723 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2724 boolean isPointer, MotionEvent motion) {
2725 super(looper);
2726 mWindow = window;
2727 mKeyEvent = key;
2728 mIsPointer = isPointer;
2729 mMotionEvent = motion;
2730 sendEmptyMessage(0);
2731 }
Romain Guy8506ab42009-06-11 17:35:47 -07002732
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002733 @Override
2734 public void handleMessage(Message msg) {
2735 if (mKeyEvent != null) {
2736 try {
2737 sWindowSession.finishKey(mWindow);
2738 } catch (RemoteException e) {
2739 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002740 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002741 boolean didFinish;
2742 MotionEvent event = mMotionEvent;
2743 if (event == null) {
2744 try {
2745 event = sWindowSession.getPendingPointerMove(mWindow);
2746 } catch (RemoteException e) {
2747 }
2748 didFinish = true;
2749 } else {
2750 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2751 }
2752 if (!didFinish) {
2753 try {
2754 sWindowSession.finishKey(mWindow);
2755 } catch (RemoteException e) {
2756 }
2757 }
2758 } else {
2759 MotionEvent event = mMotionEvent;
2760 if (event == null) {
2761 try {
2762 event = sWindowSession.getPendingTrackballMove(mWindow);
2763 } catch (RemoteException e) {
2764 }
2765 } else {
2766 try {
2767 sWindowSession.finishKey(mWindow);
2768 } catch (RemoteException e) {
2769 }
2770 }
2771 }
2772 }
2773 }
Romain Guy8506ab42009-06-11 17:35:47 -07002774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002776 private final WeakReference<ViewRoot> mViewRoot;
2777 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002779 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002781 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 }
2783
2784 public void resized(int w, int h, Rect coveredInsets,
2785 Rect visibleInsets, boolean reportDraw) {
2786 final ViewRoot viewRoot = mViewRoot.get();
2787 if (viewRoot != null) {
2788 viewRoot.dispatchResized(w, h, coveredInsets,
2789 visibleInsets, reportDraw);
2790 }
2791 }
2792
2793 public void dispatchKey(KeyEvent event) {
2794 final ViewRoot viewRoot = mViewRoot.get();
2795 if (viewRoot != null) {
2796 viewRoot.dispatchKey(event);
2797 } else {
2798 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002799 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 }
2801 }
2802
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002803 public void dispatchPointer(MotionEvent event, long eventTime,
2804 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002806 if (viewRoot != null) {
2807 if (MEASURE_LATENCY) {
2808 // Note: eventTime is in milliseconds
2809 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2810 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002811 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002812 } else {
2813 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 }
2815 }
2816
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002817 public void dispatchTrackball(MotionEvent event, long eventTime,
2818 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 final ViewRoot viewRoot = mViewRoot.get();
2820 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002821 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002822 } else {
2823 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 }
2825 }
2826
2827 public void dispatchAppVisibility(boolean visible) {
2828 final ViewRoot viewRoot = mViewRoot.get();
2829 if (viewRoot != null) {
2830 viewRoot.dispatchAppVisibility(visible);
2831 }
2832 }
2833
2834 public void dispatchGetNewSurface() {
2835 final ViewRoot viewRoot = mViewRoot.get();
2836 if (viewRoot != null) {
2837 viewRoot.dispatchGetNewSurface();
2838 }
2839 }
2840
2841 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2842 final ViewRoot viewRoot = mViewRoot.get();
2843 if (viewRoot != null) {
2844 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2845 }
2846 }
2847
2848 private static int checkCallingPermission(String permission) {
2849 if (!Process.supportsProcesses()) {
2850 return PackageManager.PERMISSION_GRANTED;
2851 }
2852
2853 try {
2854 return ActivityManagerNative.getDefault().checkPermission(
2855 permission, Binder.getCallingPid(), Binder.getCallingUid());
2856 } catch (RemoteException e) {
2857 return PackageManager.PERMISSION_DENIED;
2858 }
2859 }
2860
2861 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2862 final ViewRoot viewRoot = mViewRoot.get();
2863 if (viewRoot != null) {
2864 final View view = viewRoot.mView;
2865 if (view != null) {
2866 if (checkCallingPermission(Manifest.permission.DUMP) !=
2867 PackageManager.PERMISSION_GRANTED) {
2868 throw new SecurityException("Insufficient permissions to invoke"
2869 + " executeCommand() from pid=" + Binder.getCallingPid()
2870 + ", uid=" + Binder.getCallingUid());
2871 }
2872
2873 OutputStream clientStream = null;
2874 try {
2875 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2876 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2877 } catch (IOException e) {
2878 e.printStackTrace();
2879 } finally {
2880 if (clientStream != null) {
2881 try {
2882 clientStream.close();
2883 } catch (IOException e) {
2884 e.printStackTrace();
2885 }
2886 }
2887 }
2888 }
2889 }
2890 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002891
Dianne Hackbornffa42482009-09-23 22:20:11 -07002892 public void closeSystemDialogs(String reason) {
2893 final ViewRoot viewRoot = mViewRoot.get();
2894 if (viewRoot != null) {
2895 viewRoot.dispatchCloseSystemDialogs(reason);
2896 }
2897 }
2898
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002899 public void dispatchWallpaperOffsets(float x, float y, boolean sync) {
2900 if (sync) {
2901 try {
2902 sWindowSession.wallpaperOffsetsComplete(asBinder());
2903 } catch (RemoteException e) {
2904 }
2905 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 }
2908
2909 /**
2910 * Maintains state information for a single trackball axis, generating
2911 * discrete (DPAD) movements based on raw trackball motion.
2912 */
2913 static final class TrackballAxis {
2914 /**
2915 * The maximum amount of acceleration we will apply.
2916 */
2917 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 /**
2920 * The maximum amount of time (in milliseconds) between events in order
2921 * for us to consider the user to be doing fast trackball movements,
2922 * and thus apply an acceleration.
2923 */
2924 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 /**
2927 * Scaling factor to the time (in milliseconds) between events to how
2928 * much to multiple/divide the current acceleration. When movement
2929 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2930 * FAST_MOVE_TIME it divides it.
2931 */
2932 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 float position;
2935 float absPosition;
2936 float acceleration = 1;
2937 long lastMoveTime = 0;
2938 int step;
2939 int dir;
2940 int nonAccelMovement;
2941
2942 void reset(int _step) {
2943 position = 0;
2944 acceleration = 1;
2945 lastMoveTime = 0;
2946 step = _step;
2947 dir = 0;
2948 }
2949
2950 /**
2951 * Add trackball movement into the state. If the direction of movement
2952 * has been reversed, the state is reset before adding the
2953 * movement (so that you don't have to compensate for any previously
2954 * collected movement before see the result of the movement in the
2955 * new direction).
2956 *
2957 * @return Returns the absolute value of the amount of movement
2958 * collected so far.
2959 */
2960 float collect(float off, long time, String axis) {
2961 long normTime;
2962 if (off > 0) {
2963 normTime = (long)(off * FAST_MOVE_TIME);
2964 if (dir < 0) {
2965 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2966 position = 0;
2967 step = 0;
2968 acceleration = 1;
2969 lastMoveTime = 0;
2970 }
2971 dir = 1;
2972 } else if (off < 0) {
2973 normTime = (long)((-off) * FAST_MOVE_TIME);
2974 if (dir > 0) {
2975 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2976 position = 0;
2977 step = 0;
2978 acceleration = 1;
2979 lastMoveTime = 0;
2980 }
2981 dir = -1;
2982 } else {
2983 normTime = 0;
2984 }
Romain Guy8506ab42009-06-11 17:35:47 -07002985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 // The number of milliseconds between each movement that is
2987 // considered "normal" and will not result in any acceleration
2988 // or deceleration, scaled by the offset we have here.
2989 if (normTime > 0) {
2990 long delta = time - lastMoveTime;
2991 lastMoveTime = time;
2992 float acc = acceleration;
2993 if (delta < normTime) {
2994 // The user is scrolling rapidly, so increase acceleration.
2995 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2996 if (scale > 1) acc *= scale;
2997 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2998 + off + " normTime=" + normTime + " delta=" + delta
2999 + " scale=" + scale + " acc=" + acc);
3000 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3001 } else {
3002 // The user is scrolling slowly, so decrease acceleration.
3003 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3004 if (scale > 1) acc /= scale;
3005 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3006 + off + " normTime=" + normTime + " delta=" + delta
3007 + " scale=" + scale + " acc=" + acc);
3008 acceleration = acc > 1 ? acc : 1;
3009 }
3010 }
3011 position += off;
3012 return (absPosition = Math.abs(position));
3013 }
3014
3015 /**
3016 * Generate the number of discrete movement events appropriate for
3017 * the currently collected trackball movement.
3018 *
3019 * @param precision The minimum movement required to generate the
3020 * first discrete movement.
3021 *
3022 * @return Returns the number of discrete movements, either positive
3023 * or negative, or 0 if there is not enough trackball movement yet
3024 * for a discrete movement.
3025 */
3026 int generate(float precision) {
3027 int movement = 0;
3028 nonAccelMovement = 0;
3029 do {
3030 final int dir = position >= 0 ? 1 : -1;
3031 switch (step) {
3032 // If we are going to execute the first step, then we want
3033 // to do this as soon as possible instead of waiting for
3034 // a full movement, in order to make things look responsive.
3035 case 0:
3036 if (absPosition < precision) {
3037 return movement;
3038 }
3039 movement += dir;
3040 nonAccelMovement += dir;
3041 step = 1;
3042 break;
3043 // If we have generated the first movement, then we need
3044 // to wait for the second complete trackball motion before
3045 // generating the second discrete movement.
3046 case 1:
3047 if (absPosition < 2) {
3048 return movement;
3049 }
3050 movement += dir;
3051 nonAccelMovement += dir;
3052 position += dir > 0 ? -2 : 2;
3053 absPosition = Math.abs(position);
3054 step = 2;
3055 break;
3056 // After the first two, we generate discrete movements
3057 // consistently with the trackball, applying an acceleration
3058 // if the trackball is moving quickly. This is a simple
3059 // acceleration on top of what we already compute based
3060 // on how quickly the wheel is being turned, to apply
3061 // a longer increasing acceleration to continuous movement
3062 // in one direction.
3063 default:
3064 if (absPosition < 1) {
3065 return movement;
3066 }
3067 movement += dir;
3068 position += dir >= 0 ? -1 : 1;
3069 absPosition = Math.abs(position);
3070 float acc = acceleration;
3071 acc *= 1.1f;
3072 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3073 break;
3074 }
3075 } while (true);
3076 }
3077 }
3078
3079 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3080 public CalledFromWrongThreadException(String msg) {
3081 super(msg);
3082 }
3083 }
3084
3085 private SurfaceHolder mHolder = new SurfaceHolder() {
3086 // we only need a SurfaceHolder for opengl. it would be nice
3087 // to implement everything else though, especially the callback
3088 // support (opengl doesn't make use of it right now, but eventually
3089 // will).
3090 public Surface getSurface() {
3091 return mSurface;
3092 }
3093
3094 public boolean isCreating() {
3095 return false;
3096 }
3097
3098 public void addCallback(Callback callback) {
3099 }
3100
3101 public void removeCallback(Callback callback) {
3102 }
3103
3104 public void setFixedSize(int width, int height) {
3105 }
3106
3107 public void setSizeFromLayout() {
3108 }
3109
3110 public void setFormat(int format) {
3111 }
3112
3113 public void setType(int type) {
3114 }
3115
3116 public void setKeepScreenOn(boolean screenOn) {
3117 }
3118
3119 public Canvas lockCanvas() {
3120 return null;
3121 }
3122
3123 public Canvas lockCanvas(Rect dirty) {
3124 return null;
3125 }
3126
3127 public void unlockCanvasAndPost(Canvas canvas) {
3128 }
3129 public Rect getSurfaceFrame() {
3130 return null;
3131 }
3132 };
3133
3134 static RunQueue getRunQueue() {
3135 RunQueue rq = sRunQueues.get();
3136 if (rq != null) {
3137 return rq;
3138 }
3139 rq = new RunQueue();
3140 sRunQueues.set(rq);
3141 return rq;
3142 }
Romain Guy8506ab42009-06-11 17:35:47 -07003143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 /**
3145 * @hide
3146 */
3147 static final class RunQueue {
3148 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3149
3150 void post(Runnable action) {
3151 postDelayed(action, 0);
3152 }
3153
3154 void postDelayed(Runnable action, long delayMillis) {
3155 HandlerAction handlerAction = new HandlerAction();
3156 handlerAction.action = action;
3157 handlerAction.delay = delayMillis;
3158
3159 synchronized (mActions) {
3160 mActions.add(handlerAction);
3161 }
3162 }
3163
3164 void removeCallbacks(Runnable action) {
3165 final HandlerAction handlerAction = new HandlerAction();
3166 handlerAction.action = action;
3167
3168 synchronized (mActions) {
3169 final ArrayList<HandlerAction> actions = mActions;
3170
3171 while (actions.remove(handlerAction)) {
3172 // Keep going
3173 }
3174 }
3175 }
3176
3177 void executeActions(Handler handler) {
3178 synchronized (mActions) {
3179 final ArrayList<HandlerAction> actions = mActions;
3180 final int count = actions.size();
3181
3182 for (int i = 0; i < count; i++) {
3183 final HandlerAction handlerAction = actions.get(i);
3184 handler.postDelayed(handlerAction.action, handlerAction.delay);
3185 }
3186
Romain Guy15df6702009-08-17 20:17:30 -07003187 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 }
3189 }
3190
3191 private static class HandlerAction {
3192 Runnable action;
3193 long delay;
3194
3195 @Override
3196 public boolean equals(Object o) {
3197 if (this == o) return true;
3198 if (o == null || getClass() != o.getClass()) return false;
3199
3200 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 return !(action != null ? !action.equals(that.action) : that.action != null);
3202
3203 }
3204
3205 @Override
3206 public int hashCode() {
3207 int result = action != null ? action.hashCode() : 0;
3208 result = 31 * result + (int) (delay ^ (delay >>> 32));
3209 return result;
3210 }
3211 }
3212 }
3213
3214 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3215
3216 // inform skia to just abandon its texture cache IDs
3217 // doesn't call glDeleteTextures
3218 private static native void nativeAbandonGlCaches();
3219}