blob: 07b2d1ccae1ec635b5ac1245f3ca9f6ef79ea298 [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
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800101 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
102 static boolean sFirstDrawComplete = false;
103
Romain Guy8506ab42009-06-11 17:35:47 -0700104 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 long mLastTrackballTime = 0;
107 final TrackballAxis mTrackballAxisX = new TrackballAxis();
108 final TrackballAxis mTrackballAxisY = new TrackballAxis();
109
110 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 final InputMethodCallback mInputMethodCallback;
113 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
114 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 final Thread mThread;
117
118 final WindowLeaked mLocation;
119
120 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
121
122 final W mWindow;
123
124 View mView;
125 View mFocusedView;
126 View mRealFocusedView; // this is not set to null in touch mode
127 int mViewVisibility;
128 boolean mAppVisible = true;
129
130 final Region mTransparentRegion;
131 final Region mPreviousTransparentRegion;
132
133 int mWidth;
134 int mHeight;
135 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700136 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700137
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700138 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
140 final View.AttachInfo mAttachInfo;
141
142 final Rect mTempRect; // used in the transaction to not thrash the heap.
143 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145 boolean mTraversalScheduled;
146 boolean mWillDrawSoon;
147 boolean mLayoutRequested;
148 boolean mFirst;
149 boolean mReportNextDraw;
150 boolean mFullRedrawNeeded;
151 boolean mNewSurfaceNeeded;
152 boolean mHasHadWindowFocus;
153 boolean mLastWasImTarget;
154
155 boolean mWindowAttributesChanged = false;
156
157 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700158 // Surface can never be reassigned or cleared (use Surface.clear()).
159 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161 boolean mAdded;
162 boolean mAddedTouchMode;
163
164 /*package*/ int mAddNesting;
165
166 // These are accessed by multiple threads.
167 final Rect mWinFrame; // frame given by window manager.
168
169 final Rect mPendingVisibleInsets = new Rect();
170 final Rect mPendingContentInsets = new Rect();
171 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
172 = new ViewTreeObserver.InternalInsetsInfo();
173
174 boolean mScrollMayChange;
175 int mSoftInputMode;
176 View mLastScrolledFocus;
177 int mScrollY;
178 int mCurScrollY;
179 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 EGL10 mEgl;
182 EGLDisplay mEglDisplay;
183 EGLContext mEglContext;
184 EGLSurface mEglSurface;
185 GL11 mGL;
186 Canvas mGlCanvas;
187 boolean mUseGL;
188 boolean mGlWanted;
189
Romain Guy8506ab42009-06-11 17:35:47 -0700190 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
192 /**
193 * see {@link #playSoundEffect(int)}
194 */
195 AudioManager mAudioManager;
196
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700197 private final int mDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700199 public static IWindowSession getWindowSession(Looper mainLooper) {
200 synchronized (mStaticInit) {
201 if (!mInitialized) {
202 try {
203 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
204 sWindowSession = IWindowManager.Stub.asInterface(
205 ServiceManager.getService("window"))
206 .openSession(imm.getClient(), imm.getInputContext());
207 mInitialized = true;
208 } catch (RemoteException e) {
209 }
210 }
211 return sWindowSession;
212 }
213 }
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 public ViewRoot(Context context) {
216 super();
217
Michael Chan53071d62009-05-13 17:29:48 -0700218 if (MEASURE_LATENCY && lt == null) {
219 lt = new LatencyTimer(100, 1000);
220 }
221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 ++sInstanceCount;
223
224 // Initialize the statics when this class is first instantiated. This is
225 // done here instead of in the static block because Zygote does not
226 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700227 getWindowSession(context.getMainLooper());
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 mThread = Thread.currentThread();
230 mLocation = new WindowLeaked(null);
231 mLocation.fillInStackTrace();
232 mWidth = -1;
233 mHeight = -1;
234 mDirty = new Rect();
235 mTempRect = new Rect();
236 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700238 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 mInputMethodCallback = new InputMethodCallback(this);
240 mViewVisibility = View.GONE;
241 mTransparentRegion = new Region();
242 mPreviousTransparentRegion = new Region();
243 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 mAdded = false;
245 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
246 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700247 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 }
249
250 @Override
251 protected void finalize() throws Throwable {
252 super.finalize();
253 --sInstanceCount;
254 }
255
256 public static long getInstanceCount() {
257 return sInstanceCount;
258 }
259
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800260 public static void addFirstDrawHandler(Runnable callback) {
261 synchronized (sFirstDrawHandlers) {
262 if (!sFirstDrawComplete) {
263 sFirstDrawHandlers.add(callback);
264 }
265 }
266 }
267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 // FIXME for perf testing only
269 private boolean mProfile = false;
270
271 /**
272 * Call this to profile the next traversal call.
273 * FIXME for perf testing only. Remove eventually
274 */
275 public void profile() {
276 mProfile = true;
277 }
278
279 /**
280 * Indicates whether we are in touch mode. Calling this method triggers an IPC
281 * call and should be avoided whenever possible.
282 *
283 * @return True, if the device is in touch mode, false otherwise.
284 *
285 * @hide
286 */
287 static boolean isInTouchMode() {
288 if (mInitialized) {
289 try {
290 return sWindowSession.getInTouchMode();
291 } catch (RemoteException e) {
292 }
293 }
294 return false;
295 }
296
297 private void initializeGL() {
298 initializeGLInner();
299 int err = mEgl.eglGetError();
300 if (err != EGL10.EGL_SUCCESS) {
301 // give-up on using GL
302 destroyGL();
303 mGlWanted = false;
304 }
305 }
306
307 private void initializeGLInner() {
308 final EGL10 egl = (EGL10) EGLContext.getEGL();
309 mEgl = egl;
310
311 /*
312 * Get to the default display.
313 */
314 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
315 mEglDisplay = eglDisplay;
316
317 /*
318 * We can now initialize EGL for that display
319 */
320 int[] version = new int[2];
321 egl.eglInitialize(eglDisplay, version);
322
323 /*
324 * Specify a configuration for our opengl session
325 * and grab the first configuration that matches is
326 */
327 final int[] configSpec = {
328 EGL10.EGL_RED_SIZE, 5,
329 EGL10.EGL_GREEN_SIZE, 6,
330 EGL10.EGL_BLUE_SIZE, 5,
331 EGL10.EGL_DEPTH_SIZE, 0,
332 EGL10.EGL_NONE
333 };
334 final EGLConfig[] configs = new EGLConfig[1];
335 final int[] num_config = new int[1];
336 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
337 final EGLConfig config = configs[0];
338
339 /*
340 * Create an OpenGL ES context. This must be done only once, an
341 * OpenGL context is a somewhat heavy object.
342 */
343 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
344 EGL10.EGL_NO_CONTEXT, null);
345 mEglContext = context;
346
347 /*
348 * Create an EGL surface we can render into.
349 */
350 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
351 mEglSurface = surface;
352
353 /*
354 * Before we can issue GL commands, we need to make sure
355 * the context is current and bound to a surface.
356 */
357 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
358
359 /*
360 * Get to the appropriate GL interface.
361 * This is simply done by casting the GL context to either
362 * GL10 or GL11.
363 */
364 final GL11 gl = (GL11) context.getGL();
365 mGL = gl;
366 mGlCanvas = new Canvas(gl);
367 mUseGL = true;
368 }
369
370 private void destroyGL() {
371 // inform skia that the context is gone
372 nativeAbandonGlCaches();
373
374 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
375 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
376 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
377 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
378 mEgl.eglTerminate(mEglDisplay);
379 mEglContext = null;
380 mEglSurface = null;
381 mEglDisplay = null;
382 mEgl = null;
383 mGlCanvas = null;
384 mGL = null;
385 mUseGL = false;
386 }
387
388 private void checkEglErrors() {
389 if (mUseGL) {
390 int err = mEgl.eglGetError();
391 if (err != EGL10.EGL_SUCCESS) {
392 // something bad has happened revert to
393 // normal rendering.
394 destroyGL();
395 if (err != EGL11.EGL_CONTEXT_LOST) {
396 // we'll try again if it was context lost
397 mGlWanted = false;
398 }
399 }
400 }
401 }
402
403 /**
404 * We have one child
405 */
406 public void setView(View view, WindowManager.LayoutParams attrs,
407 View panelParentView) {
408 synchronized (this) {
409 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700410 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700411 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700412 attrs = mWindowAttributes;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700413 Resources resources = mView.getContext().getResources();
414 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700415 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700416
417 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700418 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
419 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700420 }
421
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700422 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700423 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700424 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700425 attrs.backup();
426 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700427 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700428 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
429
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700430 if (!compatibilityInfo.supportsScreen()) {
431 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
432 }
433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 mSoftInputMode = attrs.softInputMode;
435 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700437 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700438 mAttachInfo.mApplicationScale =
439 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 if (panelParentView != null) {
441 mAttachInfo.mPanelParentWindowToken
442 = panelParentView.getApplicationWindowToken();
443 }
444 mAdded = true;
445 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 // Schedule the first layout -before- adding to the window
448 // manager, to make sure we do the relayout before receiving
449 // any other events from the system.
450 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700452 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 getHostVisibility(), mAttachInfo.mContentInsets);
454 } catch (RemoteException e) {
455 mAdded = false;
456 mView = null;
457 mAttachInfo.mRootView = null;
458 unscheduleTraversals();
459 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700460 } finally {
461 if (restore) {
462 attrs.restore();
463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700465
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700466 if (mTranslator != null) {
467 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 mPendingContentInsets.set(mAttachInfo.mContentInsets);
470 mPendingVisibleInsets.set(0, 0, 0, 0);
471 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
472 if (res < WindowManagerImpl.ADD_OKAY) {
473 mView = null;
474 mAttachInfo.mRootView = null;
475 mAdded = false;
476 unscheduleTraversals();
477 switch (res) {
478 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
479 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
480 throw new WindowManagerImpl.BadTokenException(
481 "Unable to add window -- token " + attrs.token
482 + " is not valid; is your activity running?");
483 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
484 throw new WindowManagerImpl.BadTokenException(
485 "Unable to add window -- token " + attrs.token
486 + " is not for an application");
487 case WindowManagerImpl.ADD_APP_EXITING:
488 throw new WindowManagerImpl.BadTokenException(
489 "Unable to add window -- app for token " + attrs.token
490 + " is exiting");
491 case WindowManagerImpl.ADD_DUPLICATE_ADD:
492 throw new WindowManagerImpl.BadTokenException(
493 "Unable to add window -- window " + mWindow
494 + " has already been added");
495 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
496 // Silently ignore -- we would have just removed it
497 // right away, anyway.
498 return;
499 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
500 throw new WindowManagerImpl.BadTokenException(
501 "Unable to add window " + mWindow +
502 " -- another window of this type already exists");
503 case WindowManagerImpl.ADD_PERMISSION_DENIED:
504 throw new WindowManagerImpl.BadTokenException(
505 "Unable to add window " + mWindow +
506 " -- permission denied for this window type");
507 }
508 throw new RuntimeException(
509 "Unable to add window -- unknown error code " + res);
510 }
511 view.assignParent(this);
512 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
513 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
514 }
515 }
516 }
517
518 public View getView() {
519 return mView;
520 }
521
522 final WindowLeaked getLocation() {
523 return mLocation;
524 }
525
526 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
527 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700528 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700529 // preserve compatible window flag if exists.
530 int compatibleWindowFlag =
531 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700533 mWindowAttributes.flags |= compatibleWindowFlag;
534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 if (newView) {
536 mSoftInputMode = attrs.softInputMode;
537 requestLayout();
538 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700539 // Don't lose the mode we last auto-computed.
540 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
541 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
542 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
543 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
544 | (oldSoftInputMode
545 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 mWindowAttributesChanged = true;
548 scheduleTraversals();
549 }
550 }
551
552 void handleAppVisibility(boolean visible) {
553 if (mAppVisible != visible) {
554 mAppVisible = visible;
555 scheduleTraversals();
556 }
557 }
558
559 void handleGetNewSurface() {
560 mNewSurfaceNeeded = true;
561 mFullRedrawNeeded = true;
562 scheduleTraversals();
563 }
564
565 /**
566 * {@inheritDoc}
567 */
568 public void requestLayout() {
569 checkThread();
570 mLayoutRequested = true;
571 scheduleTraversals();
572 }
573
574 /**
575 * {@inheritDoc}
576 */
577 public boolean isLayoutRequested() {
578 return mLayoutRequested;
579 }
580
581 public void invalidateChild(View child, Rect dirty) {
582 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700583 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
584 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700586 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700587 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700588 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700589 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700590 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700591 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700592 }
Romain Guy1e095972009-07-07 11:22:45 -0700593 if (mAttachInfo.mScalingRequired) {
594 dirty.inset(-1, -1);
595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597 mDirty.union(dirty);
598 if (!mWillDrawSoon) {
599 scheduleTraversals();
600 }
601 }
602
603 public ViewParent getParent() {
604 return null;
605 }
606
607 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
608 invalidateChild(null, dirty);
609 return null;
610 }
611
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700612 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 if (child != mView) {
614 throw new RuntimeException("child is not mine, honest!");
615 }
616 // Note: don't apply scroll offset, because we want to know its
617 // visibility in the virtual canvas being given to the view hierarchy.
618 return r.intersect(0, 0, mWidth, mHeight);
619 }
620
621 public void bringChildToFront(View child) {
622 }
623
624 public void scheduleTraversals() {
625 if (!mTraversalScheduled) {
626 mTraversalScheduled = true;
627 sendEmptyMessage(DO_TRAVERSAL);
628 }
629 }
630
631 public void unscheduleTraversals() {
632 if (mTraversalScheduled) {
633 mTraversalScheduled = false;
634 removeMessages(DO_TRAVERSAL);
635 }
636 }
637
638 int getHostVisibility() {
639 return mAppVisible ? mView.getVisibility() : View.GONE;
640 }
Romain Guy8506ab42009-06-11 17:35:47 -0700641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 private void performTraversals() {
643 // cache mView since it is used so much below...
644 final View host = mView;
645
646 if (DBG) {
647 System.out.println("======================================");
648 System.out.println("performTraversals");
649 host.debug();
650 }
651
652 if (host == null || !mAdded)
653 return;
654
655 mTraversalScheduled = false;
656 mWillDrawSoon = true;
657 boolean windowResizesToFitContent = false;
658 boolean fullRedrawNeeded = mFullRedrawNeeded;
659 boolean newSurface = false;
660 WindowManager.LayoutParams lp = mWindowAttributes;
661
662 int desiredWindowWidth;
663 int desiredWindowHeight;
664 int childWidthMeasureSpec;
665 int childHeightMeasureSpec;
666
667 final View.AttachInfo attachInfo = mAttachInfo;
668
669 final int viewVisibility = getHostVisibility();
670 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
671 || mNewSurfaceNeeded;
672
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700673 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 WindowManager.LayoutParams params = null;
676 if (mWindowAttributesChanged) {
677 mWindowAttributesChanged = false;
678 params = lp;
679 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700680 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 if (mFirst) {
682 fullRedrawNeeded = true;
683 mLayoutRequested = true;
684
Romain Guy8506ab42009-06-11 17:35:47 -0700685 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700686 mView.getContext().getResources().getDisplayMetrics();
687 desiredWindowWidth = packageMetrics.widthPixels;
688 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689
690 // For the very first time, tell the view hierarchy that it
691 // is attached to the window. Note that at this point the surface
692 // object is not initialized to its backing store, but soon it
693 // will be (assuming the window is visible).
694 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700695 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 attachInfo.mHasWindowFocus = false;
697 attachInfo.mWindowVisibility = viewVisibility;
698 attachInfo.mRecomputeGlobalAttributes = false;
699 attachInfo.mKeepScreenOn = false;
700 viewVisibilityChanged = false;
701 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700705 desiredWindowWidth = frame.width();
706 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
708 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700709 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 fullRedrawNeeded = true;
711 mLayoutRequested = true;
712 windowResizesToFitContent = true;
713 }
714 }
715
716 if (viewVisibilityChanged) {
717 attachInfo.mWindowVisibility = viewVisibility;
718 host.dispatchWindowVisibilityChanged(viewVisibility);
719 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
720 if (mUseGL) {
721 destroyGL();
722 }
723 }
724 if (viewVisibility == View.GONE) {
725 // After making a window gone, we will count it as being
726 // shown for the first time the next time it gets focus.
727 mHasHadWindowFocus = false;
728 }
729 }
730
731 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700734 // Execute enqueued actions on every layout in case a view that was detached
735 // enqueued an action after being detached
736 getRunQueue().executeActions(attachInfo.mHandler);
737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 if (mFirst) {
739 host.fitSystemWindows(mAttachInfo.mContentInsets);
740 // make sure touch mode code executes by setting cached value
741 // to opposite of the added touch mode.
742 mAttachInfo.mInTouchMode = !mAddedTouchMode;
743 ensureTouchModeLocally(mAddedTouchMode);
744 } else {
745 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
746 mAttachInfo.mContentInsets.set(mPendingContentInsets);
747 host.fitSystemWindows(mAttachInfo.mContentInsets);
748 insetsChanged = true;
749 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
750 + mAttachInfo.mContentInsets);
751 }
752 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
753 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
754 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
755 + mAttachInfo.mVisibleInsets);
756 }
757 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
758 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
759 windowResizesToFitContent = true;
760
Romain Guy8506ab42009-06-11 17:35:47 -0700761 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700762 mView.getContext().getResources().getDisplayMetrics();
763 desiredWindowWidth = packageMetrics.widthPixels;
764 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
766 }
767
768 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
769 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
770
771 // Ask host how big it wants to be
772 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
773 "Measuring " + host + " in display " + desiredWindowWidth
774 + "x" + desiredWindowHeight + "...");
775 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
776
777 if (DBG) {
778 System.out.println("======================================");
779 System.out.println("performTraversals -- after measure");
780 host.debug();
781 }
782 }
783
784 if (attachInfo.mRecomputeGlobalAttributes) {
785 //Log.i(TAG, "Computing screen on!");
786 attachInfo.mRecomputeGlobalAttributes = false;
787 boolean oldVal = attachInfo.mKeepScreenOn;
788 attachInfo.mKeepScreenOn = false;
789 host.dispatchCollectViewAttributes(0);
790 if (attachInfo.mKeepScreenOn != oldVal) {
791 params = lp;
792 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
793 }
794 }
795
796 if (mFirst || attachInfo.mViewVisibilityChanged) {
797 attachInfo.mViewVisibilityChanged = false;
798 int resizeMode = mSoftInputMode &
799 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
800 // If we are in auto resize mode, then we need to determine
801 // what mode to use now.
802 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
803 final int N = attachInfo.mScrollContainers.size();
804 for (int i=0; i<N; i++) {
805 if (attachInfo.mScrollContainers.get(i).isShown()) {
806 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
807 }
808 }
809 if (resizeMode == 0) {
810 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
811 }
812 if ((lp.softInputMode &
813 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
814 lp.softInputMode = (lp.softInputMode &
815 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
816 resizeMode;
817 params = lp;
818 }
819 }
820 }
Romain Guy8506ab42009-06-11 17:35:47 -0700821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
823 if (!PixelFormat.formatHasAlpha(params.format)) {
824 params.format = PixelFormat.TRANSLUCENT;
825 }
826 }
827
828 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
829 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
830
831 final boolean computesInternalInsets =
832 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
833 boolean insetsPending = false;
834 int relayoutResult = 0;
835 if (mFirst || windowShouldResize || insetsChanged
836 || viewVisibilityChanged || params != null) {
837
838 if (viewVisibility == View.VISIBLE) {
839 // If this window is giving internal insets to the window
840 // manager, and it is being added or changing its visibility,
841 // then we want to first give the window manager "fake"
842 // insets to cause it to effectively ignore the content of
843 // the window during layout. This avoids it briefly causing
844 // other windows to resize/move based on the raw frame of the
845 // window, waiting until we can finish laying out this window
846 // and get back to the window manager with the ultimately
847 // computed insets.
848 insetsPending = computesInternalInsets
849 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
852 if (params == null) {
853 params = mWindowAttributes;
854 }
855 mGlWanted = true;
856 }
857 }
858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 boolean initialized = false;
860 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700861 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 try {
863 boolean hadSurface = mSurface.isValid();
864 int fl = 0;
865 if (params != null) {
866 fl = params.flags;
867 if (attachInfo.mKeepScreenOn) {
868 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
869 }
870 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700871 if (DEBUG_LAYOUT) {
872 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
873 host.mMeasuredHeight + ", params=" + params);
874 }
875 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 if (params != null) {
878 params.flags = fl;
879 }
880
881 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
882 + " content=" + mPendingContentInsets.toShortString()
883 + " visible=" + mPendingVisibleInsets.toShortString()
884 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 contentInsetsChanged = !mPendingContentInsets.equals(
887 mAttachInfo.mContentInsets);
888 visibleInsetsChanged = !mPendingVisibleInsets.equals(
889 mAttachInfo.mVisibleInsets);
890 if (contentInsetsChanged) {
891 mAttachInfo.mContentInsets.set(mPendingContentInsets);
892 host.fitSystemWindows(mAttachInfo.mContentInsets);
893 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
894 + mAttachInfo.mContentInsets);
895 }
896 if (visibleInsetsChanged) {
897 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
898 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
899 + mAttachInfo.mVisibleInsets);
900 }
901
902 if (!hadSurface) {
903 if (mSurface.isValid()) {
904 // If we are creating a new surface, then we need to
905 // completely redraw it. Also, when we get to the
906 // point of drawing it we will hold off and schedule
907 // a new traversal instead. This is so we can tell the
908 // window manager about all of the windows being displayed
909 // before actually drawing them, so it can display then
910 // all at once.
911 newSurface = true;
912 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700913 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 if (mGlWanted && !mUseGL) {
916 initializeGL();
917 initialized = mGlCanvas != null;
918 }
919 }
920 } else if (!mSurface.isValid()) {
921 // If the surface has been removed, then reset the scroll
922 // positions.
923 mLastScrolledFocus = null;
924 mScrollY = mCurScrollY = 0;
925 if (mScroller != null) {
926 mScroller.abortAnimation();
927 }
928 }
929 } catch (RemoteException e) {
930 }
931 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700932 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933
934 attachInfo.mWindowLeft = frame.left;
935 attachInfo.mWindowTop = frame.top;
936
937 // !!FIXME!! This next section handles the case where we did not get the
938 // window size we asked for. We should avoid this by getting a maximum size from
939 // the window session beforehand.
940 mWidth = frame.width();
941 mHeight = frame.height();
942
943 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -0700944 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
945 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
947
948 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
949 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
950 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
951 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
952 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
953 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
954
955 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
956 + mWidth + " measuredWidth=" + host.mMeasuredWidth
957 + " mHeight=" + mHeight
958 + " measuredHeight" + host.mMeasuredHeight
959 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 // Ask host how big it wants to be
962 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
963
964 // Implementation of weights from WindowManager.LayoutParams
965 // We just grow the dimensions as needed and re-measure if
966 // needs be
967 int width = host.mMeasuredWidth;
968 int height = host.mMeasuredHeight;
969 boolean measureAgain = false;
970
971 if (lp.horizontalWeight > 0.0f) {
972 width += (int) ((mWidth - width) * lp.horizontalWeight);
973 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
974 MeasureSpec.EXACTLY);
975 measureAgain = true;
976 }
977 if (lp.verticalWeight > 0.0f) {
978 height += (int) ((mHeight - height) * lp.verticalWeight);
979 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
980 MeasureSpec.EXACTLY);
981 measureAgain = true;
982 }
983
984 if (measureAgain) {
985 if (DEBUG_LAYOUT) Log.v(TAG,
986 "And hey let's measure once more: width=" + width
987 + " height=" + height);
988 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
989 }
990
991 mLayoutRequested = true;
992 }
993 }
994
995 final boolean didLayout = mLayoutRequested;
996 boolean triggerGlobalLayoutListener = didLayout
997 || attachInfo.mRecomputeGlobalAttributes;
998 if (didLayout) {
999 mLayoutRequested = false;
1000 mScrollMayChange = true;
1001 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1002 "ViewRoot", "Laying out " + host + " to (" +
1003 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001004 long startTime = 0L;
1005 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 startTime = SystemClock.elapsedRealtime();
1007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1009
Romain Guy13922e02009-05-12 17:56:14 -07001010 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1011 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1012 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1013 + "please refer to the logs with the tag "
1014 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1015 }
1016 }
1017
1018 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1020 }
1021
1022 // By this point all views have been sized and positionned
1023 // We can compute the transparent area
1024
1025 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1026 // start out transparent
1027 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1028 host.getLocationInWindow(mTmpLocation);
1029 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1030 mTmpLocation[0] + host.mRight - host.mLeft,
1031 mTmpLocation[1] + host.mBottom - host.mTop);
1032
1033 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001034 if (mTranslator != null) {
1035 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1036 }
1037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1039 mPreviousTransparentRegion.set(mTransparentRegion);
1040 // reconfigure window manager
1041 try {
1042 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1043 } catch (RemoteException e) {
1044 }
1045 }
1046 }
1047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 if (DBG) {
1049 System.out.println("======================================");
1050 System.out.println("performTraversals -- after setFrame");
1051 host.debug();
1052 }
1053 }
1054
1055 if (triggerGlobalLayoutListener) {
1056 attachInfo.mRecomputeGlobalAttributes = false;
1057 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1058 }
1059
1060 if (computesInternalInsets) {
1061 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1062 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1063 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1064 givenContent.left = givenContent.top = givenContent.right
1065 = givenContent.bottom = givenVisible.left = givenVisible.top
1066 = givenVisible.right = givenVisible.bottom = 0;
1067 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001068 Rect contentInsets = insets.contentInsets;
1069 Rect visibleInsets = insets.visibleInsets;
1070 if (mTranslator != null) {
1071 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1072 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1075 mLastGivenInsets.set(insets);
1076 try {
1077 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001078 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 } catch (RemoteException e) {
1080 }
1081 }
1082 }
Romain Guy8506ab42009-06-11 17:35:47 -07001083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 if (mFirst) {
1085 // handle first focus request
1086 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1087 + mView.hasFocus());
1088 if (mView != null) {
1089 if (!mView.hasFocus()) {
1090 mView.requestFocus(View.FOCUS_FORWARD);
1091 mFocusedView = mRealFocusedView = mView.findFocus();
1092 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1093 + mFocusedView);
1094 } else {
1095 mRealFocusedView = mView.findFocus();
1096 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1097 + mRealFocusedView);
1098 }
1099 }
1100 }
1101
1102 mFirst = false;
1103 mWillDrawSoon = false;
1104 mNewSurfaceNeeded = false;
1105 mViewVisibility = viewVisibility;
1106
1107 if (mAttachInfo.mHasWindowFocus) {
1108 final boolean imTarget = WindowManager.LayoutParams
1109 .mayUseInputMethod(mWindowAttributes.flags);
1110 if (imTarget != mLastWasImTarget) {
1111 mLastWasImTarget = imTarget;
1112 InputMethodManager imm = InputMethodManager.peekInstance();
1113 if (imm != null && imTarget) {
1114 imm.startGettingWindowFocus(mView);
1115 imm.onWindowFocus(mView, mView.findFocus(),
1116 mWindowAttributes.softInputMode,
1117 !mHasHadWindowFocus, mWindowAttributes.flags);
1118 }
1119 }
1120 }
Romain Guy8506ab42009-06-11 17:35:47 -07001121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1123
1124 if (!cancelDraw && !newSurface) {
1125 mFullRedrawNeeded = false;
1126 draw(fullRedrawNeeded);
1127
1128 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1129 || mReportNextDraw) {
1130 if (LOCAL_LOGV) {
1131 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1132 }
1133 mReportNextDraw = false;
1134 try {
1135 sWindowSession.finishDrawing(mWindow);
1136 } catch (RemoteException e) {
1137 }
1138 }
1139 } else {
1140 // We were supposed to report when we are done drawing. Since we canceled the
1141 // draw, remember it here.
1142 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1143 mReportNextDraw = true;
1144 }
1145 if (fullRedrawNeeded) {
1146 mFullRedrawNeeded = true;
1147 }
1148 // Try again
1149 scheduleTraversals();
1150 }
1151 }
1152
1153 public void requestTransparentRegion(View child) {
1154 // the test below should not fail unless someone is messing with us
1155 checkThread();
1156 if (mView == child) {
1157 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1158 // Need to make sure we re-evaluate the window attributes next
1159 // time around, to ensure the window has the correct format.
1160 mWindowAttributesChanged = true;
1161 }
1162 }
1163
1164 /**
1165 * Figures out the measure spec for the root view in a window based on it's
1166 * layout params.
1167 *
1168 * @param windowSize
1169 * The available width or height of the window
1170 *
1171 * @param rootDimension
1172 * The layout params for one dimension (width or height) of the
1173 * window.
1174 *
1175 * @return The measure spec to use to measure the root view.
1176 */
1177 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1178 int measureSpec;
1179 switch (rootDimension) {
1180
Romain Guy980a9382010-01-08 15:06:28 -08001181 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 // Window can't resize. Force root view to be windowSize.
1183 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1184 break;
1185 case ViewGroup.LayoutParams.WRAP_CONTENT:
1186 // Window can resize. Set max size for root view.
1187 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1188 break;
1189 default:
1190 // Window wants to be an exact size. Force root view to be that size.
1191 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1192 break;
1193 }
1194 return measureSpec;
1195 }
1196
1197 private void draw(boolean fullRedrawNeeded) {
1198 Surface surface = mSurface;
1199 if (surface == null || !surface.isValid()) {
1200 return;
1201 }
1202
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001203 if (!sFirstDrawComplete) {
1204 synchronized (sFirstDrawHandlers) {
1205 sFirstDrawComplete = true;
1206 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1207 post(sFirstDrawHandlers.get(i));
1208 }
1209 }
1210 }
1211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 scrollToRectOrFocus(null, false);
1213
1214 if (mAttachInfo.mViewScrollChanged) {
1215 mAttachInfo.mViewScrollChanged = false;
1216 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1217 }
Romain Guy8506ab42009-06-11 17:35:47 -07001218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001220 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 if (scrolling) {
1222 yoff = mScroller.getCurrY();
1223 } else {
1224 yoff = mScrollY;
1225 }
1226 if (mCurScrollY != yoff) {
1227 mCurScrollY = yoff;
1228 fullRedrawNeeded = true;
1229 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001230 float appScale = mAttachInfo.mApplicationScale;
1231 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232
1233 Rect dirty = mDirty;
1234 if (mUseGL) {
1235 if (!dirty.isEmpty()) {
1236 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001237 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 mGL.glDisable(GL_SCISSOR_TEST);
1239 mGL.glClearColor(0, 0, 0, 0);
1240 mGL.glClear(GL_COLOR_BUFFER_BIT);
1241 mGL.glEnable(GL_SCISSOR_TEST);
1242
1243 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001244 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001246
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001247 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1248 try {
1249 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001250 if (mTranslator != null) {
1251 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001252 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001253 canvas.setScreenDensity(scalingRequired
1254 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001255 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001256 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1257 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1258 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001259 } finally {
1260 canvas.restoreToCount(saveCount);
1261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262
Romain Guy5bcdff42009-05-14 21:27:18 -07001263 mAttachInfo.mIgnoreDirtyState = false;
1264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1266 checkEglErrors();
1267
Mike Reedfd716532009-10-12 14:42:56 -04001268 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 int now = (int)SystemClock.elapsedRealtime();
1270 if (sDrawTime != 0) {
1271 nativeShowFPS(canvas, now - sDrawTime);
1272 }
1273 sDrawTime = now;
1274 }
1275 }
1276 }
1277 if (scrolling) {
1278 mFullRedrawNeeded = true;
1279 scheduleTraversals();
1280 }
1281 return;
1282 }
1283
Romain Guy5bcdff42009-05-14 21:27:18 -07001284 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001285 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001286 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288
1289 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1290 Log.v("ViewRoot", "Draw " + mView + "/"
1291 + mWindowAttributes.getTitle()
1292 + ": dirty={" + dirty.left + "," + dirty.top
1293 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001294 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1295 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
1297
1298 Canvas canvas;
1299 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001300 int left = dirty.left;
1301 int top = dirty.top;
1302 int right = dirty.right;
1303 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001305
1306 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1307 bottom != dirty.bottom) {
1308 mAttachInfo.mIgnoreDirtyState = true;
1309 }
1310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 // TODO: Do this in native
Dianne Hackborn11ea3342009-07-22 21:48:55 -07001312 canvas.setDensity(mDensity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 } catch (Surface.OutOfResourcesException e) {
1314 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1315 // TODO: we should ask the window manager to do something!
1316 // for now we just do nothing
1317 return;
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001318 } catch (IllegalArgumentException e) {
1319 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1320 // TODO: we should ask the window manager to do something!
1321 // for now we just do nothing
1322 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324
1325 try {
Romain Guybb93d552009-03-24 21:04:15 -07001326 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001327 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328
1329 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1330 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1331 + canvas.getWidth() + ", h=" + canvas.getHeight());
1332 //canvas.drawARGB(255, 255, 0, 0);
1333 }
1334
Romain Guy13922e02009-05-12 17:56:14 -07001335 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 startTime = SystemClock.elapsedRealtime();
1337 }
1338
1339 // If this bitmap's format includes an alpha channel, we
1340 // need to clear it before drawing so that the child will
1341 // properly re-composite its drawing on a transparent
1342 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001343 // or
1344 // If we are applying an offset, we need to clear the area
1345 // where the offset doesn't appear to avoid having garbage
1346 // left in the blank areas.
1347 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1349 }
1350
1351 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001352 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001354 mView.mPrivateFlags |= View.DRAWN;
1355
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001356 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001357 Context cxt = mView.getContext();
1358 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -07001359 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1360 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001361 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001362 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001363 try {
1364 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001365 if (mTranslator != null) {
1366 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001367 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001368 canvas.setScreenDensity(scalingRequired
1369 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001370 mView.draw(canvas);
1371 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001372 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001373 canvas.restoreToCount(saveCount);
1374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375
Romain Guy5bcdff42009-05-14 21:27:18 -07001376 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1377 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1378 }
1379
Mike Reedfd716532009-10-12 14:42:56 -04001380 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 int now = (int)SystemClock.elapsedRealtime();
1382 if (sDrawTime != 0) {
1383 nativeShowFPS(canvas, now - sDrawTime);
1384 }
1385 sDrawTime = now;
1386 }
1387
Romain Guy13922e02009-05-12 17:56:14 -07001388 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1390 }
1391 }
Romain Guy8506ab42009-06-11 17:35:47 -07001392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 } finally {
1394 surface.unlockCanvasAndPost(canvas);
1395 }
1396
1397 if (LOCAL_LOGV) {
1398 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1399 }
Romain Guy8506ab42009-06-11 17:35:47 -07001400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 if (scrolling) {
1402 mFullRedrawNeeded = true;
1403 scheduleTraversals();
1404 }
1405 }
1406
1407 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1408 final View.AttachInfo attachInfo = mAttachInfo;
1409 final Rect ci = attachInfo.mContentInsets;
1410 final Rect vi = attachInfo.mVisibleInsets;
1411 int scrollY = 0;
1412 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 if (vi.left > ci.left || vi.top > ci.top
1415 || vi.right > ci.right || vi.bottom > ci.bottom) {
1416 // We'll assume that we aren't going to change the scroll
1417 // offset, since we want to avoid that unless it is actually
1418 // going to make the focus visible... otherwise we scroll
1419 // all over the place.
1420 scrollY = mScrollY;
1421 // We can be called for two different situations: during a draw,
1422 // to update the scroll position if the focus has changed (in which
1423 // case 'rectangle' is null), or in response to a
1424 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1425 // is non-null and we just want to scroll to whatever that
1426 // rectangle is).
1427 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001428
1429 // When in touch mode, focus points to the previously focused view,
1430 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001431 // line checks whether the view is still in our hierarchy.
1432 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001433 mRealFocusedView = null;
1434 return false;
1435 }
1436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 if (focus != mLastScrolledFocus) {
1438 // If the focus has changed, then ignore any requests to scroll
1439 // to a rectangle; first we want to make sure the entire focus
1440 // view is visible.
1441 rectangle = null;
1442 }
1443 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1444 + " rectangle=" + rectangle + " ci=" + ci
1445 + " vi=" + vi);
1446 if (focus == mLastScrolledFocus && !mScrollMayChange
1447 && rectangle == null) {
1448 // Optimization: if the focus hasn't changed since last
1449 // time, and no layout has happened, then just leave things
1450 // as they are.
1451 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1452 + mScrollY + " vi=" + vi.toShortString());
1453 } else if (focus != null) {
1454 // We need to determine if the currently focused view is
1455 // within the visible part of the window and, if not, apply
1456 // a pan so it can be seen.
1457 mLastScrolledFocus = focus;
1458 mScrollMayChange = false;
1459 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1460 // Try to find the rectangle from the focus view.
1461 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1462 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1463 + mView.getWidth() + " h=" + mView.getHeight()
1464 + " ci=" + ci.toShortString()
1465 + " vi=" + vi.toShortString());
1466 if (rectangle == null) {
1467 focus.getFocusedRect(mTempRect);
1468 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1469 + ": focusRect=" + mTempRect.toShortString());
1470 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1471 focus, mTempRect);
1472 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1473 "Focus in window: focusRect="
1474 + mTempRect.toShortString()
1475 + " visRect=" + mVisRect.toShortString());
1476 } else {
1477 mTempRect.set(rectangle);
1478 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1479 "Request scroll to rect: "
1480 + mTempRect.toShortString()
1481 + " visRect=" + mVisRect.toShortString());
1482 }
1483 if (mTempRect.intersect(mVisRect)) {
1484 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1485 "Focus window visible rect: "
1486 + mTempRect.toShortString());
1487 if (mTempRect.height() >
1488 (mView.getHeight()-vi.top-vi.bottom)) {
1489 // If the focus simply is not going to fit, then
1490 // best is probably just to leave things as-is.
1491 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1492 "Too tall; leaving scrollY=" + scrollY);
1493 } else if ((mTempRect.top-scrollY) < vi.top) {
1494 scrollY -= vi.top - (mTempRect.top-scrollY);
1495 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1496 "Top covered; scrollY=" + scrollY);
1497 } else if ((mTempRect.bottom-scrollY)
1498 > (mView.getHeight()-vi.bottom)) {
1499 scrollY += (mTempRect.bottom-scrollY)
1500 - (mView.getHeight()-vi.bottom);
1501 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1502 "Bottom covered; scrollY=" + scrollY);
1503 }
1504 handled = true;
1505 }
1506 }
1507 }
1508 }
Romain Guy8506ab42009-06-11 17:35:47 -07001509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 if (scrollY != mScrollY) {
1511 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1512 + mScrollY + " , new=" + scrollY);
1513 if (!immediate) {
1514 if (mScroller == null) {
1515 mScroller = new Scroller(mView.getContext());
1516 }
1517 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1518 } else if (mScroller != null) {
1519 mScroller.abortAnimation();
1520 }
1521 mScrollY = scrollY;
1522 }
Romain Guy8506ab42009-06-11 17:35:47 -07001523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 return handled;
1525 }
Romain Guy8506ab42009-06-11 17:35:47 -07001526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 public void requestChildFocus(View child, View focused) {
1528 checkThread();
1529 if (mFocusedView != focused) {
1530 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1531 scheduleTraversals();
1532 }
1533 mFocusedView = mRealFocusedView = focused;
1534 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1535 + mFocusedView);
1536 }
1537
1538 public void clearChildFocus(View child) {
1539 checkThread();
1540
1541 View oldFocus = mFocusedView;
1542
1543 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1544 mFocusedView = mRealFocusedView = null;
1545 if (mView != null && !mView.hasFocus()) {
1546 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1547 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1548 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1549 }
1550 } else if (oldFocus != null) {
1551 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1552 }
1553 }
1554
1555
1556 public void focusableViewAvailable(View v) {
1557 checkThread();
1558
1559 if (mView != null && !mView.hasFocus()) {
1560 v.requestFocus();
1561 } else {
1562 // the one case where will transfer focus away from the current one
1563 // is if the current view is a view group that prefers to give focus
1564 // to its children first AND the view is a descendant of it.
1565 mFocusedView = mView.findFocus();
1566 boolean descendantsHaveDibsOnFocus =
1567 (mFocusedView instanceof ViewGroup) &&
1568 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1569 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1570 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1571 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1572 v.requestFocus();
1573 }
1574 }
1575 }
1576
1577 public void recomputeViewAttributes(View child) {
1578 checkThread();
1579 if (mView == child) {
1580 mAttachInfo.mRecomputeGlobalAttributes = true;
1581 if (!mWillDrawSoon) {
1582 scheduleTraversals();
1583 }
1584 }
1585 }
1586
1587 void dispatchDetachedFromWindow() {
1588 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1589
1590 if (mView != null) {
1591 mView.dispatchDetachedFromWindow();
1592 }
1593
1594 mView = null;
1595 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001596 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597
1598 if (mUseGL) {
1599 destroyGL();
1600 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001601 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602
1603 try {
1604 sWindowSession.remove(mWindow);
1605 } catch (RemoteException e) {
1606 }
1607 }
Romain Guy8506ab42009-06-11 17:35:47 -07001608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 /**
1610 * Return true if child is an ancestor of parent, (or equal to the parent).
1611 */
1612 private static boolean isViewDescendantOf(View child, View parent) {
1613 if (child == parent) {
1614 return true;
1615 }
1616
1617 final ViewParent theParent = child.getParent();
1618 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1619 }
1620
1621
1622 public final static int DO_TRAVERSAL = 1000;
1623 public final static int DIE = 1001;
1624 public final static int RESIZED = 1002;
1625 public final static int RESIZED_REPORT = 1003;
1626 public final static int WINDOW_FOCUS_CHANGED = 1004;
1627 public final static int DISPATCH_KEY = 1005;
1628 public final static int DISPATCH_POINTER = 1006;
1629 public final static int DISPATCH_TRACKBALL = 1007;
1630 public final static int DISPATCH_APP_VISIBILITY = 1008;
1631 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1632 public final static int FINISHED_EVENT = 1010;
1633 public final static int DISPATCH_KEY_FROM_IME = 1011;
1634 public final static int FINISH_INPUT_CONNECTION = 1012;
1635 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001636 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637
1638 @Override
1639 public void handleMessage(Message msg) {
1640 switch (msg.what) {
1641 case View.AttachInfo.INVALIDATE_MSG:
1642 ((View) msg.obj).invalidate();
1643 break;
1644 case View.AttachInfo.INVALIDATE_RECT_MSG:
1645 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1646 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1647 info.release();
1648 break;
1649 case DO_TRAVERSAL:
1650 if (mProfile) {
1651 Debug.startMethodTracing("ViewRoot");
1652 }
1653
1654 performTraversals();
1655
1656 if (mProfile) {
1657 Debug.stopMethodTracing();
1658 mProfile = false;
1659 }
1660 break;
1661 case FINISHED_EVENT:
1662 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1663 break;
1664 case DISPATCH_KEY:
1665 if (LOCAL_LOGV) Log.v(
1666 "ViewRoot", "Dispatching key "
1667 + msg.obj + " to " + mView);
1668 deliverKeyEvent((KeyEvent)msg.obj, true);
1669 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001670 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001672 boolean callWhenDone = msg.arg1 != 0;
1673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 if (event == null) {
1675 try {
Michael Chan53071d62009-05-13 17:29:48 -07001676 long timeBeforeGettingEvents;
1677 if (MEASURE_LATENCY) {
1678 timeBeforeGettingEvents = System.nanoTime();
1679 }
1680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001682
1683 if (MEASURE_LATENCY && event != null) {
1684 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1685 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 } catch (RemoteException e) {
1688 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001689 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001691 if (event != null && mTranslator != null) {
1692 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 try {
1695 boolean handled;
1696 if (mView != null && mAdded && event != null) {
1697
1698 // enter touch mode on the down
1699 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1700 if (isDown) {
1701 ensureTouchMode(true);
1702 }
1703 if(Config.LOGV) {
1704 captureMotionLog("captureDispatchPointer", event);
1705 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001706 if (mCurScrollY != 0) {
1707 event.offsetLocation(0, mCurScrollY);
1708 }
Michael Chan53071d62009-05-13 17:29:48 -07001709 if (MEASURE_LATENCY) {
1710 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001713 if (MEASURE_LATENCY) {
1714 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 if (!handled && isDown) {
1717 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1718
1719 final int edgeFlags = event.getEdgeFlags();
1720 int direction = View.FOCUS_UP;
1721 int x = (int)event.getX();
1722 int y = (int)event.getY();
1723 final int[] deltas = new int[2];
1724
1725 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1726 direction = View.FOCUS_DOWN;
1727 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1728 deltas[0] = edgeSlop;
1729 x += edgeSlop;
1730 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1731 deltas[0] = -edgeSlop;
1732 x -= edgeSlop;
1733 }
1734 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1735 direction = View.FOCUS_UP;
1736 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1737 deltas[0] = edgeSlop;
1738 x += edgeSlop;
1739 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1740 deltas[0] = -edgeSlop;
1741 x -= edgeSlop;
1742 }
1743 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1744 direction = View.FOCUS_RIGHT;
1745 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1746 direction = View.FOCUS_LEFT;
1747 }
1748
1749 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1750 View nearest = FocusFinder.getInstance().findNearestTouchable(
1751 ((ViewGroup) mView), x, y, direction, deltas);
1752 if (nearest != null) {
1753 event.offsetLocation(deltas[0], deltas[1]);
1754 event.setEdgeFlags(0);
1755 mView.dispatchTouchEvent(event);
1756 }
1757 }
1758 }
1759 }
1760 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001761 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 try {
1763 sWindowSession.finishKey(mWindow);
1764 } catch (RemoteException e) {
1765 }
1766 }
1767 if (event != null) {
1768 event.recycle();
1769 }
1770 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1771 // Let the exception fall through -- the looper will catch
1772 // it and take care of the bad app for us.
1773 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001774 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001776 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 break;
1778 case DISPATCH_APP_VISIBILITY:
1779 handleAppVisibility(msg.arg1 != 0);
1780 break;
1781 case DISPATCH_GET_NEW_SURFACE:
1782 handleGetNewSurface();
1783 break;
1784 case RESIZED:
1785 Rect coveredInsets = ((Rect[])msg.obj)[0];
1786 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1789 && mPendingContentInsets.equals(coveredInsets)
1790 && mPendingVisibleInsets.equals(visibleInsets)) {
1791 break;
1792 }
1793 // fall through...
1794 case RESIZED_REPORT:
1795 if (mAdded) {
1796 mWinFrame.left = 0;
1797 mWinFrame.right = msg.arg1;
1798 mWinFrame.top = 0;
1799 mWinFrame.bottom = msg.arg2;
1800 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1801 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1802 if (msg.what == RESIZED_REPORT) {
1803 mReportNextDraw = true;
1804 }
1805 requestLayout();
1806 }
1807 break;
1808 case WINDOW_FOCUS_CHANGED: {
1809 if (mAdded) {
1810 boolean hasWindowFocus = msg.arg1 != 0;
1811 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1812 if (hasWindowFocus) {
1813 boolean inTouchMode = msg.arg2 != 0;
1814 ensureTouchModeLocally(inTouchMode);
1815
1816 if (mGlWanted) {
1817 checkEglErrors();
1818 // we lost the gl context, so recreate it.
1819 if (mGlWanted && !mUseGL) {
1820 initializeGL();
1821 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001822 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001823 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001824 (int) (mWidth * appScale + 0.5f),
1825 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828 }
1829 }
Romain Guy8506ab42009-06-11 17:35:47 -07001830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 mLastWasImTarget = WindowManager.LayoutParams
1832 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 InputMethodManager imm = InputMethodManager.peekInstance();
1835 if (mView != null) {
1836 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1837 imm.startGettingWindowFocus(mView);
1838 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001839 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 mView.dispatchWindowFocusChanged(hasWindowFocus);
1841 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 // Note: must be done after the focus change callbacks,
1844 // so all of the view state is set up correctly.
1845 if (hasWindowFocus) {
1846 if (imm != null && mLastWasImTarget) {
1847 imm.onWindowFocus(mView, mView.findFocus(),
1848 mWindowAttributes.softInputMode,
1849 !mHasHadWindowFocus, mWindowAttributes.flags);
1850 }
1851 // Clear the forward bit. We can just do this directly, since
1852 // the window manager doesn't care about it.
1853 mWindowAttributes.softInputMode &=
1854 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1855 ((WindowManager.LayoutParams)mView.getLayoutParams())
1856 .softInputMode &=
1857 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1858 mHasHadWindowFocus = true;
1859 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001860
1861 if (hasWindowFocus && mView != null) {
1862 sendAccessibilityEvents();
1863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
1865 } break;
1866 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001867 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001869 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 if (LOCAL_LOGV) Log.v(
1871 "ViewRoot", "Dispatching key "
1872 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001873 KeyEvent event = (KeyEvent)msg.obj;
1874 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1875 // The IME is trying to say this event is from the
1876 // system! Bad bad bad!
1877 event = KeyEvent.changeFlags(event,
1878 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001881 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 case FINISH_INPUT_CONNECTION: {
1883 InputMethodManager imm = InputMethodManager.peekInstance();
1884 if (imm != null) {
1885 imm.reportFinishInputConnection((InputConnection)msg.obj);
1886 }
1887 } break;
1888 case CHECK_FOCUS: {
1889 InputMethodManager imm = InputMethodManager.peekInstance();
1890 if (imm != null) {
1891 imm.checkFocus();
1892 }
1893 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001894 case CLOSE_SYSTEM_DIALOGS: {
1895 if (mView != null) {
1896 mView.onCloseSystemDialogs((String)msg.obj);
1897 }
1898 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900 }
1901
1902 /**
1903 * Something in the current window tells us we need to change the touch mode. For
1904 * example, we are not in touch mode, and the user touches the screen.
1905 *
1906 * If the touch mode has changed, tell the window manager, and handle it locally.
1907 *
1908 * @param inTouchMode Whether we want to be in touch mode.
1909 * @return True if the touch mode changed and focus changed was changed as a result
1910 */
1911 boolean ensureTouchMode(boolean inTouchMode) {
1912 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1913 + "touch mode is " + mAttachInfo.mInTouchMode);
1914 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1915
1916 // tell the window manager
1917 try {
1918 sWindowSession.setInTouchMode(inTouchMode);
1919 } catch (RemoteException e) {
1920 throw new RuntimeException(e);
1921 }
1922
1923 // handle the change
1924 return ensureTouchModeLocally(inTouchMode);
1925 }
1926
1927 /**
1928 * Ensure that the touch mode for this window is set, and if it is changing,
1929 * take the appropriate action.
1930 * @param inTouchMode Whether we want to be in touch mode.
1931 * @return True if the touch mode changed and focus changed was changed as a result
1932 */
1933 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1934 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1935 + "touch mode is " + mAttachInfo.mInTouchMode);
1936
1937 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1938
1939 mAttachInfo.mInTouchMode = inTouchMode;
1940 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1941
1942 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1943 }
1944
1945 private boolean enterTouchMode() {
1946 if (mView != null) {
1947 if (mView.hasFocus()) {
1948 // note: not relying on mFocusedView here because this could
1949 // be when the window is first being added, and mFocused isn't
1950 // set yet.
1951 final View focused = mView.findFocus();
1952 if (focused != null && !focused.isFocusableInTouchMode()) {
1953
1954 final ViewGroup ancestorToTakeFocus =
1955 findAncestorToTakeFocusInTouchMode(focused);
1956 if (ancestorToTakeFocus != null) {
1957 // there is an ancestor that wants focus after its descendants that
1958 // is focusable in touch mode.. give it focus
1959 return ancestorToTakeFocus.requestFocus();
1960 } else {
1961 // nothing appropriate to have focus in touch mode, clear it out
1962 mView.unFocus();
1963 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1964 mFocusedView = null;
1965 return true;
1966 }
1967 }
1968 }
1969 }
1970 return false;
1971 }
1972
1973
1974 /**
1975 * Find an ancestor of focused that wants focus after its descendants and is
1976 * focusable in touch mode.
1977 * @param focused The currently focused view.
1978 * @return An appropriate view, or null if no such view exists.
1979 */
1980 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1981 ViewParent parent = focused.getParent();
1982 while (parent instanceof ViewGroup) {
1983 final ViewGroup vgParent = (ViewGroup) parent;
1984 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1985 && vgParent.isFocusableInTouchMode()) {
1986 return vgParent;
1987 }
1988 if (vgParent.isRootNamespace()) {
1989 return null;
1990 } else {
1991 parent = vgParent.getParent();
1992 }
1993 }
1994 return null;
1995 }
1996
1997 private boolean leaveTouchMode() {
1998 if (mView != null) {
1999 if (mView.hasFocus()) {
2000 // i learned the hard way to not trust mFocusedView :)
2001 mFocusedView = mView.findFocus();
2002 if (!(mFocusedView instanceof ViewGroup)) {
2003 // some view has focus, let it keep it
2004 return false;
2005 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2006 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2007 // some view group has focus, and doesn't prefer its children
2008 // over itself for focus, so let them keep it.
2009 return false;
2010 }
2011 }
2012
2013 // find the best view to give focus to in this brave new non-touch-mode
2014 // world
2015 final View focused = focusSearch(null, View.FOCUS_DOWN);
2016 if (focused != null) {
2017 return focused.requestFocus(View.FOCUS_DOWN);
2018 }
2019 }
2020 return false;
2021 }
2022
2023
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002024 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 if (event == null) {
2026 try {
2027 event = sWindowSession.getPendingTrackballMove(mWindow);
2028 } catch (RemoteException e) {
2029 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002030 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032
2033 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2034
2035 boolean handled = false;
2036 try {
2037 if (event == null) {
2038 handled = true;
2039 } else if (mView != null && mAdded) {
2040 handled = mView.dispatchTrackballEvent(event);
2041 if (!handled) {
2042 // we could do something here, like changing the focus
2043 // or something?
2044 }
2045 }
2046 } finally {
2047 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002048 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 try {
2050 sWindowSession.finishKey(mWindow);
2051 } catch (RemoteException e) {
2052 }
2053 }
2054 if (event != null) {
2055 event.recycle();
2056 }
2057 // If we reach this, we delivered a trackball event to mView and
2058 // mView consumed it. Because we will not translate the trackball
2059 // event into a key event, touch mode will not exit, so we exit
2060 // touch mode here.
2061 ensureTouchMode(false);
2062 //noinspection ReturnInsideFinallyBlock
2063 return;
2064 }
2065 // Let the exception fall through -- the looper will catch
2066 // it and take care of the bad app for us.
2067 }
2068
2069 final TrackballAxis x = mTrackballAxisX;
2070 final TrackballAxis y = mTrackballAxisY;
2071
2072 long curTime = SystemClock.uptimeMillis();
2073 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2074 // It has been too long since the last movement,
2075 // so restart at the beginning.
2076 x.reset(0);
2077 y.reset(0);
2078 mLastTrackballTime = curTime;
2079 }
2080
2081 try {
2082 final int action = event.getAction();
2083 final int metastate = event.getMetaState();
2084 switch (action) {
2085 case MotionEvent.ACTION_DOWN:
2086 x.reset(2);
2087 y.reset(2);
2088 deliverKeyEvent(new KeyEvent(curTime, curTime,
2089 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2090 0, metastate), false);
2091 break;
2092 case MotionEvent.ACTION_UP:
2093 x.reset(2);
2094 y.reset(2);
2095 deliverKeyEvent(new KeyEvent(curTime, curTime,
2096 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2097 0, metastate), false);
2098 break;
2099 }
2100
2101 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2102 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2103 + " move=" + event.getX()
2104 + " / Y=" + y.position + " step="
2105 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2106 + " move=" + event.getY());
2107 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2108 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2109
2110 // Generate DPAD events based on the trackball movement.
2111 // We pick the axis that has moved the most as the direction of
2112 // the DPAD. When we generate DPAD events for one axis, then the
2113 // other axis is reset -- we don't want to perform DPAD jumps due
2114 // to slight movements in the trackball when making major movements
2115 // along the other axis.
2116 int keycode = 0;
2117 int movement = 0;
2118 float accel = 1;
2119 if (xOff > yOff) {
2120 movement = x.generate((2/event.getXPrecision()));
2121 if (movement != 0) {
2122 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2123 : KeyEvent.KEYCODE_DPAD_LEFT;
2124 accel = x.acceleration;
2125 y.reset(2);
2126 }
2127 } else if (yOff > 0) {
2128 movement = y.generate((2/event.getYPrecision()));
2129 if (movement != 0) {
2130 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2131 : KeyEvent.KEYCODE_DPAD_UP;
2132 accel = y.acceleration;
2133 x.reset(2);
2134 }
2135 }
2136
2137 if (keycode != 0) {
2138 if (movement < 0) movement = -movement;
2139 int accelMovement = (int)(movement * accel);
2140 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2141 + " accelMovement=" + accelMovement
2142 + " accel=" + accel);
2143 if (accelMovement > movement) {
2144 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2145 + keycode);
2146 movement--;
2147 deliverKeyEvent(new KeyEvent(curTime, curTime,
2148 KeyEvent.ACTION_MULTIPLE, keycode,
2149 accelMovement-movement, metastate), false);
2150 }
2151 while (movement > 0) {
2152 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2153 + keycode);
2154 movement--;
2155 curTime = SystemClock.uptimeMillis();
2156 deliverKeyEvent(new KeyEvent(curTime, curTime,
2157 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2158 deliverKeyEvent(new KeyEvent(curTime, curTime,
2159 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2160 }
2161 mLastTrackballTime = curTime;
2162 }
2163 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002164 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 try {
2166 sWindowSession.finishKey(mWindow);
2167 } catch (RemoteException e) {
2168 }
2169 if (event != null) {
2170 event.recycle();
2171 }
2172 }
2173 // Let the exception fall through -- the looper will catch
2174 // it and take care of the bad app for us.
2175 }
2176 }
2177
2178 /**
2179 * @param keyCode The key code
2180 * @return True if the key is directional.
2181 */
2182 static boolean isDirectional(int keyCode) {
2183 switch (keyCode) {
2184 case KeyEvent.KEYCODE_DPAD_LEFT:
2185 case KeyEvent.KEYCODE_DPAD_RIGHT:
2186 case KeyEvent.KEYCODE_DPAD_UP:
2187 case KeyEvent.KEYCODE_DPAD_DOWN:
2188 return true;
2189 }
2190 return false;
2191 }
2192
2193 /**
2194 * Returns true if this key is a keyboard key.
2195 * @param keyEvent The key event.
2196 * @return whether this key is a keyboard key.
2197 */
2198 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2199 final int convertedKey = keyEvent.getUnicodeChar();
2200 return convertedKey > 0;
2201 }
2202
2203
2204
2205 /**
2206 * See if the key event means we should leave touch mode (and leave touch
2207 * mode if so).
2208 * @param event The key event.
2209 * @return Whether this key event should be consumed (meaning the act of
2210 * leaving touch mode alone is considered the event).
2211 */
2212 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2213 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2214 return false;
2215 }
2216 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2217 return false;
2218 }
2219
2220 // only relevant if we are in touch mode
2221 if (!mAttachInfo.mInTouchMode) {
2222 return false;
2223 }
2224
2225 // if something like an edit text has focus and the user is typing,
2226 // leave touch mode
2227 //
2228 // note: the condition of not being a keyboard key is kind of a hacky
2229 // approximation of whether we think the focused view will want the
2230 // key; if we knew for sure whether the focused view would consume
2231 // the event, that would be better.
2232 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2233 mFocusedView = mView.findFocus();
2234 if ((mFocusedView instanceof ViewGroup)
2235 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2236 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2237 // something has focus, but is holding it weakly as a container
2238 return false;
2239 }
2240 if (ensureTouchMode(false)) {
2241 throw new IllegalStateException("should not have changed focus "
2242 + "when leaving touch mode while a view has focus.");
2243 }
2244 return false;
2245 }
2246
2247 if (isDirectional(event.getKeyCode())) {
2248 // no view has focus, so we leave touch mode (and find something
2249 // to give focus to). the event is consumed if we were able to
2250 // find something to give focus to.
2251 return ensureTouchMode(false);
2252 }
2253 return false;
2254 }
2255
2256 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002257 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 */
2259 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002260 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 if (ev == null ||
2262 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2263 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 }
Romain Guy8506ab42009-06-11 17:35:47 -07002265
2266 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 sb.append(ev.getDownTime()).append(',');
2268 sb.append(ev.getEventTime()).append(',');
2269 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002270 sb.append(ev.getX()).append(',');
2271 sb.append(ev.getY()).append(',');
2272 sb.append(ev.getPressure()).append(',');
2273 sb.append(ev.getSize()).append(',');
2274 sb.append(ev.getMetaState()).append(',');
2275 sb.append(ev.getXPrecision()).append(',');
2276 sb.append(ev.getYPrecision()).append(',');
2277 sb.append(ev.getDeviceId()).append(',');
2278 sb.append(ev.getEdgeFlags());
2279 Log.d(TAG, sb.toString());
2280 }
2281 /**
2282 * log motion events
2283 */
2284 private static void captureKeyLog(String subTag, KeyEvent ev) {
2285 //check dynamic switch
2286 if (ev == null ||
2287 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2288 return;
2289 }
2290 StringBuilder sb = new StringBuilder(subTag + ": ");
2291 sb.append(ev.getDownTime()).append(',');
2292 sb.append(ev.getEventTime()).append(',');
2293 sb.append(ev.getAction()).append(',');
2294 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 sb.append(ev.getRepeatCount()).append(',');
2296 sb.append(ev.getMetaState()).append(',');
2297 sb.append(ev.getDeviceId()).append(',');
2298 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002299 Log.d(TAG, sb.toString());
2300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301
2302 int enqueuePendingEvent(Object event, boolean sendDone) {
2303 int seq = mPendingEventSeq+1;
2304 if (seq < 0) seq = 0;
2305 mPendingEventSeq = seq;
2306 mPendingEvents.put(seq, event);
2307 return sendDone ? seq : -seq;
2308 }
2309
2310 Object retrievePendingEvent(int seq) {
2311 if (seq < 0) seq = -seq;
2312 Object event = mPendingEvents.get(seq);
2313 if (event != null) {
2314 mPendingEvents.remove(seq);
2315 }
2316 return event;
2317 }
Romain Guy8506ab42009-06-11 17:35:47 -07002318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2320 // If mView is null, we just consume the key event because it doesn't
2321 // make sense to do anything else with it.
2322 boolean handled = mView != null
2323 ? mView.dispatchKeyEventPreIme(event) : true;
2324 if (handled) {
2325 if (sendDone) {
2326 if (LOCAL_LOGV) Log.v(
2327 "ViewRoot", "Telling window manager key is finished");
2328 try {
2329 sWindowSession.finishKey(mWindow);
2330 } catch (RemoteException e) {
2331 }
2332 }
2333 return;
2334 }
2335 // If it is possible for this window to interact with the input
2336 // method window, then we want to first dispatch our key events
2337 // to the input method.
2338 if (mLastWasImTarget) {
2339 InputMethodManager imm = InputMethodManager.peekInstance();
2340 if (imm != null && mView != null) {
2341 int seq = enqueuePendingEvent(event, sendDone);
2342 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2343 + seq + " event=" + event);
2344 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2345 mInputMethodCallback);
2346 return;
2347 }
2348 }
2349 deliverKeyEventToViewHierarchy(event, sendDone);
2350 }
2351
2352 void handleFinishedEvent(int seq, boolean handled) {
2353 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2354 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2355 + " handled=" + handled + " event=" + event);
2356 if (event != null) {
2357 final boolean sendDone = seq >= 0;
2358 if (!handled) {
2359 deliverKeyEventToViewHierarchy(event, sendDone);
2360 return;
2361 } else if (sendDone) {
2362 if (LOCAL_LOGV) Log.v(
2363 "ViewRoot", "Telling window manager key is finished");
2364 try {
2365 sWindowSession.finishKey(mWindow);
2366 } catch (RemoteException e) {
2367 }
2368 } else {
2369 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2370 + " handled=" + handled + " ev=" + event
2371 + ") neither delivering nor finishing key");
2372 }
2373 }
2374 }
Romain Guy8506ab42009-06-11 17:35:47 -07002375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2377 try {
2378 if (mView != null && mAdded) {
2379 final int action = event.getAction();
2380 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2381
2382 if (checkForLeavingTouchModeAndConsume(event)) {
2383 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002384 }
2385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 if (Config.LOGV) {
2387 captureKeyLog("captureDispatchKeyEvent", event);
2388 }
2389 boolean keyHandled = mView.dispatchKeyEvent(event);
2390
2391 if (!keyHandled && isDown) {
2392 int direction = 0;
2393 switch (event.getKeyCode()) {
2394 case KeyEvent.KEYCODE_DPAD_LEFT:
2395 direction = View.FOCUS_LEFT;
2396 break;
2397 case KeyEvent.KEYCODE_DPAD_RIGHT:
2398 direction = View.FOCUS_RIGHT;
2399 break;
2400 case KeyEvent.KEYCODE_DPAD_UP:
2401 direction = View.FOCUS_UP;
2402 break;
2403 case KeyEvent.KEYCODE_DPAD_DOWN:
2404 direction = View.FOCUS_DOWN;
2405 break;
2406 }
2407
2408 if (direction != 0) {
2409
2410 View focused = mView != null ? mView.findFocus() : null;
2411 if (focused != null) {
2412 View v = focused.focusSearch(direction);
2413 boolean focusPassed = false;
2414 if (v != null && v != focused) {
2415 // do the math the get the interesting rect
2416 // of previous focused into the coord system of
2417 // newly focused view
2418 focused.getFocusedRect(mTempRect);
2419 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2420 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2421 focusPassed = v.requestFocus(direction, mTempRect);
2422 }
2423
2424 if (!focusPassed) {
2425 mView.dispatchUnhandledMove(focused, direction);
2426 } else {
2427 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2428 }
2429 }
2430 }
2431 }
2432 }
2433
2434 } finally {
2435 if (sendDone) {
2436 if (LOCAL_LOGV) Log.v(
2437 "ViewRoot", "Telling window manager key is finished");
2438 try {
2439 sWindowSession.finishKey(mWindow);
2440 } catch (RemoteException e) {
2441 }
2442 }
2443 // Let the exception fall through -- the looper will catch
2444 // it and take care of the bad app for us.
2445 }
2446 }
2447
2448 private AudioManager getAudioManager() {
2449 if (mView == null) {
2450 throw new IllegalStateException("getAudioManager called when there is no mView");
2451 }
2452 if (mAudioManager == null) {
2453 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2454 }
2455 return mAudioManager;
2456 }
2457
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002458 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2459 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002460
2461 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002462 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002463 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002464 restore = true;
2465 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002466 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002467 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002468 if (params != null) {
2469 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002470 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002471 int relayoutResult = sWindowSession.relayout(
2472 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002473 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2474 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002475 viewVisibility, insetsPending, mWinFrame,
2476 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002477 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002478 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002479 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002480
2481 if (mTranslator != null) {
2482 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2483 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2484 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002485 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002486 return relayoutResult;
2487 }
Romain Guy8506ab42009-06-11 17:35:47 -07002488
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002489 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 * {@inheritDoc}
2491 */
2492 public void playSoundEffect(int effectId) {
2493 checkThread();
2494
2495 final AudioManager audioManager = getAudioManager();
2496
2497 switch (effectId) {
2498 case SoundEffectConstants.CLICK:
2499 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2500 return;
2501 case SoundEffectConstants.NAVIGATION_DOWN:
2502 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2503 return;
2504 case SoundEffectConstants.NAVIGATION_LEFT:
2505 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2506 return;
2507 case SoundEffectConstants.NAVIGATION_RIGHT:
2508 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2509 return;
2510 case SoundEffectConstants.NAVIGATION_UP:
2511 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2512 return;
2513 default:
2514 throw new IllegalArgumentException("unknown effect id " + effectId +
2515 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2516 }
2517 }
2518
2519 /**
2520 * {@inheritDoc}
2521 */
2522 public boolean performHapticFeedback(int effectId, boolean always) {
2523 try {
2524 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2525 } catch (RemoteException e) {
2526 return false;
2527 }
2528 }
2529
2530 /**
2531 * {@inheritDoc}
2532 */
2533 public View focusSearch(View focused, int direction) {
2534 checkThread();
2535 if (!(mView instanceof ViewGroup)) {
2536 return null;
2537 }
2538 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2539 }
2540
2541 public void debug() {
2542 mView.debug();
2543 }
2544
2545 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002546 if (immediate) {
2547 doDie();
2548 } else {
2549 sendEmptyMessage(DIE);
2550 }
2551 }
2552
2553 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 checkThread();
2555 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2556 synchronized (this) {
2557 if (mAdded && !mFirst) {
2558 int viewVisibility = mView.getVisibility();
2559 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2560 if (mWindowAttributesChanged || viewVisibilityChanged) {
2561 // If layout params have been changed, first give them
2562 // to the window manager to make sure it has the correct
2563 // animation info.
2564 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002565 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2566 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 sWindowSession.finishDrawing(mWindow);
2568 }
2569 } catch (RemoteException e) {
2570 }
2571 }
2572
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002573 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 if (mAdded) {
2576 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002577 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579 }
2580 }
2581
2582 public void dispatchFinishedEvent(int seq, boolean handled) {
2583 Message msg = obtainMessage(FINISHED_EVENT);
2584 msg.arg1 = seq;
2585 msg.arg2 = handled ? 1 : 0;
2586 sendMessage(msg);
2587 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 public void dispatchResized(int w, int h, Rect coveredInsets,
2590 Rect visibleInsets, boolean reportDraw) {
2591 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2592 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2593 + " visibleInsets=" + visibleInsets.toShortString()
2594 + " reportDraw=" + reportDraw);
2595 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002596 if (mTranslator != null) {
2597 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2598 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2599 w *= mTranslator.applicationInvertedScale;
2600 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002601 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002602 msg.arg1 = w;
2603 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2605 sendMessage(msg);
2606 }
2607
2608 public void dispatchKey(KeyEvent event) {
2609 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2610 //noinspection ConstantConditions
2611 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2612 if (Config.LOGD) Log.d("keydisp",
2613 "===================================================");
2614 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2615 debug();
2616
2617 if (Config.LOGD) Log.d("keydisp",
2618 "===================================================");
2619 }
2620 }
2621
2622 Message msg = obtainMessage(DISPATCH_KEY);
2623 msg.obj = event;
2624
2625 if (LOCAL_LOGV) Log.v(
2626 "ViewRoot", "sending key " + event + " to " + mView);
2627
2628 sendMessageAtTime(msg, event.getEventTime());
2629 }
2630
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002631 public void dispatchPointer(MotionEvent event, long eventTime,
2632 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 Message msg = obtainMessage(DISPATCH_POINTER);
2634 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002635 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 sendMessageAtTime(msg, eventTime);
2637 }
2638
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002639 public void dispatchTrackball(MotionEvent event, long eventTime,
2640 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2642 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002643 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 sendMessageAtTime(msg, eventTime);
2645 }
2646
2647 public void dispatchAppVisibility(boolean visible) {
2648 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2649 msg.arg1 = visible ? 1 : 0;
2650 sendMessage(msg);
2651 }
2652
2653 public void dispatchGetNewSurface() {
2654 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2655 sendMessage(msg);
2656 }
2657
2658 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2659 Message msg = Message.obtain();
2660 msg.what = WINDOW_FOCUS_CHANGED;
2661 msg.arg1 = hasFocus ? 1 : 0;
2662 msg.arg2 = inTouchMode ? 1 : 0;
2663 sendMessage(msg);
2664 }
2665
Dianne Hackbornffa42482009-09-23 22:20:11 -07002666 public void dispatchCloseSystemDialogs(String reason) {
2667 Message msg = Message.obtain();
2668 msg.what = CLOSE_SYSTEM_DIALOGS;
2669 msg.obj = reason;
2670 sendMessage(msg);
2671 }
2672
svetoslavganov75986cf2009-05-14 22:28:01 -07002673 /**
2674 * The window is getting focus so if there is anything focused/selected
2675 * send an {@link AccessibilityEvent} to announce that.
2676 */
2677 private void sendAccessibilityEvents() {
2678 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2679 return;
2680 }
2681 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2682 View focusedView = mView.findFocus();
2683 if (focusedView != null && focusedView != mView) {
2684 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2685 }
2686 }
2687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 public boolean showContextMenuForChild(View originalView) {
2689 return false;
2690 }
2691
2692 public void createContextMenu(ContextMenu menu) {
2693 }
2694
2695 public void childDrawableStateChanged(View child) {
2696 }
2697
2698 protected Rect getWindowFrame() {
2699 return mWinFrame;
2700 }
2701
2702 void checkThread() {
2703 if (mThread != Thread.currentThread()) {
2704 throw new CalledFromWrongThreadException(
2705 "Only the original thread that created a view hierarchy can touch its views.");
2706 }
2707 }
2708
2709 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2710 // ViewRoot never intercepts touch event, so this can be a no-op
2711 }
2712
2713 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2714 boolean immediate) {
2715 return scrollToRectOrFocus(rectangle, immediate);
2716 }
Romain Guy8506ab42009-06-11 17:35:47 -07002717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 static class InputMethodCallback extends IInputMethodCallback.Stub {
2719 private WeakReference<ViewRoot> mViewRoot;
2720
2721 public InputMethodCallback(ViewRoot viewRoot) {
2722 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2723 }
Romain Guy8506ab42009-06-11 17:35:47 -07002724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 public void finishedEvent(int seq, boolean handled) {
2726 final ViewRoot viewRoot = mViewRoot.get();
2727 if (viewRoot != null) {
2728 viewRoot.dispatchFinishedEvent(seq, handled);
2729 }
2730 }
2731
2732 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2733 // Stub -- not for use in the client.
2734 }
2735 }
Romain Guy8506ab42009-06-11 17:35:47 -07002736
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002737 static class EventCompletion extends Handler {
2738 final IWindow mWindow;
2739 final KeyEvent mKeyEvent;
2740 final boolean mIsPointer;
2741 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002742
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002743 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2744 boolean isPointer, MotionEvent motion) {
2745 super(looper);
2746 mWindow = window;
2747 mKeyEvent = key;
2748 mIsPointer = isPointer;
2749 mMotionEvent = motion;
2750 sendEmptyMessage(0);
2751 }
Romain Guy8506ab42009-06-11 17:35:47 -07002752
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002753 @Override
2754 public void handleMessage(Message msg) {
2755 if (mKeyEvent != null) {
2756 try {
2757 sWindowSession.finishKey(mWindow);
2758 } catch (RemoteException e) {
2759 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002760 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002761 boolean didFinish;
2762 MotionEvent event = mMotionEvent;
2763 if (event == null) {
2764 try {
2765 event = sWindowSession.getPendingPointerMove(mWindow);
2766 } catch (RemoteException e) {
2767 }
2768 didFinish = true;
2769 } else {
2770 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2771 }
2772 if (!didFinish) {
2773 try {
2774 sWindowSession.finishKey(mWindow);
2775 } catch (RemoteException e) {
2776 }
2777 }
2778 } else {
2779 MotionEvent event = mMotionEvent;
2780 if (event == null) {
2781 try {
2782 event = sWindowSession.getPendingTrackballMove(mWindow);
2783 } catch (RemoteException e) {
2784 }
2785 } else {
2786 try {
2787 sWindowSession.finishKey(mWindow);
2788 } catch (RemoteException e) {
2789 }
2790 }
2791 }
2792 }
2793 }
Romain Guy8506ab42009-06-11 17:35:47 -07002794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002796 private final WeakReference<ViewRoot> mViewRoot;
2797 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002799 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002801 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 }
2803
2804 public void resized(int w, int h, Rect coveredInsets,
2805 Rect visibleInsets, boolean reportDraw) {
2806 final ViewRoot viewRoot = mViewRoot.get();
2807 if (viewRoot != null) {
2808 viewRoot.dispatchResized(w, h, coveredInsets,
2809 visibleInsets, reportDraw);
2810 }
2811 }
2812
2813 public void dispatchKey(KeyEvent event) {
2814 final ViewRoot viewRoot = mViewRoot.get();
2815 if (viewRoot != null) {
2816 viewRoot.dispatchKey(event);
2817 } else {
2818 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002819 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 }
2821 }
2822
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002823 public void dispatchPointer(MotionEvent event, long eventTime,
2824 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002826 if (viewRoot != null) {
2827 if (MEASURE_LATENCY) {
2828 // Note: eventTime is in milliseconds
2829 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2830 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002831 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002832 } else {
2833 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 }
2835 }
2836
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002837 public void dispatchTrackball(MotionEvent event, long eventTime,
2838 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 final ViewRoot viewRoot = mViewRoot.get();
2840 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002841 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002842 } else {
2843 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 }
2845 }
2846
2847 public void dispatchAppVisibility(boolean visible) {
2848 final ViewRoot viewRoot = mViewRoot.get();
2849 if (viewRoot != null) {
2850 viewRoot.dispatchAppVisibility(visible);
2851 }
2852 }
2853
2854 public void dispatchGetNewSurface() {
2855 final ViewRoot viewRoot = mViewRoot.get();
2856 if (viewRoot != null) {
2857 viewRoot.dispatchGetNewSurface();
2858 }
2859 }
2860
2861 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2862 final ViewRoot viewRoot = mViewRoot.get();
2863 if (viewRoot != null) {
2864 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2865 }
2866 }
2867
2868 private static int checkCallingPermission(String permission) {
2869 if (!Process.supportsProcesses()) {
2870 return PackageManager.PERMISSION_GRANTED;
2871 }
2872
2873 try {
2874 return ActivityManagerNative.getDefault().checkPermission(
2875 permission, Binder.getCallingPid(), Binder.getCallingUid());
2876 } catch (RemoteException e) {
2877 return PackageManager.PERMISSION_DENIED;
2878 }
2879 }
2880
2881 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2882 final ViewRoot viewRoot = mViewRoot.get();
2883 if (viewRoot != null) {
2884 final View view = viewRoot.mView;
2885 if (view != null) {
2886 if (checkCallingPermission(Manifest.permission.DUMP) !=
2887 PackageManager.PERMISSION_GRANTED) {
2888 throw new SecurityException("Insufficient permissions to invoke"
2889 + " executeCommand() from pid=" + Binder.getCallingPid()
2890 + ", uid=" + Binder.getCallingUid());
2891 }
2892
2893 OutputStream clientStream = null;
2894 try {
2895 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2896 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2897 } catch (IOException e) {
2898 e.printStackTrace();
2899 } finally {
2900 if (clientStream != null) {
2901 try {
2902 clientStream.close();
2903 } catch (IOException e) {
2904 e.printStackTrace();
2905 }
2906 }
2907 }
2908 }
2909 }
2910 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002911
Dianne Hackbornffa42482009-09-23 22:20:11 -07002912 public void closeSystemDialogs(String reason) {
2913 final ViewRoot viewRoot = mViewRoot.get();
2914 if (viewRoot != null) {
2915 viewRoot.dispatchCloseSystemDialogs(reason);
2916 }
2917 }
2918
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002919 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2920 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002921 if (sync) {
2922 try {
2923 sWindowSession.wallpaperOffsetsComplete(asBinder());
2924 } catch (RemoteException e) {
2925 }
2926 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002927 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002928
2929 public void dispatchWallpaperCommand(String action, int x, int y,
2930 int z, Bundle extras, boolean sync) {
2931 if (sync) {
2932 try {
2933 sWindowSession.wallpaperCommandComplete(asBinder(), null);
2934 } catch (RemoteException e) {
2935 }
2936 }
2937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 }
2939
2940 /**
2941 * Maintains state information for a single trackball axis, generating
2942 * discrete (DPAD) movements based on raw trackball motion.
2943 */
2944 static final class TrackballAxis {
2945 /**
2946 * The maximum amount of acceleration we will apply.
2947 */
2948 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 /**
2951 * The maximum amount of time (in milliseconds) between events in order
2952 * for us to consider the user to be doing fast trackball movements,
2953 * and thus apply an acceleration.
2954 */
2955 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 /**
2958 * Scaling factor to the time (in milliseconds) between events to how
2959 * much to multiple/divide the current acceleration. When movement
2960 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2961 * FAST_MOVE_TIME it divides it.
2962 */
2963 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 float position;
2966 float absPosition;
2967 float acceleration = 1;
2968 long lastMoveTime = 0;
2969 int step;
2970 int dir;
2971 int nonAccelMovement;
2972
2973 void reset(int _step) {
2974 position = 0;
2975 acceleration = 1;
2976 lastMoveTime = 0;
2977 step = _step;
2978 dir = 0;
2979 }
2980
2981 /**
2982 * Add trackball movement into the state. If the direction of movement
2983 * has been reversed, the state is reset before adding the
2984 * movement (so that you don't have to compensate for any previously
2985 * collected movement before see the result of the movement in the
2986 * new direction).
2987 *
2988 * @return Returns the absolute value of the amount of movement
2989 * collected so far.
2990 */
2991 float collect(float off, long time, String axis) {
2992 long normTime;
2993 if (off > 0) {
2994 normTime = (long)(off * FAST_MOVE_TIME);
2995 if (dir < 0) {
2996 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2997 position = 0;
2998 step = 0;
2999 acceleration = 1;
3000 lastMoveTime = 0;
3001 }
3002 dir = 1;
3003 } else if (off < 0) {
3004 normTime = (long)((-off) * FAST_MOVE_TIME);
3005 if (dir > 0) {
3006 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3007 position = 0;
3008 step = 0;
3009 acceleration = 1;
3010 lastMoveTime = 0;
3011 }
3012 dir = -1;
3013 } else {
3014 normTime = 0;
3015 }
Romain Guy8506ab42009-06-11 17:35:47 -07003016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 // The number of milliseconds between each movement that is
3018 // considered "normal" and will not result in any acceleration
3019 // or deceleration, scaled by the offset we have here.
3020 if (normTime > 0) {
3021 long delta = time - lastMoveTime;
3022 lastMoveTime = time;
3023 float acc = acceleration;
3024 if (delta < normTime) {
3025 // The user is scrolling rapidly, so increase acceleration.
3026 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3027 if (scale > 1) acc *= scale;
3028 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3029 + off + " normTime=" + normTime + " delta=" + delta
3030 + " scale=" + scale + " acc=" + acc);
3031 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3032 } else {
3033 // The user is scrolling slowly, so decrease acceleration.
3034 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3035 if (scale > 1) acc /= scale;
3036 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3037 + off + " normTime=" + normTime + " delta=" + delta
3038 + " scale=" + scale + " acc=" + acc);
3039 acceleration = acc > 1 ? acc : 1;
3040 }
3041 }
3042 position += off;
3043 return (absPosition = Math.abs(position));
3044 }
3045
3046 /**
3047 * Generate the number of discrete movement events appropriate for
3048 * the currently collected trackball movement.
3049 *
3050 * @param precision The minimum movement required to generate the
3051 * first discrete movement.
3052 *
3053 * @return Returns the number of discrete movements, either positive
3054 * or negative, or 0 if there is not enough trackball movement yet
3055 * for a discrete movement.
3056 */
3057 int generate(float precision) {
3058 int movement = 0;
3059 nonAccelMovement = 0;
3060 do {
3061 final int dir = position >= 0 ? 1 : -1;
3062 switch (step) {
3063 // If we are going to execute the first step, then we want
3064 // to do this as soon as possible instead of waiting for
3065 // a full movement, in order to make things look responsive.
3066 case 0:
3067 if (absPosition < precision) {
3068 return movement;
3069 }
3070 movement += dir;
3071 nonAccelMovement += dir;
3072 step = 1;
3073 break;
3074 // If we have generated the first movement, then we need
3075 // to wait for the second complete trackball motion before
3076 // generating the second discrete movement.
3077 case 1:
3078 if (absPosition < 2) {
3079 return movement;
3080 }
3081 movement += dir;
3082 nonAccelMovement += dir;
3083 position += dir > 0 ? -2 : 2;
3084 absPosition = Math.abs(position);
3085 step = 2;
3086 break;
3087 // After the first two, we generate discrete movements
3088 // consistently with the trackball, applying an acceleration
3089 // if the trackball is moving quickly. This is a simple
3090 // acceleration on top of what we already compute based
3091 // on how quickly the wheel is being turned, to apply
3092 // a longer increasing acceleration to continuous movement
3093 // in one direction.
3094 default:
3095 if (absPosition < 1) {
3096 return movement;
3097 }
3098 movement += dir;
3099 position += dir >= 0 ? -1 : 1;
3100 absPosition = Math.abs(position);
3101 float acc = acceleration;
3102 acc *= 1.1f;
3103 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3104 break;
3105 }
3106 } while (true);
3107 }
3108 }
3109
3110 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3111 public CalledFromWrongThreadException(String msg) {
3112 super(msg);
3113 }
3114 }
3115
3116 private SurfaceHolder mHolder = new SurfaceHolder() {
3117 // we only need a SurfaceHolder for opengl. it would be nice
3118 // to implement everything else though, especially the callback
3119 // support (opengl doesn't make use of it right now, but eventually
3120 // will).
3121 public Surface getSurface() {
3122 return mSurface;
3123 }
3124
3125 public boolean isCreating() {
3126 return false;
3127 }
3128
3129 public void addCallback(Callback callback) {
3130 }
3131
3132 public void removeCallback(Callback callback) {
3133 }
3134
3135 public void setFixedSize(int width, int height) {
3136 }
3137
3138 public void setSizeFromLayout() {
3139 }
3140
3141 public void setFormat(int format) {
3142 }
3143
3144 public void setType(int type) {
3145 }
3146
3147 public void setKeepScreenOn(boolean screenOn) {
3148 }
3149
3150 public Canvas lockCanvas() {
3151 return null;
3152 }
3153
3154 public Canvas lockCanvas(Rect dirty) {
3155 return null;
3156 }
3157
3158 public void unlockCanvasAndPost(Canvas canvas) {
3159 }
3160 public Rect getSurfaceFrame() {
3161 return null;
3162 }
3163 };
3164
3165 static RunQueue getRunQueue() {
3166 RunQueue rq = sRunQueues.get();
3167 if (rq != null) {
3168 return rq;
3169 }
3170 rq = new RunQueue();
3171 sRunQueues.set(rq);
3172 return rq;
3173 }
Romain Guy8506ab42009-06-11 17:35:47 -07003174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 /**
3176 * @hide
3177 */
3178 static final class RunQueue {
3179 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3180
3181 void post(Runnable action) {
3182 postDelayed(action, 0);
3183 }
3184
3185 void postDelayed(Runnable action, long delayMillis) {
3186 HandlerAction handlerAction = new HandlerAction();
3187 handlerAction.action = action;
3188 handlerAction.delay = delayMillis;
3189
3190 synchronized (mActions) {
3191 mActions.add(handlerAction);
3192 }
3193 }
3194
3195 void removeCallbacks(Runnable action) {
3196 final HandlerAction handlerAction = new HandlerAction();
3197 handlerAction.action = action;
3198
3199 synchronized (mActions) {
3200 final ArrayList<HandlerAction> actions = mActions;
3201
3202 while (actions.remove(handlerAction)) {
3203 // Keep going
3204 }
3205 }
3206 }
3207
3208 void executeActions(Handler handler) {
3209 synchronized (mActions) {
3210 final ArrayList<HandlerAction> actions = mActions;
3211 final int count = actions.size();
3212
3213 for (int i = 0; i < count; i++) {
3214 final HandlerAction handlerAction = actions.get(i);
3215 handler.postDelayed(handlerAction.action, handlerAction.delay);
3216 }
3217
Romain Guy15df6702009-08-17 20:17:30 -07003218 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 }
3220 }
3221
3222 private static class HandlerAction {
3223 Runnable action;
3224 long delay;
3225
3226 @Override
3227 public boolean equals(Object o) {
3228 if (this == o) return true;
3229 if (o == null || getClass() != o.getClass()) return false;
3230
3231 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 return !(action != null ? !action.equals(that.action) : that.action != null);
3233
3234 }
3235
3236 @Override
3237 public int hashCode() {
3238 int result = action != null ? action.hashCode() : 0;
3239 result = 31 * result + (int) (delay ^ (delay >>> 32));
3240 return result;
3241 }
3242 }
3243 }
3244
3245 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3246
3247 // inform skia to just abandon its texture cache IDs
3248 // doesn't call glDeleteTextures
3249 private static native void nativeAbandonGlCaches();
3250}