blob: 57768515ad482d9fc62e961b23d2b20aa047412e [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;
24import android.graphics.Point;
25import android.graphics.PorterDuff;
26import android.graphics.Rect;
27import android.graphics.Region;
28import android.os.*;
29import android.os.Process;
30import android.os.SystemProperties;
31import android.util.AndroidRuntimeException;
32import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070033import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.Log;
35import android.util.EventLog;
36import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070038import android.view.accessibility.AccessibilityEvent;
39import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.view.inputmethod.InputConnection;
41import android.view.inputmethod.InputMethodManager;
42import android.widget.Scroller;
43import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070044import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.Context;
46import android.app.ActivityManagerNative;
47import android.Manifest;
48import android.media.AudioManager;
49
50import java.lang.ref.WeakReference;
51import java.io.IOException;
52import java.io.OutputStream;
53import java.util.ArrayList;
54
55import javax.microedition.khronos.egl.*;
56import javax.microedition.khronos.opengles.*;
57import static javax.microedition.khronos.opengles.GL10.*;
58
59/**
60 * The top of a view hierarchy, implementing the needed protocol between View
61 * and the WindowManager. This is for the most part an internal implementation
62 * detail of {@link WindowManagerImpl}.
63 *
64 * {@hide}
65 */
66@SuppressWarnings({"EmptyCatchBlock"})
67public final class ViewRoot extends Handler implements ViewParent,
68 View.AttachInfo.Callbacks {
69 private static final String TAG = "ViewRoot";
70 private static final boolean DBG = false;
71 @SuppressWarnings({"ConstantConditionalExpression"})
72 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
73 /** @noinspection PointlessBooleanExpression*/
74 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
75 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
76 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
77 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
78 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
79 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
80 private static final boolean WATCH_POINTER = false;
81
Michael Chan53071d62009-05-13 17:29:48 -070082 private static final boolean MEASURE_LATENCY = false;
83 private static LatencyTimer lt;
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 /**
86 * Maximum time we allow the user to roll the trackball enough to generate
87 * a key event, before resetting the counters.
88 */
89 static final int MAX_TRACKBALL_DELAY = 250;
90
91 static long sInstanceCount = 0;
92
93 static IWindowSession sWindowSession;
94
95 static final Object mStaticInit = new Object();
96 static boolean mInitialized = false;
97
98 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
99
Romain Guy8506ab42009-06-11 17:35:47 -0700100 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 long mLastTrackballTime = 0;
103 final TrackballAxis mTrackballAxisX = new TrackballAxis();
104 final TrackballAxis mTrackballAxisY = new TrackballAxis();
105
106 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 final InputMethodCallback mInputMethodCallback;
109 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
110 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 final Thread mThread;
113
114 final WindowLeaked mLocation;
115
116 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
117
118 final W mWindow;
119
120 View mView;
121 View mFocusedView;
122 View mRealFocusedView; // this is not set to null in touch mode
123 int mViewVisibility;
124 boolean mAppVisible = true;
125
126 final Region mTransparentRegion;
127 final Region mPreviousTransparentRegion;
128
129 int mWidth;
130 int mHeight;
131 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700132 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700133
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700134 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
136 final View.AttachInfo mAttachInfo;
137
138 final Rect mTempRect; // used in the transaction to not thrash the heap.
139 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 boolean mTraversalScheduled;
142 boolean mWillDrawSoon;
143 boolean mLayoutRequested;
144 boolean mFirst;
145 boolean mReportNextDraw;
146 boolean mFullRedrawNeeded;
147 boolean mNewSurfaceNeeded;
148 boolean mHasHadWindowFocus;
149 boolean mLastWasImTarget;
150
151 boolean mWindowAttributesChanged = false;
152
153 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700154 // Surface can never be reassigned or cleared (use Surface.clear()).
155 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157 boolean mAdded;
158 boolean mAddedTouchMode;
159
160 /*package*/ int mAddNesting;
161
162 // These are accessed by multiple threads.
163 final Rect mWinFrame; // frame given by window manager.
164
165 final Rect mPendingVisibleInsets = new Rect();
166 final Rect mPendingContentInsets = new Rect();
167 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
168 = new ViewTreeObserver.InternalInsetsInfo();
169
170 boolean mScrollMayChange;
171 int mSoftInputMode;
172 View mLastScrolledFocus;
173 int mScrollY;
174 int mCurScrollY;
175 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 EGL10 mEgl;
178 EGLDisplay mEglDisplay;
179 EGLContext mEglContext;
180 EGLSurface mEglSurface;
181 GL11 mGL;
182 Canvas mGlCanvas;
183 boolean mUseGL;
184 boolean mGlWanted;
185
Romain Guy8506ab42009-06-11 17:35:47 -0700186 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 /**
189 * see {@link #playSoundEffect(int)}
190 */
191 AudioManager mAudioManager;
192
193 private final float mDensity;
194
195 public ViewRoot(Context context) {
196 super();
197
Michael Chan53071d62009-05-13 17:29:48 -0700198 if (MEASURE_LATENCY && lt == null) {
199 lt = new LatencyTimer(100, 1000);
200 }
201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 ++sInstanceCount;
203
204 // Initialize the statics when this class is first instantiated. This is
205 // done here instead of in the static block because Zygote does not
206 // allow the spawning of threads.
207 synchronized (mStaticInit) {
208 if (!mInitialized) {
209 try {
210 InputMethodManager imm = InputMethodManager.getInstance(context);
211 sWindowSession = IWindowManager.Stub.asInterface(
212 ServiceManager.getService("window"))
213 .openSession(imm.getClient(), imm.getInputContext());
214 mInitialized = true;
215 } catch (RemoteException e) {
216 }
217 }
218 }
219
220 mThread = Thread.currentThread();
221 mLocation = new WindowLeaked(null);
222 mLocation.fillInStackTrace();
223 mWidth = -1;
224 mHeight = -1;
225 mDirty = new Rect();
226 mTempRect = new Rect();
227 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700229 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 mInputMethodCallback = new InputMethodCallback(this);
231 mViewVisibility = View.GONE;
232 mTransparentRegion = new Region();
233 mPreviousTransparentRegion = new Region();
234 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 mAdded = false;
236 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
237 mViewConfiguration = ViewConfiguration.get(context);
238 mDensity = context.getResources().getDisplayMetrics().density;
239 }
240
241 @Override
242 protected void finalize() throws Throwable {
243 super.finalize();
244 --sInstanceCount;
245 }
246
247 public static long getInstanceCount() {
248 return sInstanceCount;
249 }
250
251 // FIXME for perf testing only
252 private boolean mProfile = false;
253
254 /**
255 * Call this to profile the next traversal call.
256 * FIXME for perf testing only. Remove eventually
257 */
258 public void profile() {
259 mProfile = true;
260 }
261
262 /**
263 * Indicates whether we are in touch mode. Calling this method triggers an IPC
264 * call and should be avoided whenever possible.
265 *
266 * @return True, if the device is in touch mode, false otherwise.
267 *
268 * @hide
269 */
270 static boolean isInTouchMode() {
271 if (mInitialized) {
272 try {
273 return sWindowSession.getInTouchMode();
274 } catch (RemoteException e) {
275 }
276 }
277 return false;
278 }
279
280 private void initializeGL() {
281 initializeGLInner();
282 int err = mEgl.eglGetError();
283 if (err != EGL10.EGL_SUCCESS) {
284 // give-up on using GL
285 destroyGL();
286 mGlWanted = false;
287 }
288 }
289
290 private void initializeGLInner() {
291 final EGL10 egl = (EGL10) EGLContext.getEGL();
292 mEgl = egl;
293
294 /*
295 * Get to the default display.
296 */
297 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
298 mEglDisplay = eglDisplay;
299
300 /*
301 * We can now initialize EGL for that display
302 */
303 int[] version = new int[2];
304 egl.eglInitialize(eglDisplay, version);
305
306 /*
307 * Specify a configuration for our opengl session
308 * and grab the first configuration that matches is
309 */
310 final int[] configSpec = {
311 EGL10.EGL_RED_SIZE, 5,
312 EGL10.EGL_GREEN_SIZE, 6,
313 EGL10.EGL_BLUE_SIZE, 5,
314 EGL10.EGL_DEPTH_SIZE, 0,
315 EGL10.EGL_NONE
316 };
317 final EGLConfig[] configs = new EGLConfig[1];
318 final int[] num_config = new int[1];
319 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
320 final EGLConfig config = configs[0];
321
322 /*
323 * Create an OpenGL ES context. This must be done only once, an
324 * OpenGL context is a somewhat heavy object.
325 */
326 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
327 EGL10.EGL_NO_CONTEXT, null);
328 mEglContext = context;
329
330 /*
331 * Create an EGL surface we can render into.
332 */
333 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
334 mEglSurface = surface;
335
336 /*
337 * Before we can issue GL commands, we need to make sure
338 * the context is current and bound to a surface.
339 */
340 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
341
342 /*
343 * Get to the appropriate GL interface.
344 * This is simply done by casting the GL context to either
345 * GL10 or GL11.
346 */
347 final GL11 gl = (GL11) context.getGL();
348 mGL = gl;
349 mGlCanvas = new Canvas(gl);
350 mUseGL = true;
351 }
352
353 private void destroyGL() {
354 // inform skia that the context is gone
355 nativeAbandonGlCaches();
356
357 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
358 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
359 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
360 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
361 mEgl.eglTerminate(mEglDisplay);
362 mEglContext = null;
363 mEglSurface = null;
364 mEglDisplay = null;
365 mEgl = null;
366 mGlCanvas = null;
367 mGL = null;
368 mUseGL = false;
369 }
370
371 private void checkEglErrors() {
372 if (mUseGL) {
373 int err = mEgl.eglGetError();
374 if (err != EGL10.EGL_SUCCESS) {
375 // something bad has happened revert to
376 // normal rendering.
377 destroyGL();
378 if (err != EGL11.EGL_CONTEXT_LOST) {
379 // we'll try again if it was context lost
380 mGlWanted = false;
381 }
382 }
383 }
384 }
385
386 /**
387 * We have one child
388 */
389 public void setView(View view, WindowManager.LayoutParams attrs,
390 View panelParentView) {
391 synchronized (this) {
392 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700393 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700394 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700395 attrs = mWindowAttributes;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700396
397 CompatibilityInfo compatibilityInfo =
398 mView.getContext().getResources().getCompatibilityInfo();
399 mTranslator = compatibilityInfo.getTranslator(attrs);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700400 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700401 if (attrs != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700402 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700403 attrs.backup();
404 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700405 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700406 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
407
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700408 if (!compatibilityInfo.supportsScreen()) {
409 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
410 }
411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 mSoftInputMode = attrs.softInputMode;
413 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 mAttachInfo.mRootView = view;
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700415 mAttachInfo.mScalingRequired = mTranslator == null ? false : true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700416 mAttachInfo.mApplicationScale =
417 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 if (panelParentView != null) {
419 mAttachInfo.mPanelParentWindowToken
420 = panelParentView.getApplicationWindowToken();
421 }
422 mAdded = true;
423 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 // Schedule the first layout -before- adding to the window
426 // manager, to make sure we do the relayout before receiving
427 // any other events from the system.
428 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700430 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 getHostVisibility(), mAttachInfo.mContentInsets);
432 } catch (RemoteException e) {
433 mAdded = false;
434 mView = null;
435 mAttachInfo.mRootView = null;
436 unscheduleTraversals();
437 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700438 } finally {
439 if (restore) {
440 attrs.restore();
441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700443
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700444 if (mTranslator != null) {
445 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 mPendingContentInsets.set(mAttachInfo.mContentInsets);
448 mPendingVisibleInsets.set(0, 0, 0, 0);
449 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
450 if (res < WindowManagerImpl.ADD_OKAY) {
451 mView = null;
452 mAttachInfo.mRootView = null;
453 mAdded = false;
454 unscheduleTraversals();
455 switch (res) {
456 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
457 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
458 throw new WindowManagerImpl.BadTokenException(
459 "Unable to add window -- token " + attrs.token
460 + " is not valid; is your activity running?");
461 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
462 throw new WindowManagerImpl.BadTokenException(
463 "Unable to add window -- token " + attrs.token
464 + " is not for an application");
465 case WindowManagerImpl.ADD_APP_EXITING:
466 throw new WindowManagerImpl.BadTokenException(
467 "Unable to add window -- app for token " + attrs.token
468 + " is exiting");
469 case WindowManagerImpl.ADD_DUPLICATE_ADD:
470 throw new WindowManagerImpl.BadTokenException(
471 "Unable to add window -- window " + mWindow
472 + " has already been added");
473 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
474 // Silently ignore -- we would have just removed it
475 // right away, anyway.
476 return;
477 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
478 throw new WindowManagerImpl.BadTokenException(
479 "Unable to add window " + mWindow +
480 " -- another window of this type already exists");
481 case WindowManagerImpl.ADD_PERMISSION_DENIED:
482 throw new WindowManagerImpl.BadTokenException(
483 "Unable to add window " + mWindow +
484 " -- permission denied for this window type");
485 }
486 throw new RuntimeException(
487 "Unable to add window -- unknown error code " + res);
488 }
489 view.assignParent(this);
490 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
491 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
492 }
493 }
494 }
495
496 public View getView() {
497 return mView;
498 }
499
500 final WindowLeaked getLocation() {
501 return mLocation;
502 }
503
504 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
505 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700506 int oldSoftInputMode = mWindowAttributes.softInputMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 if (newView) {
510 mSoftInputMode = attrs.softInputMode;
511 requestLayout();
512 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700513 // Don't lose the mode we last auto-computed.
514 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
515 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
516 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
517 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
518 | (oldSoftInputMode
519 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 mWindowAttributesChanged = true;
522 scheduleTraversals();
523 }
524 }
525
526 void handleAppVisibility(boolean visible) {
527 if (mAppVisible != visible) {
528 mAppVisible = visible;
529 scheduleTraversals();
530 }
531 }
532
533 void handleGetNewSurface() {
534 mNewSurfaceNeeded = true;
535 mFullRedrawNeeded = true;
536 scheduleTraversals();
537 }
538
539 /**
540 * {@inheritDoc}
541 */
542 public void requestLayout() {
543 checkThread();
544 mLayoutRequested = true;
545 scheduleTraversals();
546 }
547
548 /**
549 * {@inheritDoc}
550 */
551 public boolean isLayoutRequested() {
552 return mLayoutRequested;
553 }
554
555 public void invalidateChild(View child, Rect dirty) {
556 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700557 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
558 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700560 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700561 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700562 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700563 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700564 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700565 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700566 }
Romain Guy1e095972009-07-07 11:22:45 -0700567 if (mAttachInfo.mScalingRequired) {
568 dirty.inset(-1, -1);
569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571 mDirty.union(dirty);
572 if (!mWillDrawSoon) {
573 scheduleTraversals();
574 }
575 }
576
577 public ViewParent getParent() {
578 return null;
579 }
580
581 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
582 invalidateChild(null, dirty);
583 return null;
584 }
585
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700586 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 if (child != mView) {
588 throw new RuntimeException("child is not mine, honest!");
589 }
590 // Note: don't apply scroll offset, because we want to know its
591 // visibility in the virtual canvas being given to the view hierarchy.
592 return r.intersect(0, 0, mWidth, mHeight);
593 }
594
595 public void bringChildToFront(View child) {
596 }
597
598 public void scheduleTraversals() {
599 if (!mTraversalScheduled) {
600 mTraversalScheduled = true;
601 sendEmptyMessage(DO_TRAVERSAL);
602 }
603 }
604
605 public void unscheduleTraversals() {
606 if (mTraversalScheduled) {
607 mTraversalScheduled = false;
608 removeMessages(DO_TRAVERSAL);
609 }
610 }
611
612 int getHostVisibility() {
613 return mAppVisible ? mView.getVisibility() : View.GONE;
614 }
Romain Guy8506ab42009-06-11 17:35:47 -0700615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 private void performTraversals() {
617 // cache mView since it is used so much below...
618 final View host = mView;
619
620 if (DBG) {
621 System.out.println("======================================");
622 System.out.println("performTraversals");
623 host.debug();
624 }
625
626 if (host == null || !mAdded)
627 return;
628
629 mTraversalScheduled = false;
630 mWillDrawSoon = true;
631 boolean windowResizesToFitContent = false;
632 boolean fullRedrawNeeded = mFullRedrawNeeded;
633 boolean newSurface = false;
634 WindowManager.LayoutParams lp = mWindowAttributes;
635
636 int desiredWindowWidth;
637 int desiredWindowHeight;
638 int childWidthMeasureSpec;
639 int childHeightMeasureSpec;
640
641 final View.AttachInfo attachInfo = mAttachInfo;
642
643 final int viewVisibility = getHostVisibility();
644 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
645 || mNewSurfaceNeeded;
646
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700647 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 WindowManager.LayoutParams params = null;
650 if (mWindowAttributesChanged) {
651 mWindowAttributesChanged = false;
652 params = lp;
653 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700654 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 if (mFirst) {
656 fullRedrawNeeded = true;
657 mLayoutRequested = true;
658
Romain Guy8506ab42009-06-11 17:35:47 -0700659 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700660 mView.getContext().getResources().getDisplayMetrics();
661 desiredWindowWidth = packageMetrics.widthPixels;
662 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663
664 // For the very first time, tell the view hierarchy that it
665 // is attached to the window. Note that at this point the surface
666 // object is not initialized to its backing store, but soon it
667 // will be (assuming the window is visible).
668 attachInfo.mSurface = mSurface;
669 attachInfo.mHasWindowFocus = false;
670 attachInfo.mWindowVisibility = viewVisibility;
671 attachInfo.mRecomputeGlobalAttributes = false;
672 attachInfo.mKeepScreenOn = false;
673 viewVisibilityChanged = false;
674 host.dispatchAttachedToWindow(attachInfo, 0);
675 getRunQueue().executeActions(attachInfo.mHandler);
676 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700679 desiredWindowWidth = frame.width();
680 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
682 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700683 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 fullRedrawNeeded = true;
685 mLayoutRequested = true;
686 windowResizesToFitContent = true;
687 }
688 }
689
690 if (viewVisibilityChanged) {
691 attachInfo.mWindowVisibility = viewVisibility;
692 host.dispatchWindowVisibilityChanged(viewVisibility);
693 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
694 if (mUseGL) {
695 destroyGL();
696 }
697 }
698 if (viewVisibility == View.GONE) {
699 // After making a window gone, we will count it as being
700 // shown for the first time the next time it gets focus.
701 mHasHadWindowFocus = false;
702 }
703 }
704
705 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 if (mLayoutRequested) {
708 if (mFirst) {
709 host.fitSystemWindows(mAttachInfo.mContentInsets);
710 // make sure touch mode code executes by setting cached value
711 // to opposite of the added touch mode.
712 mAttachInfo.mInTouchMode = !mAddedTouchMode;
713 ensureTouchModeLocally(mAddedTouchMode);
714 } else {
715 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
716 mAttachInfo.mContentInsets.set(mPendingContentInsets);
717 host.fitSystemWindows(mAttachInfo.mContentInsets);
718 insetsChanged = true;
719 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
720 + mAttachInfo.mContentInsets);
721 }
722 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
723 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
724 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
725 + mAttachInfo.mVisibleInsets);
726 }
727 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
728 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
729 windowResizesToFitContent = true;
730
Romain Guy8506ab42009-06-11 17:35:47 -0700731 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700732 mView.getContext().getResources().getDisplayMetrics();
733 desiredWindowWidth = packageMetrics.widthPixels;
734 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 }
736 }
737
738 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
739 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
740
741 // Ask host how big it wants to be
742 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
743 "Measuring " + host + " in display " + desiredWindowWidth
744 + "x" + desiredWindowHeight + "...");
745 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
746
747 if (DBG) {
748 System.out.println("======================================");
749 System.out.println("performTraversals -- after measure");
750 host.debug();
751 }
752 }
753
754 if (attachInfo.mRecomputeGlobalAttributes) {
755 //Log.i(TAG, "Computing screen on!");
756 attachInfo.mRecomputeGlobalAttributes = false;
757 boolean oldVal = attachInfo.mKeepScreenOn;
758 attachInfo.mKeepScreenOn = false;
759 host.dispatchCollectViewAttributes(0);
760 if (attachInfo.mKeepScreenOn != oldVal) {
761 params = lp;
762 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
763 }
764 }
765
766 if (mFirst || attachInfo.mViewVisibilityChanged) {
767 attachInfo.mViewVisibilityChanged = false;
768 int resizeMode = mSoftInputMode &
769 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
770 // If we are in auto resize mode, then we need to determine
771 // what mode to use now.
772 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
773 final int N = attachInfo.mScrollContainers.size();
774 for (int i=0; i<N; i++) {
775 if (attachInfo.mScrollContainers.get(i).isShown()) {
776 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
777 }
778 }
779 if (resizeMode == 0) {
780 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
781 }
782 if ((lp.softInputMode &
783 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
784 lp.softInputMode = (lp.softInputMode &
785 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
786 resizeMode;
787 params = lp;
788 }
789 }
790 }
Romain Guy8506ab42009-06-11 17:35:47 -0700791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
793 if (!PixelFormat.formatHasAlpha(params.format)) {
794 params.format = PixelFormat.TRANSLUCENT;
795 }
796 }
797
798 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
799 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
800
801 final boolean computesInternalInsets =
802 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
803 boolean insetsPending = false;
804 int relayoutResult = 0;
805 if (mFirst || windowShouldResize || insetsChanged
806 || viewVisibilityChanged || params != null) {
807
808 if (viewVisibility == View.VISIBLE) {
809 // If this window is giving internal insets to the window
810 // manager, and it is being added or changing its visibility,
811 // then we want to first give the window manager "fake"
812 // insets to cause it to effectively ignore the content of
813 // the window during layout. This avoids it briefly causing
814 // other windows to resize/move based on the raw frame of the
815 // window, waiting until we can finish laying out this window
816 // and get back to the window manager with the ultimately
817 // computed insets.
818 insetsPending = computesInternalInsets
819 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
822 if (params == null) {
823 params = mWindowAttributes;
824 }
825 mGlWanted = true;
826 }
827 }
828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 boolean initialized = false;
830 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700831 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 try {
833 boolean hadSurface = mSurface.isValid();
834 int fl = 0;
835 if (params != null) {
836 fl = params.flags;
837 if (attachInfo.mKeepScreenOn) {
838 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
839 }
840 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700841 if (DEBUG_LAYOUT) {
842 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
843 host.mMeasuredHeight + ", params=" + params);
844 }
845 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 if (params != null) {
848 params.flags = fl;
849 }
850
851 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
852 + " content=" + mPendingContentInsets.toShortString()
853 + " visible=" + mPendingVisibleInsets.toShortString()
854 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 contentInsetsChanged = !mPendingContentInsets.equals(
857 mAttachInfo.mContentInsets);
858 visibleInsetsChanged = !mPendingVisibleInsets.equals(
859 mAttachInfo.mVisibleInsets);
860 if (contentInsetsChanged) {
861 mAttachInfo.mContentInsets.set(mPendingContentInsets);
862 host.fitSystemWindows(mAttachInfo.mContentInsets);
863 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
864 + mAttachInfo.mContentInsets);
865 }
866 if (visibleInsetsChanged) {
867 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
868 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
869 + mAttachInfo.mVisibleInsets);
870 }
871
872 if (!hadSurface) {
873 if (mSurface.isValid()) {
874 // If we are creating a new surface, then we need to
875 // completely redraw it. Also, when we get to the
876 // point of drawing it we will hold off and schedule
877 // a new traversal instead. This is so we can tell the
878 // window manager about all of the windows being displayed
879 // before actually drawing them, so it can display then
880 // all at once.
881 newSurface = true;
882 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 if (mGlWanted && !mUseGL) {
885 initializeGL();
886 initialized = mGlCanvas != null;
887 }
888 }
889 } else if (!mSurface.isValid()) {
890 // If the surface has been removed, then reset the scroll
891 // positions.
892 mLastScrolledFocus = null;
893 mScrollY = mCurScrollY = 0;
894 if (mScroller != null) {
895 mScroller.abortAnimation();
896 }
897 }
898 } catch (RemoteException e) {
899 }
900 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700901 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902
903 attachInfo.mWindowLeft = frame.left;
904 attachInfo.mWindowTop = frame.top;
905
906 // !!FIXME!! This next section handles the case where we did not get the
907 // window size we asked for. We should avoid this by getting a maximum size from
908 // the window session beforehand.
909 mWidth = frame.width();
910 mHeight = frame.height();
911
912 if (initialized) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700913 mGlCanvas.setViewport((int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 }
915
916 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
917 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
918 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
919 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
920 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
921 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
922
923 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
924 + mWidth + " measuredWidth=" + host.mMeasuredWidth
925 + " mHeight=" + mHeight
926 + " measuredHeight" + host.mMeasuredHeight
927 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 // Ask host how big it wants to be
930 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
931
932 // Implementation of weights from WindowManager.LayoutParams
933 // We just grow the dimensions as needed and re-measure if
934 // needs be
935 int width = host.mMeasuredWidth;
936 int height = host.mMeasuredHeight;
937 boolean measureAgain = false;
938
939 if (lp.horizontalWeight > 0.0f) {
940 width += (int) ((mWidth - width) * lp.horizontalWeight);
941 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
942 MeasureSpec.EXACTLY);
943 measureAgain = true;
944 }
945 if (lp.verticalWeight > 0.0f) {
946 height += (int) ((mHeight - height) * lp.verticalWeight);
947 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
948 MeasureSpec.EXACTLY);
949 measureAgain = true;
950 }
951
952 if (measureAgain) {
953 if (DEBUG_LAYOUT) Log.v(TAG,
954 "And hey let's measure once more: width=" + width
955 + " height=" + height);
956 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
957 }
958
959 mLayoutRequested = true;
960 }
961 }
962
963 final boolean didLayout = mLayoutRequested;
964 boolean triggerGlobalLayoutListener = didLayout
965 || attachInfo.mRecomputeGlobalAttributes;
966 if (didLayout) {
967 mLayoutRequested = false;
968 mScrollMayChange = true;
969 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
970 "ViewRoot", "Laying out " + host + " to (" +
971 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700972 long startTime = 0L;
973 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 startTime = SystemClock.elapsedRealtime();
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
977
Romain Guy13922e02009-05-12 17:56:14 -0700978 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
979 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
980 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
981 + "please refer to the logs with the tag "
982 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
983 }
984 }
985
986 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
988 }
989
990 // By this point all views have been sized and positionned
991 // We can compute the transparent area
992
993 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
994 // start out transparent
995 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
996 host.getLocationInWindow(mTmpLocation);
997 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
998 mTmpLocation[0] + host.mRight - host.mLeft,
999 mTmpLocation[1] + host.mBottom - host.mTop);
1000
1001 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001002 if (mTranslator != null) {
1003 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1004 }
1005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1007 mPreviousTransparentRegion.set(mTransparentRegion);
1008 // reconfigure window manager
1009 try {
1010 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1011 } catch (RemoteException e) {
1012 }
1013 }
1014 }
1015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 if (DBG) {
1017 System.out.println("======================================");
1018 System.out.println("performTraversals -- after setFrame");
1019 host.debug();
1020 }
1021 }
1022
1023 if (triggerGlobalLayoutListener) {
1024 attachInfo.mRecomputeGlobalAttributes = false;
1025 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1026 }
1027
1028 if (computesInternalInsets) {
1029 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1030 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1031 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1032 givenContent.left = givenContent.top = givenContent.right
1033 = givenContent.bottom = givenVisible.left = givenVisible.top
1034 = givenVisible.right = givenVisible.bottom = 0;
1035 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001036 Rect contentInsets = insets.contentInsets;
1037 Rect visibleInsets = insets.visibleInsets;
1038 if (mTranslator != null) {
1039 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1040 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1043 mLastGivenInsets.set(insets);
1044 try {
1045 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001046 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 } catch (RemoteException e) {
1048 }
1049 }
1050 }
Romain Guy8506ab42009-06-11 17:35:47 -07001051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 if (mFirst) {
1053 // handle first focus request
1054 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1055 + mView.hasFocus());
1056 if (mView != null) {
1057 if (!mView.hasFocus()) {
1058 mView.requestFocus(View.FOCUS_FORWARD);
1059 mFocusedView = mRealFocusedView = mView.findFocus();
1060 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1061 + mFocusedView);
1062 } else {
1063 mRealFocusedView = mView.findFocus();
1064 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1065 + mRealFocusedView);
1066 }
1067 }
1068 }
1069
1070 mFirst = false;
1071 mWillDrawSoon = false;
1072 mNewSurfaceNeeded = false;
1073 mViewVisibility = viewVisibility;
1074
1075 if (mAttachInfo.mHasWindowFocus) {
1076 final boolean imTarget = WindowManager.LayoutParams
1077 .mayUseInputMethod(mWindowAttributes.flags);
1078 if (imTarget != mLastWasImTarget) {
1079 mLastWasImTarget = imTarget;
1080 InputMethodManager imm = InputMethodManager.peekInstance();
1081 if (imm != null && imTarget) {
1082 imm.startGettingWindowFocus(mView);
1083 imm.onWindowFocus(mView, mView.findFocus(),
1084 mWindowAttributes.softInputMode,
1085 !mHasHadWindowFocus, mWindowAttributes.flags);
1086 }
1087 }
1088 }
Romain Guy8506ab42009-06-11 17:35:47 -07001089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1091
1092 if (!cancelDraw && !newSurface) {
1093 mFullRedrawNeeded = false;
1094 draw(fullRedrawNeeded);
1095
1096 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1097 || mReportNextDraw) {
1098 if (LOCAL_LOGV) {
1099 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1100 }
1101 mReportNextDraw = false;
1102 try {
1103 sWindowSession.finishDrawing(mWindow);
1104 } catch (RemoteException e) {
1105 }
1106 }
1107 } else {
1108 // We were supposed to report when we are done drawing. Since we canceled the
1109 // draw, remember it here.
1110 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1111 mReportNextDraw = true;
1112 }
1113 if (fullRedrawNeeded) {
1114 mFullRedrawNeeded = true;
1115 }
1116 // Try again
1117 scheduleTraversals();
1118 }
1119 }
1120
1121 public void requestTransparentRegion(View child) {
1122 // the test below should not fail unless someone is messing with us
1123 checkThread();
1124 if (mView == child) {
1125 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1126 // Need to make sure we re-evaluate the window attributes next
1127 // time around, to ensure the window has the correct format.
1128 mWindowAttributesChanged = true;
1129 }
1130 }
1131
1132 /**
1133 * Figures out the measure spec for the root view in a window based on it's
1134 * layout params.
1135 *
1136 * @param windowSize
1137 * The available width or height of the window
1138 *
1139 * @param rootDimension
1140 * The layout params for one dimension (width or height) of the
1141 * window.
1142 *
1143 * @return The measure spec to use to measure the root view.
1144 */
1145 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1146 int measureSpec;
1147 switch (rootDimension) {
1148
1149 case ViewGroup.LayoutParams.FILL_PARENT:
1150 // Window can't resize. Force root view to be windowSize.
1151 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1152 break;
1153 case ViewGroup.LayoutParams.WRAP_CONTENT:
1154 // Window can resize. Set max size for root view.
1155 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1156 break;
1157 default:
1158 // Window wants to be an exact size. Force root view to be that size.
1159 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1160 break;
1161 }
1162 return measureSpec;
1163 }
1164
1165 private void draw(boolean fullRedrawNeeded) {
1166 Surface surface = mSurface;
1167 if (surface == null || !surface.isValid()) {
1168 return;
1169 }
1170
1171 scrollToRectOrFocus(null, false);
1172
1173 if (mAttachInfo.mViewScrollChanged) {
1174 mAttachInfo.mViewScrollChanged = false;
1175 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1176 }
Romain Guy8506ab42009-06-11 17:35:47 -07001177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001179 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 if (scrolling) {
1181 yoff = mScroller.getCurrY();
1182 } else {
1183 yoff = mScrollY;
1184 }
1185 if (mCurScrollY != yoff) {
1186 mCurScrollY = yoff;
1187 fullRedrawNeeded = true;
1188 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001189 float appScale = mAttachInfo.mApplicationScale;
1190 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191
1192 Rect dirty = mDirty;
1193 if (mUseGL) {
1194 if (!dirty.isEmpty()) {
1195 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001196 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 mGL.glDisable(GL_SCISSOR_TEST);
1198 mGL.glClearColor(0, 0, 0, 0);
1199 mGL.glClear(GL_COLOR_BUFFER_BIT);
1200 mGL.glEnable(GL_SCISSOR_TEST);
1201
1202 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001203 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001205
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001206 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1207 try {
1208 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001209 if (mTranslator != null) {
1210 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001211 }
1212 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001213 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1214 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1215 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001216 } finally {
1217 canvas.restoreToCount(saveCount);
1218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219
Romain Guy5bcdff42009-05-14 21:27:18 -07001220 mAttachInfo.mIgnoreDirtyState = false;
1221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1223 checkEglErrors();
1224
Romain Guy13922e02009-05-12 17:56:14 -07001225 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 int now = (int)SystemClock.elapsedRealtime();
1227 if (sDrawTime != 0) {
1228 nativeShowFPS(canvas, now - sDrawTime);
1229 }
1230 sDrawTime = now;
1231 }
1232 }
1233 }
1234 if (scrolling) {
1235 mFullRedrawNeeded = true;
1236 scheduleTraversals();
1237 }
1238 return;
1239 }
1240
Romain Guy5bcdff42009-05-14 21:27:18 -07001241 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001242 mAttachInfo.mIgnoreDirtyState = true;
1243 dirty.union(0, 0, (int) (mWidth * appScale), (int) (mHeight * appScale));
Romain Guy5bcdff42009-05-14 21:27:18 -07001244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245
1246 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1247 Log.v("ViewRoot", "Draw " + mView + "/"
1248 + mWindowAttributes.getTitle()
1249 + ": dirty={" + dirty.left + "," + dirty.top
1250 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001251 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1252 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 }
1254
1255 Canvas canvas;
1256 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001257 int left = dirty.left;
1258 int top = dirty.top;
1259 int right = dirty.right;
1260 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001262
1263 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1264 bottom != dirty.bottom) {
1265 mAttachInfo.mIgnoreDirtyState = true;
1266 }
1267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 // TODO: Do this in native
1269 canvas.setDensityScale(mDensity);
1270 } catch (Surface.OutOfResourcesException e) {
1271 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1272 // TODO: we should ask the window manager to do something!
1273 // for now we just do nothing
1274 return;
1275 }
1276
1277 try {
Romain Guybb93d552009-03-24 21:04:15 -07001278 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001279 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280
1281 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1282 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1283 + canvas.getWidth() + ", h=" + canvas.getHeight());
1284 //canvas.drawARGB(255, 255, 0, 0);
1285 }
1286
Romain Guy13922e02009-05-12 17:56:14 -07001287 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 startTime = SystemClock.elapsedRealtime();
1289 }
1290
1291 // If this bitmap's format includes an alpha channel, we
1292 // need to clear it before drawing so that the child will
1293 // properly re-composite its drawing on a transparent
1294 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001295 // or
1296 // If we are applying an offset, we need to clear the area
1297 // where the offset doesn't appear to avoid having garbage
1298 // left in the blank areas.
1299 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1301 }
1302
1303 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001304 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001306 mView.mPrivateFlags |= View.DRAWN;
1307
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001308 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001309 Context cxt = mView.getContext();
1310 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001311 ", metrics=" + mView.getContext().getResources().getDisplayMetrics());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001312 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001313 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001314 try {
1315 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001316 if (mTranslator != null) {
1317 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001318 }
1319 mView.draw(canvas);
1320 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001321 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001322 canvas.restoreToCount(saveCount);
1323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324
Romain Guy5bcdff42009-05-14 21:27:18 -07001325 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1326 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1327 }
1328
Romain Guy13922e02009-05-12 17:56:14 -07001329 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 int now = (int)SystemClock.elapsedRealtime();
1331 if (sDrawTime != 0) {
1332 nativeShowFPS(canvas, now - sDrawTime);
1333 }
1334 sDrawTime = now;
1335 }
1336
Romain Guy13922e02009-05-12 17:56:14 -07001337 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1339 }
1340 }
Romain Guy8506ab42009-06-11 17:35:47 -07001341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 } finally {
1343 surface.unlockCanvasAndPost(canvas);
1344 }
1345
1346 if (LOCAL_LOGV) {
1347 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1348 }
Romain Guy8506ab42009-06-11 17:35:47 -07001349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 if (scrolling) {
1351 mFullRedrawNeeded = true;
1352 scheduleTraversals();
1353 }
1354 }
1355
1356 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1357 final View.AttachInfo attachInfo = mAttachInfo;
1358 final Rect ci = attachInfo.mContentInsets;
1359 final Rect vi = attachInfo.mVisibleInsets;
1360 int scrollY = 0;
1361 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 if (vi.left > ci.left || vi.top > ci.top
1364 || vi.right > ci.right || vi.bottom > ci.bottom) {
1365 // We'll assume that we aren't going to change the scroll
1366 // offset, since we want to avoid that unless it is actually
1367 // going to make the focus visible... otherwise we scroll
1368 // all over the place.
1369 scrollY = mScrollY;
1370 // We can be called for two different situations: during a draw,
1371 // to update the scroll position if the focus has changed (in which
1372 // case 'rectangle' is null), or in response to a
1373 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1374 // is non-null and we just want to scroll to whatever that
1375 // rectangle is).
1376 View focus = mRealFocusedView;
1377 if (focus != mLastScrolledFocus) {
1378 // If the focus has changed, then ignore any requests to scroll
1379 // to a rectangle; first we want to make sure the entire focus
1380 // view is visible.
1381 rectangle = null;
1382 }
1383 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1384 + " rectangle=" + rectangle + " ci=" + ci
1385 + " vi=" + vi);
1386 if (focus == mLastScrolledFocus && !mScrollMayChange
1387 && rectangle == null) {
1388 // Optimization: if the focus hasn't changed since last
1389 // time, and no layout has happened, then just leave things
1390 // as they are.
1391 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1392 + mScrollY + " vi=" + vi.toShortString());
1393 } else if (focus != null) {
1394 // We need to determine if the currently focused view is
1395 // within the visible part of the window and, if not, apply
1396 // a pan so it can be seen.
1397 mLastScrolledFocus = focus;
1398 mScrollMayChange = false;
1399 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1400 // Try to find the rectangle from the focus view.
1401 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1402 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1403 + mView.getWidth() + " h=" + mView.getHeight()
1404 + " ci=" + ci.toShortString()
1405 + " vi=" + vi.toShortString());
1406 if (rectangle == null) {
1407 focus.getFocusedRect(mTempRect);
1408 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1409 + ": focusRect=" + mTempRect.toShortString());
1410 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1411 focus, mTempRect);
1412 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1413 "Focus in window: focusRect="
1414 + mTempRect.toShortString()
1415 + " visRect=" + mVisRect.toShortString());
1416 } else {
1417 mTempRect.set(rectangle);
1418 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1419 "Request scroll to rect: "
1420 + mTempRect.toShortString()
1421 + " visRect=" + mVisRect.toShortString());
1422 }
1423 if (mTempRect.intersect(mVisRect)) {
1424 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1425 "Focus window visible rect: "
1426 + mTempRect.toShortString());
1427 if (mTempRect.height() >
1428 (mView.getHeight()-vi.top-vi.bottom)) {
1429 // If the focus simply is not going to fit, then
1430 // best is probably just to leave things as-is.
1431 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1432 "Too tall; leaving scrollY=" + scrollY);
1433 } else if ((mTempRect.top-scrollY) < vi.top) {
1434 scrollY -= vi.top - (mTempRect.top-scrollY);
1435 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1436 "Top covered; scrollY=" + scrollY);
1437 } else if ((mTempRect.bottom-scrollY)
1438 > (mView.getHeight()-vi.bottom)) {
1439 scrollY += (mTempRect.bottom-scrollY)
1440 - (mView.getHeight()-vi.bottom);
1441 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1442 "Bottom covered; scrollY=" + scrollY);
1443 }
1444 handled = true;
1445 }
1446 }
1447 }
1448 }
Romain Guy8506ab42009-06-11 17:35:47 -07001449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 if (scrollY != mScrollY) {
1451 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1452 + mScrollY + " , new=" + scrollY);
1453 if (!immediate) {
1454 if (mScroller == null) {
1455 mScroller = new Scroller(mView.getContext());
1456 }
1457 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1458 } else if (mScroller != null) {
1459 mScroller.abortAnimation();
1460 }
1461 mScrollY = scrollY;
1462 }
Romain Guy8506ab42009-06-11 17:35:47 -07001463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 return handled;
1465 }
Romain Guy8506ab42009-06-11 17:35:47 -07001466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 public void requestChildFocus(View child, View focused) {
1468 checkThread();
1469 if (mFocusedView != focused) {
1470 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1471 scheduleTraversals();
1472 }
1473 mFocusedView = mRealFocusedView = focused;
1474 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1475 + mFocusedView);
1476 }
1477
1478 public void clearChildFocus(View child) {
1479 checkThread();
1480
1481 View oldFocus = mFocusedView;
1482
1483 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1484 mFocusedView = mRealFocusedView = null;
1485 if (mView != null && !mView.hasFocus()) {
1486 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1487 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1488 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1489 }
1490 } else if (oldFocus != null) {
1491 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1492 }
1493 }
1494
1495
1496 public void focusableViewAvailable(View v) {
1497 checkThread();
1498
1499 if (mView != null && !mView.hasFocus()) {
1500 v.requestFocus();
1501 } else {
1502 // the one case where will transfer focus away from the current one
1503 // is if the current view is a view group that prefers to give focus
1504 // to its children first AND the view is a descendant of it.
1505 mFocusedView = mView.findFocus();
1506 boolean descendantsHaveDibsOnFocus =
1507 (mFocusedView instanceof ViewGroup) &&
1508 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1509 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1510 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1511 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1512 v.requestFocus();
1513 }
1514 }
1515 }
1516
1517 public void recomputeViewAttributes(View child) {
1518 checkThread();
1519 if (mView == child) {
1520 mAttachInfo.mRecomputeGlobalAttributes = true;
1521 if (!mWillDrawSoon) {
1522 scheduleTraversals();
1523 }
1524 }
1525 }
1526
1527 void dispatchDetachedFromWindow() {
1528 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1529
1530 if (mView != null) {
1531 mView.dispatchDetachedFromWindow();
1532 }
1533
1534 mView = null;
1535 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001536 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537
1538 if (mUseGL) {
1539 destroyGL();
1540 }
Mathias Agopian5583dc62009-07-09 16:28:11 -07001541 mSurface.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542
1543 try {
1544 sWindowSession.remove(mWindow);
1545 } catch (RemoteException e) {
1546 }
1547 }
Romain Guy8506ab42009-06-11 17:35:47 -07001548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 /**
1550 * Return true if child is an ancestor of parent, (or equal to the parent).
1551 */
1552 private static boolean isViewDescendantOf(View child, View parent) {
1553 if (child == parent) {
1554 return true;
1555 }
1556
1557 final ViewParent theParent = child.getParent();
1558 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1559 }
1560
1561
1562 public final static int DO_TRAVERSAL = 1000;
1563 public final static int DIE = 1001;
1564 public final static int RESIZED = 1002;
1565 public final static int RESIZED_REPORT = 1003;
1566 public final static int WINDOW_FOCUS_CHANGED = 1004;
1567 public final static int DISPATCH_KEY = 1005;
1568 public final static int DISPATCH_POINTER = 1006;
1569 public final static int DISPATCH_TRACKBALL = 1007;
1570 public final static int DISPATCH_APP_VISIBILITY = 1008;
1571 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1572 public final static int FINISHED_EVENT = 1010;
1573 public final static int DISPATCH_KEY_FROM_IME = 1011;
1574 public final static int FINISH_INPUT_CONNECTION = 1012;
1575 public final static int CHECK_FOCUS = 1013;
1576
1577 @Override
1578 public void handleMessage(Message msg) {
1579 switch (msg.what) {
1580 case View.AttachInfo.INVALIDATE_MSG:
1581 ((View) msg.obj).invalidate();
1582 break;
1583 case View.AttachInfo.INVALIDATE_RECT_MSG:
1584 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1585 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1586 info.release();
1587 break;
1588 case DO_TRAVERSAL:
1589 if (mProfile) {
1590 Debug.startMethodTracing("ViewRoot");
1591 }
1592
1593 performTraversals();
1594
1595 if (mProfile) {
1596 Debug.stopMethodTracing();
1597 mProfile = false;
1598 }
1599 break;
1600 case FINISHED_EVENT:
1601 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1602 break;
1603 case DISPATCH_KEY:
1604 if (LOCAL_LOGV) Log.v(
1605 "ViewRoot", "Dispatching key "
1606 + msg.obj + " to " + mView);
1607 deliverKeyEvent((KeyEvent)msg.obj, true);
1608 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001609 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 MotionEvent event = (MotionEvent)msg.obj;
1611
1612 boolean didFinish;
1613 if (event == null) {
1614 try {
Michael Chan53071d62009-05-13 17:29:48 -07001615 long timeBeforeGettingEvents;
1616 if (MEASURE_LATENCY) {
1617 timeBeforeGettingEvents = System.nanoTime();
1618 }
1619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001621
1622 if (MEASURE_LATENCY && event != null) {
1623 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1624 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 } catch (RemoteException e) {
1627 }
1628 didFinish = true;
1629 } else {
1630 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
1631 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001632 if (event != null && mTranslator != null) {
1633 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 try {
1636 boolean handled;
1637 if (mView != null && mAdded && event != null) {
1638
1639 // enter touch mode on the down
1640 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1641 if (isDown) {
1642 ensureTouchMode(true);
1643 }
1644 if(Config.LOGV) {
1645 captureMotionLog("captureDispatchPointer", event);
1646 }
1647 event.offsetLocation(0, mCurScrollY);
Michael Chan53071d62009-05-13 17:29:48 -07001648 if (MEASURE_LATENCY) {
1649 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001652 if (MEASURE_LATENCY) {
1653 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 if (!handled && isDown) {
1656 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1657
1658 final int edgeFlags = event.getEdgeFlags();
1659 int direction = View.FOCUS_UP;
1660 int x = (int)event.getX();
1661 int y = (int)event.getY();
1662 final int[] deltas = new int[2];
1663
1664 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1665 direction = View.FOCUS_DOWN;
1666 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1667 deltas[0] = edgeSlop;
1668 x += edgeSlop;
1669 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1670 deltas[0] = -edgeSlop;
1671 x -= edgeSlop;
1672 }
1673 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1674 direction = View.FOCUS_UP;
1675 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1676 deltas[0] = edgeSlop;
1677 x += edgeSlop;
1678 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1679 deltas[0] = -edgeSlop;
1680 x -= edgeSlop;
1681 }
1682 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1683 direction = View.FOCUS_RIGHT;
1684 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1685 direction = View.FOCUS_LEFT;
1686 }
1687
1688 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1689 View nearest = FocusFinder.getInstance().findNearestTouchable(
1690 ((ViewGroup) mView), x, y, direction, deltas);
1691 if (nearest != null) {
1692 event.offsetLocation(deltas[0], deltas[1]);
1693 event.setEdgeFlags(0);
1694 mView.dispatchTouchEvent(event);
1695 }
1696 }
1697 }
1698 }
1699 } finally {
1700 if (!didFinish) {
1701 try {
1702 sWindowSession.finishKey(mWindow);
1703 } catch (RemoteException e) {
1704 }
1705 }
1706 if (event != null) {
1707 event.recycle();
1708 }
1709 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1710 // Let the exception fall through -- the looper will catch
1711 // it and take care of the bad app for us.
1712 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001713 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 case DISPATCH_TRACKBALL:
1715 deliverTrackballEvent((MotionEvent)msg.obj);
1716 break;
1717 case DISPATCH_APP_VISIBILITY:
1718 handleAppVisibility(msg.arg1 != 0);
1719 break;
1720 case DISPATCH_GET_NEW_SURFACE:
1721 handleGetNewSurface();
1722 break;
1723 case RESIZED:
1724 Rect coveredInsets = ((Rect[])msg.obj)[0];
1725 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1728 && mPendingContentInsets.equals(coveredInsets)
1729 && mPendingVisibleInsets.equals(visibleInsets)) {
1730 break;
1731 }
1732 // fall through...
1733 case RESIZED_REPORT:
1734 if (mAdded) {
1735 mWinFrame.left = 0;
1736 mWinFrame.right = msg.arg1;
1737 mWinFrame.top = 0;
1738 mWinFrame.bottom = msg.arg2;
1739 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1740 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1741 if (msg.what == RESIZED_REPORT) {
1742 mReportNextDraw = true;
1743 }
1744 requestLayout();
1745 }
1746 break;
1747 case WINDOW_FOCUS_CHANGED: {
1748 if (mAdded) {
1749 boolean hasWindowFocus = msg.arg1 != 0;
1750 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1751 if (hasWindowFocus) {
1752 boolean inTouchMode = msg.arg2 != 0;
1753 ensureTouchModeLocally(inTouchMode);
1754
1755 if (mGlWanted) {
1756 checkEglErrors();
1757 // we lost the gl context, so recreate it.
1758 if (mGlWanted && !mUseGL) {
1759 initializeGL();
1760 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001761 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001762 mGlCanvas.setViewport(
1763 (int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765 }
1766 }
1767 }
Romain Guy8506ab42009-06-11 17:35:47 -07001768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 mLastWasImTarget = WindowManager.LayoutParams
1770 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 InputMethodManager imm = InputMethodManager.peekInstance();
1773 if (mView != null) {
1774 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1775 imm.startGettingWindowFocus(mView);
1776 }
1777 mView.dispatchWindowFocusChanged(hasWindowFocus);
1778 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 // Note: must be done after the focus change callbacks,
1781 // so all of the view state is set up correctly.
1782 if (hasWindowFocus) {
1783 if (imm != null && mLastWasImTarget) {
1784 imm.onWindowFocus(mView, mView.findFocus(),
1785 mWindowAttributes.softInputMode,
1786 !mHasHadWindowFocus, mWindowAttributes.flags);
1787 }
1788 // Clear the forward bit. We can just do this directly, since
1789 // the window manager doesn't care about it.
1790 mWindowAttributes.softInputMode &=
1791 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1792 ((WindowManager.LayoutParams)mView.getLayoutParams())
1793 .softInputMode &=
1794 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1795 mHasHadWindowFocus = true;
1796 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001797
1798 if (hasWindowFocus && mView != null) {
1799 sendAccessibilityEvents();
1800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
1802 } break;
1803 case DIE:
1804 dispatchDetachedFromWindow();
1805 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001806 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 if (LOCAL_LOGV) Log.v(
1808 "ViewRoot", "Dispatching key "
1809 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001810 KeyEvent event = (KeyEvent)msg.obj;
1811 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1812 // The IME is trying to say this event is from the
1813 // system! Bad bad bad!
1814 event = KeyEvent.changeFlags(event,
1815 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001818 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 case FINISH_INPUT_CONNECTION: {
1820 InputMethodManager imm = InputMethodManager.peekInstance();
1821 if (imm != null) {
1822 imm.reportFinishInputConnection((InputConnection)msg.obj);
1823 }
1824 } break;
1825 case CHECK_FOCUS: {
1826 InputMethodManager imm = InputMethodManager.peekInstance();
1827 if (imm != null) {
1828 imm.checkFocus();
1829 }
1830 } break;
1831 }
1832 }
1833
1834 /**
1835 * Something in the current window tells us we need to change the touch mode. For
1836 * example, we are not in touch mode, and the user touches the screen.
1837 *
1838 * If the touch mode has changed, tell the window manager, and handle it locally.
1839 *
1840 * @param inTouchMode Whether we want to be in touch mode.
1841 * @return True if the touch mode changed and focus changed was changed as a result
1842 */
1843 boolean ensureTouchMode(boolean inTouchMode) {
1844 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1845 + "touch mode is " + mAttachInfo.mInTouchMode);
1846 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1847
1848 // tell the window manager
1849 try {
1850 sWindowSession.setInTouchMode(inTouchMode);
1851 } catch (RemoteException e) {
1852 throw new RuntimeException(e);
1853 }
1854
1855 // handle the change
1856 return ensureTouchModeLocally(inTouchMode);
1857 }
1858
1859 /**
1860 * Ensure that the touch mode for this window is set, and if it is changing,
1861 * take the appropriate action.
1862 * @param inTouchMode Whether we want to be in touch mode.
1863 * @return True if the touch mode changed and focus changed was changed as a result
1864 */
1865 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1866 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1867 + "touch mode is " + mAttachInfo.mInTouchMode);
1868
1869 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1870
1871 mAttachInfo.mInTouchMode = inTouchMode;
1872 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1873
1874 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1875 }
1876
1877 private boolean enterTouchMode() {
1878 if (mView != null) {
1879 if (mView.hasFocus()) {
1880 // note: not relying on mFocusedView here because this could
1881 // be when the window is first being added, and mFocused isn't
1882 // set yet.
1883 final View focused = mView.findFocus();
1884 if (focused != null && !focused.isFocusableInTouchMode()) {
1885
1886 final ViewGroup ancestorToTakeFocus =
1887 findAncestorToTakeFocusInTouchMode(focused);
1888 if (ancestorToTakeFocus != null) {
1889 // there is an ancestor that wants focus after its descendants that
1890 // is focusable in touch mode.. give it focus
1891 return ancestorToTakeFocus.requestFocus();
1892 } else {
1893 // nothing appropriate to have focus in touch mode, clear it out
1894 mView.unFocus();
1895 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1896 mFocusedView = null;
1897 return true;
1898 }
1899 }
1900 }
1901 }
1902 return false;
1903 }
1904
1905
1906 /**
1907 * Find an ancestor of focused that wants focus after its descendants and is
1908 * focusable in touch mode.
1909 * @param focused The currently focused view.
1910 * @return An appropriate view, or null if no such view exists.
1911 */
1912 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1913 ViewParent parent = focused.getParent();
1914 while (parent instanceof ViewGroup) {
1915 final ViewGroup vgParent = (ViewGroup) parent;
1916 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1917 && vgParent.isFocusableInTouchMode()) {
1918 return vgParent;
1919 }
1920 if (vgParent.isRootNamespace()) {
1921 return null;
1922 } else {
1923 parent = vgParent.getParent();
1924 }
1925 }
1926 return null;
1927 }
1928
1929 private boolean leaveTouchMode() {
1930 if (mView != null) {
1931 if (mView.hasFocus()) {
1932 // i learned the hard way to not trust mFocusedView :)
1933 mFocusedView = mView.findFocus();
1934 if (!(mFocusedView instanceof ViewGroup)) {
1935 // some view has focus, let it keep it
1936 return false;
1937 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1938 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1939 // some view group has focus, and doesn't prefer its children
1940 // over itself for focus, so let them keep it.
1941 return false;
1942 }
1943 }
1944
1945 // find the best view to give focus to in this brave new non-touch-mode
1946 // world
1947 final View focused = focusSearch(null, View.FOCUS_DOWN);
1948 if (focused != null) {
1949 return focused.requestFocus(View.FOCUS_DOWN);
1950 }
1951 }
1952 return false;
1953 }
1954
1955
1956 private void deliverTrackballEvent(MotionEvent event) {
1957 boolean didFinish;
1958 if (event == null) {
1959 try {
1960 event = sWindowSession.getPendingTrackballMove(mWindow);
1961 } catch (RemoteException e) {
1962 }
1963 didFinish = true;
1964 } else {
1965 didFinish = false;
1966 }
1967
1968 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
1969
1970 boolean handled = false;
1971 try {
1972 if (event == null) {
1973 handled = true;
1974 } else if (mView != null && mAdded) {
1975 handled = mView.dispatchTrackballEvent(event);
1976 if (!handled) {
1977 // we could do something here, like changing the focus
1978 // or something?
1979 }
1980 }
1981 } finally {
1982 if (handled) {
1983 if (!didFinish) {
1984 try {
1985 sWindowSession.finishKey(mWindow);
1986 } catch (RemoteException e) {
1987 }
1988 }
1989 if (event != null) {
1990 event.recycle();
1991 }
1992 // If we reach this, we delivered a trackball event to mView and
1993 // mView consumed it. Because we will not translate the trackball
1994 // event into a key event, touch mode will not exit, so we exit
1995 // touch mode here.
1996 ensureTouchMode(false);
1997 //noinspection ReturnInsideFinallyBlock
1998 return;
1999 }
2000 // Let the exception fall through -- the looper will catch
2001 // it and take care of the bad app for us.
2002 }
2003
2004 final TrackballAxis x = mTrackballAxisX;
2005 final TrackballAxis y = mTrackballAxisY;
2006
2007 long curTime = SystemClock.uptimeMillis();
2008 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2009 // It has been too long since the last movement,
2010 // so restart at the beginning.
2011 x.reset(0);
2012 y.reset(0);
2013 mLastTrackballTime = curTime;
2014 }
2015
2016 try {
2017 final int action = event.getAction();
2018 final int metastate = event.getMetaState();
2019 switch (action) {
2020 case MotionEvent.ACTION_DOWN:
2021 x.reset(2);
2022 y.reset(2);
2023 deliverKeyEvent(new KeyEvent(curTime, curTime,
2024 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2025 0, metastate), false);
2026 break;
2027 case MotionEvent.ACTION_UP:
2028 x.reset(2);
2029 y.reset(2);
2030 deliverKeyEvent(new KeyEvent(curTime, curTime,
2031 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2032 0, metastate), false);
2033 break;
2034 }
2035
2036 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2037 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2038 + " move=" + event.getX()
2039 + " / Y=" + y.position + " step="
2040 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2041 + " move=" + event.getY());
2042 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2043 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2044
2045 // Generate DPAD events based on the trackball movement.
2046 // We pick the axis that has moved the most as the direction of
2047 // the DPAD. When we generate DPAD events for one axis, then the
2048 // other axis is reset -- we don't want to perform DPAD jumps due
2049 // to slight movements in the trackball when making major movements
2050 // along the other axis.
2051 int keycode = 0;
2052 int movement = 0;
2053 float accel = 1;
2054 if (xOff > yOff) {
2055 movement = x.generate((2/event.getXPrecision()));
2056 if (movement != 0) {
2057 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2058 : KeyEvent.KEYCODE_DPAD_LEFT;
2059 accel = x.acceleration;
2060 y.reset(2);
2061 }
2062 } else if (yOff > 0) {
2063 movement = y.generate((2/event.getYPrecision()));
2064 if (movement != 0) {
2065 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2066 : KeyEvent.KEYCODE_DPAD_UP;
2067 accel = y.acceleration;
2068 x.reset(2);
2069 }
2070 }
2071
2072 if (keycode != 0) {
2073 if (movement < 0) movement = -movement;
2074 int accelMovement = (int)(movement * accel);
2075 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2076 + " accelMovement=" + accelMovement
2077 + " accel=" + accel);
2078 if (accelMovement > movement) {
2079 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2080 + keycode);
2081 movement--;
2082 deliverKeyEvent(new KeyEvent(curTime, curTime,
2083 KeyEvent.ACTION_MULTIPLE, keycode,
2084 accelMovement-movement, metastate), false);
2085 }
2086 while (movement > 0) {
2087 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2088 + keycode);
2089 movement--;
2090 curTime = SystemClock.uptimeMillis();
2091 deliverKeyEvent(new KeyEvent(curTime, curTime,
2092 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2093 deliverKeyEvent(new KeyEvent(curTime, curTime,
2094 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2095 }
2096 mLastTrackballTime = curTime;
2097 }
2098 } finally {
2099 if (!didFinish) {
2100 try {
2101 sWindowSession.finishKey(mWindow);
2102 } catch (RemoteException e) {
2103 }
2104 if (event != null) {
2105 event.recycle();
2106 }
2107 }
2108 // Let the exception fall through -- the looper will catch
2109 // it and take care of the bad app for us.
2110 }
2111 }
2112
2113 /**
2114 * @param keyCode The key code
2115 * @return True if the key is directional.
2116 */
2117 static boolean isDirectional(int keyCode) {
2118 switch (keyCode) {
2119 case KeyEvent.KEYCODE_DPAD_LEFT:
2120 case KeyEvent.KEYCODE_DPAD_RIGHT:
2121 case KeyEvent.KEYCODE_DPAD_UP:
2122 case KeyEvent.KEYCODE_DPAD_DOWN:
2123 return true;
2124 }
2125 return false;
2126 }
2127
2128 /**
2129 * Returns true if this key is a keyboard key.
2130 * @param keyEvent The key event.
2131 * @return whether this key is a keyboard key.
2132 */
2133 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2134 final int convertedKey = keyEvent.getUnicodeChar();
2135 return convertedKey > 0;
2136 }
2137
2138
2139
2140 /**
2141 * See if the key event means we should leave touch mode (and leave touch
2142 * mode if so).
2143 * @param event The key event.
2144 * @return Whether this key event should be consumed (meaning the act of
2145 * leaving touch mode alone is considered the event).
2146 */
2147 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2148 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2149 return false;
2150 }
2151 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2152 return false;
2153 }
2154
2155 // only relevant if we are in touch mode
2156 if (!mAttachInfo.mInTouchMode) {
2157 return false;
2158 }
2159
2160 // if something like an edit text has focus and the user is typing,
2161 // leave touch mode
2162 //
2163 // note: the condition of not being a keyboard key is kind of a hacky
2164 // approximation of whether we think the focused view will want the
2165 // key; if we knew for sure whether the focused view would consume
2166 // the event, that would be better.
2167 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2168 mFocusedView = mView.findFocus();
2169 if ((mFocusedView instanceof ViewGroup)
2170 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2171 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2172 // something has focus, but is holding it weakly as a container
2173 return false;
2174 }
2175 if (ensureTouchMode(false)) {
2176 throw new IllegalStateException("should not have changed focus "
2177 + "when leaving touch mode while a view has focus.");
2178 }
2179 return false;
2180 }
2181
2182 if (isDirectional(event.getKeyCode())) {
2183 // no view has focus, so we leave touch mode (and find something
2184 // to give focus to). the event is consumed if we were able to
2185 // find something to give focus to.
2186 return ensureTouchMode(false);
2187 }
2188 return false;
2189 }
2190
2191 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002192 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 */
2194 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002195 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 if (ev == null ||
2197 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2198 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 }
Romain Guy8506ab42009-06-11 17:35:47 -07002200
2201 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 sb.append(ev.getDownTime()).append(',');
2203 sb.append(ev.getEventTime()).append(',');
2204 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002205 sb.append(ev.getX()).append(',');
2206 sb.append(ev.getY()).append(',');
2207 sb.append(ev.getPressure()).append(',');
2208 sb.append(ev.getSize()).append(',');
2209 sb.append(ev.getMetaState()).append(',');
2210 sb.append(ev.getXPrecision()).append(',');
2211 sb.append(ev.getYPrecision()).append(',');
2212 sb.append(ev.getDeviceId()).append(',');
2213 sb.append(ev.getEdgeFlags());
2214 Log.d(TAG, sb.toString());
2215 }
2216 /**
2217 * log motion events
2218 */
2219 private static void captureKeyLog(String subTag, KeyEvent ev) {
2220 //check dynamic switch
2221 if (ev == null ||
2222 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2223 return;
2224 }
2225 StringBuilder sb = new StringBuilder(subTag + ": ");
2226 sb.append(ev.getDownTime()).append(',');
2227 sb.append(ev.getEventTime()).append(',');
2228 sb.append(ev.getAction()).append(',');
2229 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 sb.append(ev.getRepeatCount()).append(',');
2231 sb.append(ev.getMetaState()).append(',');
2232 sb.append(ev.getDeviceId()).append(',');
2233 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002234 Log.d(TAG, sb.toString());
2235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236
2237 int enqueuePendingEvent(Object event, boolean sendDone) {
2238 int seq = mPendingEventSeq+1;
2239 if (seq < 0) seq = 0;
2240 mPendingEventSeq = seq;
2241 mPendingEvents.put(seq, event);
2242 return sendDone ? seq : -seq;
2243 }
2244
2245 Object retrievePendingEvent(int seq) {
2246 if (seq < 0) seq = -seq;
2247 Object event = mPendingEvents.get(seq);
2248 if (event != null) {
2249 mPendingEvents.remove(seq);
2250 }
2251 return event;
2252 }
Romain Guy8506ab42009-06-11 17:35:47 -07002253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2255 // If mView is null, we just consume the key event because it doesn't
2256 // make sense to do anything else with it.
2257 boolean handled = mView != null
2258 ? mView.dispatchKeyEventPreIme(event) : true;
2259 if (handled) {
2260 if (sendDone) {
2261 if (LOCAL_LOGV) Log.v(
2262 "ViewRoot", "Telling window manager key is finished");
2263 try {
2264 sWindowSession.finishKey(mWindow);
2265 } catch (RemoteException e) {
2266 }
2267 }
2268 return;
2269 }
2270 // If it is possible for this window to interact with the input
2271 // method window, then we want to first dispatch our key events
2272 // to the input method.
2273 if (mLastWasImTarget) {
2274 InputMethodManager imm = InputMethodManager.peekInstance();
2275 if (imm != null && mView != null) {
2276 int seq = enqueuePendingEvent(event, sendDone);
2277 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2278 + seq + " event=" + event);
2279 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2280 mInputMethodCallback);
2281 return;
2282 }
2283 }
2284 deliverKeyEventToViewHierarchy(event, sendDone);
2285 }
2286
2287 void handleFinishedEvent(int seq, boolean handled) {
2288 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2289 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2290 + " handled=" + handled + " event=" + event);
2291 if (event != null) {
2292 final boolean sendDone = seq >= 0;
2293 if (!handled) {
2294 deliverKeyEventToViewHierarchy(event, sendDone);
2295 return;
2296 } else if (sendDone) {
2297 if (LOCAL_LOGV) Log.v(
2298 "ViewRoot", "Telling window manager key is finished");
2299 try {
2300 sWindowSession.finishKey(mWindow);
2301 } catch (RemoteException e) {
2302 }
2303 } else {
2304 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2305 + " handled=" + handled + " ev=" + event
2306 + ") neither delivering nor finishing key");
2307 }
2308 }
2309 }
Romain Guy8506ab42009-06-11 17:35:47 -07002310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2312 try {
2313 if (mView != null && mAdded) {
2314 final int action = event.getAction();
2315 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2316
2317 if (checkForLeavingTouchModeAndConsume(event)) {
2318 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002319 }
2320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 if (Config.LOGV) {
2322 captureKeyLog("captureDispatchKeyEvent", event);
2323 }
2324 boolean keyHandled = mView.dispatchKeyEvent(event);
2325
2326 if (!keyHandled && isDown) {
2327 int direction = 0;
2328 switch (event.getKeyCode()) {
2329 case KeyEvent.KEYCODE_DPAD_LEFT:
2330 direction = View.FOCUS_LEFT;
2331 break;
2332 case KeyEvent.KEYCODE_DPAD_RIGHT:
2333 direction = View.FOCUS_RIGHT;
2334 break;
2335 case KeyEvent.KEYCODE_DPAD_UP:
2336 direction = View.FOCUS_UP;
2337 break;
2338 case KeyEvent.KEYCODE_DPAD_DOWN:
2339 direction = View.FOCUS_DOWN;
2340 break;
2341 }
2342
2343 if (direction != 0) {
2344
2345 View focused = mView != null ? mView.findFocus() : null;
2346 if (focused != null) {
2347 View v = focused.focusSearch(direction);
2348 boolean focusPassed = false;
2349 if (v != null && v != focused) {
2350 // do the math the get the interesting rect
2351 // of previous focused into the coord system of
2352 // newly focused view
2353 focused.getFocusedRect(mTempRect);
2354 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2355 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2356 focusPassed = v.requestFocus(direction, mTempRect);
2357 }
2358
2359 if (!focusPassed) {
2360 mView.dispatchUnhandledMove(focused, direction);
2361 } else {
2362 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2363 }
2364 }
2365 }
2366 }
2367 }
2368
2369 } finally {
2370 if (sendDone) {
2371 if (LOCAL_LOGV) Log.v(
2372 "ViewRoot", "Telling window manager key is finished");
2373 try {
2374 sWindowSession.finishKey(mWindow);
2375 } catch (RemoteException e) {
2376 }
2377 }
2378 // Let the exception fall through -- the looper will catch
2379 // it and take care of the bad app for us.
2380 }
2381 }
2382
2383 private AudioManager getAudioManager() {
2384 if (mView == null) {
2385 throw new IllegalStateException("getAudioManager called when there is no mView");
2386 }
2387 if (mAudioManager == null) {
2388 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2389 }
2390 return mAudioManager;
2391 }
2392
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002393 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2394 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002395
2396 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002397 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002398 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002399 restore = true;
2400 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002401 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002402 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002403 if (params != null) {
2404 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002405 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002406 int relayoutResult = sWindowSession.relayout(
2407 mWindow, params,
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002408 (int) (mView.mMeasuredWidth * appScale),
2409 (int) (mView.mMeasuredHeight * appScale),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002410 viewVisibility, insetsPending, mWinFrame,
2411 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002412 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002413 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002414 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002415
2416 if (mTranslator != null) {
2417 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2418 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2419 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002420 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002421 return relayoutResult;
2422 }
Romain Guy8506ab42009-06-11 17:35:47 -07002423
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002424 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 * {@inheritDoc}
2426 */
2427 public void playSoundEffect(int effectId) {
2428 checkThread();
2429
2430 final AudioManager audioManager = getAudioManager();
2431
2432 switch (effectId) {
2433 case SoundEffectConstants.CLICK:
2434 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2435 return;
2436 case SoundEffectConstants.NAVIGATION_DOWN:
2437 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2438 return;
2439 case SoundEffectConstants.NAVIGATION_LEFT:
2440 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2441 return;
2442 case SoundEffectConstants.NAVIGATION_RIGHT:
2443 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2444 return;
2445 case SoundEffectConstants.NAVIGATION_UP:
2446 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2447 return;
2448 default:
2449 throw new IllegalArgumentException("unknown effect id " + effectId +
2450 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2451 }
2452 }
2453
2454 /**
2455 * {@inheritDoc}
2456 */
2457 public boolean performHapticFeedback(int effectId, boolean always) {
2458 try {
2459 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2460 } catch (RemoteException e) {
2461 return false;
2462 }
2463 }
2464
2465 /**
2466 * {@inheritDoc}
2467 */
2468 public View focusSearch(View focused, int direction) {
2469 checkThread();
2470 if (!(mView instanceof ViewGroup)) {
2471 return null;
2472 }
2473 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2474 }
2475
2476 public void debug() {
2477 mView.debug();
2478 }
2479
2480 public void die(boolean immediate) {
2481 checkThread();
2482 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2483 synchronized (this) {
2484 if (mAdded && !mFirst) {
2485 int viewVisibility = mView.getVisibility();
2486 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2487 if (mWindowAttributesChanged || viewVisibilityChanged) {
2488 // If layout params have been changed, first give them
2489 // to the window manager to make sure it has the correct
2490 // animation info.
2491 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002492 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2493 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 sWindowSession.finishDrawing(mWindow);
2495 }
2496 } catch (RemoteException e) {
2497 }
2498 }
2499
Mathias Agopian5583dc62009-07-09 16:28:11 -07002500 mSurface.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
2502 if (mAdded) {
2503 mAdded = false;
2504 if (immediate) {
2505 dispatchDetachedFromWindow();
2506 } else if (mView != null) {
2507 sendEmptyMessage(DIE);
2508 }
2509 }
2510 }
2511 }
2512
2513 public void dispatchFinishedEvent(int seq, boolean handled) {
2514 Message msg = obtainMessage(FINISHED_EVENT);
2515 msg.arg1 = seq;
2516 msg.arg2 = handled ? 1 : 0;
2517 sendMessage(msg);
2518 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 public void dispatchResized(int w, int h, Rect coveredInsets,
2521 Rect visibleInsets, boolean reportDraw) {
2522 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2523 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2524 + " visibleInsets=" + visibleInsets.toShortString()
2525 + " reportDraw=" + reportDraw);
2526 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002527 if (mTranslator != null) {
2528 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2529 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2530 w *= mTranslator.applicationInvertedScale;
2531 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002532 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002533 msg.arg1 = w;
2534 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2536 sendMessage(msg);
2537 }
2538
2539 public void dispatchKey(KeyEvent event) {
2540 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2541 //noinspection ConstantConditions
2542 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2543 if (Config.LOGD) Log.d("keydisp",
2544 "===================================================");
2545 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2546 debug();
2547
2548 if (Config.LOGD) Log.d("keydisp",
2549 "===================================================");
2550 }
2551 }
2552
2553 Message msg = obtainMessage(DISPATCH_KEY);
2554 msg.obj = event;
2555
2556 if (LOCAL_LOGV) Log.v(
2557 "ViewRoot", "sending key " + event + " to " + mView);
2558
2559 sendMessageAtTime(msg, event.getEventTime());
2560 }
2561
2562 public void dispatchPointer(MotionEvent event, long eventTime) {
2563 Message msg = obtainMessage(DISPATCH_POINTER);
2564 msg.obj = event;
2565 sendMessageAtTime(msg, eventTime);
2566 }
2567
2568 public void dispatchTrackball(MotionEvent event, long eventTime) {
2569 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2570 msg.obj = event;
2571 sendMessageAtTime(msg, eventTime);
2572 }
2573
2574 public void dispatchAppVisibility(boolean visible) {
2575 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2576 msg.arg1 = visible ? 1 : 0;
2577 sendMessage(msg);
2578 }
2579
2580 public void dispatchGetNewSurface() {
2581 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2582 sendMessage(msg);
2583 }
2584
2585 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2586 Message msg = Message.obtain();
2587 msg.what = WINDOW_FOCUS_CHANGED;
2588 msg.arg1 = hasFocus ? 1 : 0;
2589 msg.arg2 = inTouchMode ? 1 : 0;
2590 sendMessage(msg);
2591 }
2592
svetoslavganov75986cf2009-05-14 22:28:01 -07002593 /**
2594 * The window is getting focus so if there is anything focused/selected
2595 * send an {@link AccessibilityEvent} to announce that.
2596 */
2597 private void sendAccessibilityEvents() {
2598 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2599 return;
2600 }
2601 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2602 View focusedView = mView.findFocus();
2603 if (focusedView != null && focusedView != mView) {
2604 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2605 }
2606 }
2607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 public boolean showContextMenuForChild(View originalView) {
2609 return false;
2610 }
2611
2612 public void createContextMenu(ContextMenu menu) {
2613 }
2614
2615 public void childDrawableStateChanged(View child) {
2616 }
2617
2618 protected Rect getWindowFrame() {
2619 return mWinFrame;
2620 }
2621
2622 void checkThread() {
2623 if (mThread != Thread.currentThread()) {
2624 throw new CalledFromWrongThreadException(
2625 "Only the original thread that created a view hierarchy can touch its views.");
2626 }
2627 }
2628
2629 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2630 // ViewRoot never intercepts touch event, so this can be a no-op
2631 }
2632
2633 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2634 boolean immediate) {
2635 return scrollToRectOrFocus(rectangle, immediate);
2636 }
Romain Guy8506ab42009-06-11 17:35:47 -07002637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 static class InputMethodCallback extends IInputMethodCallback.Stub {
2639 private WeakReference<ViewRoot> mViewRoot;
2640
2641 public InputMethodCallback(ViewRoot viewRoot) {
2642 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2643 }
Romain Guy8506ab42009-06-11 17:35:47 -07002644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 public void finishedEvent(int seq, boolean handled) {
2646 final ViewRoot viewRoot = mViewRoot.get();
2647 if (viewRoot != null) {
2648 viewRoot.dispatchFinishedEvent(seq, handled);
2649 }
2650 }
2651
2652 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2653 // Stub -- not for use in the client.
2654 }
2655 }
Romain Guy8506ab42009-06-11 17:35:47 -07002656
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002657 static class EventCompletion extends Handler {
2658 final IWindow mWindow;
2659 final KeyEvent mKeyEvent;
2660 final boolean mIsPointer;
2661 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002662
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002663 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2664 boolean isPointer, MotionEvent motion) {
2665 super(looper);
2666 mWindow = window;
2667 mKeyEvent = key;
2668 mIsPointer = isPointer;
2669 mMotionEvent = motion;
2670 sendEmptyMessage(0);
2671 }
Romain Guy8506ab42009-06-11 17:35:47 -07002672
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002673 @Override
2674 public void handleMessage(Message msg) {
2675 if (mKeyEvent != null) {
2676 try {
2677 sWindowSession.finishKey(mWindow);
2678 } catch (RemoteException e) {
2679 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002680 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002681 boolean didFinish;
2682 MotionEvent event = mMotionEvent;
2683 if (event == null) {
2684 try {
2685 event = sWindowSession.getPendingPointerMove(mWindow);
2686 } catch (RemoteException e) {
2687 }
2688 didFinish = true;
2689 } else {
2690 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2691 }
2692 if (!didFinish) {
2693 try {
2694 sWindowSession.finishKey(mWindow);
2695 } catch (RemoteException e) {
2696 }
2697 }
2698 } else {
2699 MotionEvent event = mMotionEvent;
2700 if (event == null) {
2701 try {
2702 event = sWindowSession.getPendingTrackballMove(mWindow);
2703 } catch (RemoteException e) {
2704 }
2705 } else {
2706 try {
2707 sWindowSession.finishKey(mWindow);
2708 } catch (RemoteException e) {
2709 }
2710 }
2711 }
2712 }
2713 }
Romain Guy8506ab42009-06-11 17:35:47 -07002714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002716 private final WeakReference<ViewRoot> mViewRoot;
2717 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002719 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002721 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 }
2723
2724 public void resized(int w, int h, Rect coveredInsets,
2725 Rect visibleInsets, boolean reportDraw) {
2726 final ViewRoot viewRoot = mViewRoot.get();
2727 if (viewRoot != null) {
2728 viewRoot.dispatchResized(w, h, coveredInsets,
2729 visibleInsets, reportDraw);
2730 }
2731 }
2732
2733 public void dispatchKey(KeyEvent event) {
2734 final ViewRoot viewRoot = mViewRoot.get();
2735 if (viewRoot != null) {
2736 viewRoot.dispatchKey(event);
2737 } else {
2738 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002739 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 }
2741 }
2742
2743 public void dispatchPointer(MotionEvent event, long eventTime) {
2744 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002745 if (viewRoot != null) {
2746 if (MEASURE_LATENCY) {
2747 // Note: eventTime is in milliseconds
2748 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 viewRoot.dispatchPointer(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002751 } else {
2752 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 }
2754 }
2755
2756 public void dispatchTrackball(MotionEvent event, long eventTime) {
2757 final ViewRoot viewRoot = mViewRoot.get();
2758 if (viewRoot != null) {
2759 viewRoot.dispatchTrackball(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002760 } else {
2761 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 }
2763 }
2764
2765 public void dispatchAppVisibility(boolean visible) {
2766 final ViewRoot viewRoot = mViewRoot.get();
2767 if (viewRoot != null) {
2768 viewRoot.dispatchAppVisibility(visible);
2769 }
2770 }
2771
2772 public void dispatchGetNewSurface() {
2773 final ViewRoot viewRoot = mViewRoot.get();
2774 if (viewRoot != null) {
2775 viewRoot.dispatchGetNewSurface();
2776 }
2777 }
2778
2779 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2780 final ViewRoot viewRoot = mViewRoot.get();
2781 if (viewRoot != null) {
2782 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2783 }
2784 }
2785
2786 private static int checkCallingPermission(String permission) {
2787 if (!Process.supportsProcesses()) {
2788 return PackageManager.PERMISSION_GRANTED;
2789 }
2790
2791 try {
2792 return ActivityManagerNative.getDefault().checkPermission(
2793 permission, Binder.getCallingPid(), Binder.getCallingUid());
2794 } catch (RemoteException e) {
2795 return PackageManager.PERMISSION_DENIED;
2796 }
2797 }
2798
2799 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2800 final ViewRoot viewRoot = mViewRoot.get();
2801 if (viewRoot != null) {
2802 final View view = viewRoot.mView;
2803 if (view != null) {
2804 if (checkCallingPermission(Manifest.permission.DUMP) !=
2805 PackageManager.PERMISSION_GRANTED) {
2806 throw new SecurityException("Insufficient permissions to invoke"
2807 + " executeCommand() from pid=" + Binder.getCallingPid()
2808 + ", uid=" + Binder.getCallingUid());
2809 }
2810
2811 OutputStream clientStream = null;
2812 try {
2813 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2814 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2815 } catch (IOException e) {
2816 e.printStackTrace();
2817 } finally {
2818 if (clientStream != null) {
2819 try {
2820 clientStream.close();
2821 } catch (IOException e) {
2822 e.printStackTrace();
2823 }
2824 }
2825 }
2826 }
2827 }
2828 }
2829 }
2830
2831 /**
2832 * Maintains state information for a single trackball axis, generating
2833 * discrete (DPAD) movements based on raw trackball motion.
2834 */
2835 static final class TrackballAxis {
2836 /**
2837 * The maximum amount of acceleration we will apply.
2838 */
2839 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 /**
2842 * The maximum amount of time (in milliseconds) between events in order
2843 * for us to consider the user to be doing fast trackball movements,
2844 * and thus apply an acceleration.
2845 */
2846 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 /**
2849 * Scaling factor to the time (in milliseconds) between events to how
2850 * much to multiple/divide the current acceleration. When movement
2851 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2852 * FAST_MOVE_TIME it divides it.
2853 */
2854 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 float position;
2857 float absPosition;
2858 float acceleration = 1;
2859 long lastMoveTime = 0;
2860 int step;
2861 int dir;
2862 int nonAccelMovement;
2863
2864 void reset(int _step) {
2865 position = 0;
2866 acceleration = 1;
2867 lastMoveTime = 0;
2868 step = _step;
2869 dir = 0;
2870 }
2871
2872 /**
2873 * Add trackball movement into the state. If the direction of movement
2874 * has been reversed, the state is reset before adding the
2875 * movement (so that you don't have to compensate for any previously
2876 * collected movement before see the result of the movement in the
2877 * new direction).
2878 *
2879 * @return Returns the absolute value of the amount of movement
2880 * collected so far.
2881 */
2882 float collect(float off, long time, String axis) {
2883 long normTime;
2884 if (off > 0) {
2885 normTime = (long)(off * FAST_MOVE_TIME);
2886 if (dir < 0) {
2887 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2888 position = 0;
2889 step = 0;
2890 acceleration = 1;
2891 lastMoveTime = 0;
2892 }
2893 dir = 1;
2894 } else if (off < 0) {
2895 normTime = (long)((-off) * FAST_MOVE_TIME);
2896 if (dir > 0) {
2897 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2898 position = 0;
2899 step = 0;
2900 acceleration = 1;
2901 lastMoveTime = 0;
2902 }
2903 dir = -1;
2904 } else {
2905 normTime = 0;
2906 }
Romain Guy8506ab42009-06-11 17:35:47 -07002907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 // The number of milliseconds between each movement that is
2909 // considered "normal" and will not result in any acceleration
2910 // or deceleration, scaled by the offset we have here.
2911 if (normTime > 0) {
2912 long delta = time - lastMoveTime;
2913 lastMoveTime = time;
2914 float acc = acceleration;
2915 if (delta < normTime) {
2916 // The user is scrolling rapidly, so increase acceleration.
2917 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2918 if (scale > 1) acc *= scale;
2919 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2920 + off + " normTime=" + normTime + " delta=" + delta
2921 + " scale=" + scale + " acc=" + acc);
2922 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2923 } else {
2924 // The user is scrolling slowly, so decrease acceleration.
2925 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
2926 if (scale > 1) acc /= scale;
2927 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
2928 + off + " normTime=" + normTime + " delta=" + delta
2929 + " scale=" + scale + " acc=" + acc);
2930 acceleration = acc > 1 ? acc : 1;
2931 }
2932 }
2933 position += off;
2934 return (absPosition = Math.abs(position));
2935 }
2936
2937 /**
2938 * Generate the number of discrete movement events appropriate for
2939 * the currently collected trackball movement.
2940 *
2941 * @param precision The minimum movement required to generate the
2942 * first discrete movement.
2943 *
2944 * @return Returns the number of discrete movements, either positive
2945 * or negative, or 0 if there is not enough trackball movement yet
2946 * for a discrete movement.
2947 */
2948 int generate(float precision) {
2949 int movement = 0;
2950 nonAccelMovement = 0;
2951 do {
2952 final int dir = position >= 0 ? 1 : -1;
2953 switch (step) {
2954 // If we are going to execute the first step, then we want
2955 // to do this as soon as possible instead of waiting for
2956 // a full movement, in order to make things look responsive.
2957 case 0:
2958 if (absPosition < precision) {
2959 return movement;
2960 }
2961 movement += dir;
2962 nonAccelMovement += dir;
2963 step = 1;
2964 break;
2965 // If we have generated the first movement, then we need
2966 // to wait for the second complete trackball motion before
2967 // generating the second discrete movement.
2968 case 1:
2969 if (absPosition < 2) {
2970 return movement;
2971 }
2972 movement += dir;
2973 nonAccelMovement += dir;
2974 position += dir > 0 ? -2 : 2;
2975 absPosition = Math.abs(position);
2976 step = 2;
2977 break;
2978 // After the first two, we generate discrete movements
2979 // consistently with the trackball, applying an acceleration
2980 // if the trackball is moving quickly. This is a simple
2981 // acceleration on top of what we already compute based
2982 // on how quickly the wheel is being turned, to apply
2983 // a longer increasing acceleration to continuous movement
2984 // in one direction.
2985 default:
2986 if (absPosition < 1) {
2987 return movement;
2988 }
2989 movement += dir;
2990 position += dir >= 0 ? -1 : 1;
2991 absPosition = Math.abs(position);
2992 float acc = acceleration;
2993 acc *= 1.1f;
2994 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
2995 break;
2996 }
2997 } while (true);
2998 }
2999 }
3000
3001 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3002 public CalledFromWrongThreadException(String msg) {
3003 super(msg);
3004 }
3005 }
3006
3007 private SurfaceHolder mHolder = new SurfaceHolder() {
3008 // we only need a SurfaceHolder for opengl. it would be nice
3009 // to implement everything else though, especially the callback
3010 // support (opengl doesn't make use of it right now, but eventually
3011 // will).
3012 public Surface getSurface() {
3013 return mSurface;
3014 }
3015
3016 public boolean isCreating() {
3017 return false;
3018 }
3019
3020 public void addCallback(Callback callback) {
3021 }
3022
3023 public void removeCallback(Callback callback) {
3024 }
3025
3026 public void setFixedSize(int width, int height) {
3027 }
3028
3029 public void setSizeFromLayout() {
3030 }
3031
3032 public void setFormat(int format) {
3033 }
3034
3035 public void setType(int type) {
3036 }
3037
3038 public void setKeepScreenOn(boolean screenOn) {
3039 }
3040
3041 public Canvas lockCanvas() {
3042 return null;
3043 }
3044
3045 public Canvas lockCanvas(Rect dirty) {
3046 return null;
3047 }
3048
3049 public void unlockCanvasAndPost(Canvas canvas) {
3050 }
3051 public Rect getSurfaceFrame() {
3052 return null;
3053 }
3054 };
3055
3056 static RunQueue getRunQueue() {
3057 RunQueue rq = sRunQueues.get();
3058 if (rq != null) {
3059 return rq;
3060 }
3061 rq = new RunQueue();
3062 sRunQueues.set(rq);
3063 return rq;
3064 }
Romain Guy8506ab42009-06-11 17:35:47 -07003065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 /**
3067 * @hide
3068 */
3069 static final class RunQueue {
3070 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3071
3072 void post(Runnable action) {
3073 postDelayed(action, 0);
3074 }
3075
3076 void postDelayed(Runnable action, long delayMillis) {
3077 HandlerAction handlerAction = new HandlerAction();
3078 handlerAction.action = action;
3079 handlerAction.delay = delayMillis;
3080
3081 synchronized (mActions) {
3082 mActions.add(handlerAction);
3083 }
3084 }
3085
3086 void removeCallbacks(Runnable action) {
3087 final HandlerAction handlerAction = new HandlerAction();
3088 handlerAction.action = action;
3089
3090 synchronized (mActions) {
3091 final ArrayList<HandlerAction> actions = mActions;
3092
3093 while (actions.remove(handlerAction)) {
3094 // Keep going
3095 }
3096 }
3097 }
3098
3099 void executeActions(Handler handler) {
3100 synchronized (mActions) {
3101 final ArrayList<HandlerAction> actions = mActions;
3102 final int count = actions.size();
3103
3104 for (int i = 0; i < count; i++) {
3105 final HandlerAction handlerAction = actions.get(i);
3106 handler.postDelayed(handlerAction.action, handlerAction.delay);
3107 }
3108
3109 mActions.clear();
3110 }
3111 }
3112
3113 private static class HandlerAction {
3114 Runnable action;
3115 long delay;
3116
3117 @Override
3118 public boolean equals(Object o) {
3119 if (this == o) return true;
3120 if (o == null || getClass() != o.getClass()) return false;
3121
3122 HandlerAction that = (HandlerAction) o;
3123
3124 return !(action != null ? !action.equals(that.action) : that.action != null);
3125
3126 }
3127
3128 @Override
3129 public int hashCode() {
3130 int result = action != null ? action.hashCode() : 0;
3131 result = 31 * result + (int) (delay ^ (delay >>> 32));
3132 return result;
3133 }
3134 }
3135 }
3136
3137 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3138
3139 // inform skia to just abandon its texture cache IDs
3140 // doesn't call glDeleteTextures
3141 private static native void nativeAbandonGlCaches();
3142}