blob: bb61ad3c93c55603066342f8133e68444f03b101 [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;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070045import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.Context;
47import android.app.ActivityManagerNative;
48import android.Manifest;
49import android.media.AudioManager;
50
51import java.lang.ref.WeakReference;
52import java.io.IOException;
53import java.io.OutputStream;
54import java.util.ArrayList;
55
56import javax.microedition.khronos.egl.*;
57import javax.microedition.khronos.opengles.*;
58import static javax.microedition.khronos.opengles.GL10.*;
59
60/**
61 * The top of a view hierarchy, implementing the needed protocol between View
62 * and the WindowManager. This is for the most part an internal implementation
63 * detail of {@link WindowManagerImpl}.
64 *
65 * {@hide}
66 */
67@SuppressWarnings({"EmptyCatchBlock"})
68public final class ViewRoot extends Handler implements ViewParent,
69 View.AttachInfo.Callbacks {
70 private static final String TAG = "ViewRoot";
71 private static final boolean DBG = false;
72 @SuppressWarnings({"ConstantConditionalExpression"})
73 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
74 /** @noinspection PointlessBooleanExpression*/
75 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
76 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
77 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
78 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
79 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
80 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
81 private static final boolean WATCH_POINTER = false;
82
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 /**
84 * Maximum time we allow the user to roll the trackball enough to generate
85 * a key event, before resetting the counters.
86 */
87 static final int MAX_TRACKBALL_DELAY = 250;
88
89 static long sInstanceCount = 0;
90
91 static IWindowSession sWindowSession;
92
93 static final Object mStaticInit = new Object();
94 static boolean mInitialized = false;
95
96 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
97
Romain Guy8506ab42009-06-11 17:35:47 -070098 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -070099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 long mLastTrackballTime = 0;
101 final TrackballAxis mTrackballAxisX = new TrackballAxis();
102 final TrackballAxis mTrackballAxisY = new TrackballAxis();
103
104 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 final InputMethodCallback mInputMethodCallback;
107 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
108 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 final Thread mThread;
111
112 final WindowLeaked mLocation;
113
114 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
115
116 final W mWindow;
117
118 View mView;
119 View mFocusedView;
120 View mRealFocusedView; // this is not set to null in touch mode
121 int mViewVisibility;
122 boolean mAppVisible = true;
123
124 final Region mTransparentRegion;
125 final Region mPreviousTransparentRegion;
126
127 int mWidth;
128 int mHeight;
129 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700130 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700131
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700132 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
134 final View.AttachInfo mAttachInfo;
135
136 final Rect mTempRect; // used in the transaction to not thrash the heap.
137 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 boolean mTraversalScheduled;
140 boolean mWillDrawSoon;
141 boolean mLayoutRequested;
142 boolean mFirst;
143 boolean mReportNextDraw;
144 boolean mFullRedrawNeeded;
145 boolean mNewSurfaceNeeded;
146 boolean mHasHadWindowFocus;
147 boolean mLastWasImTarget;
148
149 boolean mWindowAttributesChanged = false;
150
151 // These can be accessed by any thread, must be protected with a lock.
152 Surface mSurface;
153
154 boolean mAdded;
155 boolean mAddedTouchMode;
156
157 /*package*/ int mAddNesting;
158
159 // These are accessed by multiple threads.
160 final Rect mWinFrame; // frame given by window manager.
161
162 final Rect mPendingVisibleInsets = new Rect();
163 final Rect mPendingContentInsets = new Rect();
164 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
165 = new ViewTreeObserver.InternalInsetsInfo();
166
167 boolean mScrollMayChange;
168 int mSoftInputMode;
169 View mLastScrolledFocus;
170 int mScrollY;
171 int mCurScrollY;
172 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 EGL10 mEgl;
175 EGLDisplay mEglDisplay;
176 EGLContext mEglContext;
177 EGLSurface mEglSurface;
178 GL11 mGL;
179 Canvas mGlCanvas;
180 boolean mUseGL;
181 boolean mGlWanted;
182
Romain Guy8506ab42009-06-11 17:35:47 -0700183 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
185 /**
186 * see {@link #playSoundEffect(int)}
187 */
188 AudioManager mAudioManager;
189
190 private final float mDensity;
191
192 public ViewRoot(Context context) {
193 super();
194
195 ++sInstanceCount;
196
197 // Initialize the statics when this class is first instantiated. This is
198 // done here instead of in the static block because Zygote does not
199 // allow the spawning of threads.
200 synchronized (mStaticInit) {
201 if (!mInitialized) {
202 try {
203 InputMethodManager imm = InputMethodManager.getInstance(context);
204 sWindowSession = IWindowManager.Stub.asInterface(
205 ServiceManager.getService("window"))
206 .openSession(imm.getClient(), imm.getInputContext());
207 mInitialized = true;
208 } catch (RemoteException e) {
209 }
210 }
211 }
212
213 mThread = Thread.currentThread();
214 mLocation = new WindowLeaked(null);
215 mLocation.fillInStackTrace();
216 mWidth = -1;
217 mHeight = -1;
218 mDirty = new Rect();
219 mTempRect = new Rect();
220 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700222 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 mInputMethodCallback = new InputMethodCallback(this);
224 mViewVisibility = View.GONE;
225 mTransparentRegion = new Region();
226 mPreviousTransparentRegion = new Region();
227 mFirst = true; // true for the first time the view is added
228 mSurface = new Surface();
229 mAdded = false;
230 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
231 mViewConfiguration = ViewConfiguration.get(context);
232 mDensity = context.getResources().getDisplayMetrics().density;
233 }
234
235 @Override
236 protected void finalize() throws Throwable {
237 super.finalize();
238 --sInstanceCount;
239 }
240
241 public static long getInstanceCount() {
242 return sInstanceCount;
243 }
244
245 // FIXME for perf testing only
246 private boolean mProfile = false;
247
248 /**
249 * Call this to profile the next traversal call.
250 * FIXME for perf testing only. Remove eventually
251 */
252 public void profile() {
253 mProfile = true;
254 }
255
256 /**
257 * Indicates whether we are in touch mode. Calling this method triggers an IPC
258 * call and should be avoided whenever possible.
259 *
260 * @return True, if the device is in touch mode, false otherwise.
261 *
262 * @hide
263 */
264 static boolean isInTouchMode() {
265 if (mInitialized) {
266 try {
267 return sWindowSession.getInTouchMode();
268 } catch (RemoteException e) {
269 }
270 }
271 return false;
272 }
273
274 private void initializeGL() {
275 initializeGLInner();
276 int err = mEgl.eglGetError();
277 if (err != EGL10.EGL_SUCCESS) {
278 // give-up on using GL
279 destroyGL();
280 mGlWanted = false;
281 }
282 }
283
284 private void initializeGLInner() {
285 final EGL10 egl = (EGL10) EGLContext.getEGL();
286 mEgl = egl;
287
288 /*
289 * Get to the default display.
290 */
291 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
292 mEglDisplay = eglDisplay;
293
294 /*
295 * We can now initialize EGL for that display
296 */
297 int[] version = new int[2];
298 egl.eglInitialize(eglDisplay, version);
299
300 /*
301 * Specify a configuration for our opengl session
302 * and grab the first configuration that matches is
303 */
304 final int[] configSpec = {
305 EGL10.EGL_RED_SIZE, 5,
306 EGL10.EGL_GREEN_SIZE, 6,
307 EGL10.EGL_BLUE_SIZE, 5,
308 EGL10.EGL_DEPTH_SIZE, 0,
309 EGL10.EGL_NONE
310 };
311 final EGLConfig[] configs = new EGLConfig[1];
312 final int[] num_config = new int[1];
313 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
314 final EGLConfig config = configs[0];
315
316 /*
317 * Create an OpenGL ES context. This must be done only once, an
318 * OpenGL context is a somewhat heavy object.
319 */
320 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
321 EGL10.EGL_NO_CONTEXT, null);
322 mEglContext = context;
323
324 /*
325 * Create an EGL surface we can render into.
326 */
327 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
328 mEglSurface = surface;
329
330 /*
331 * Before we can issue GL commands, we need to make sure
332 * the context is current and bound to a surface.
333 */
334 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
335
336 /*
337 * Get to the appropriate GL interface.
338 * This is simply done by casting the GL context to either
339 * GL10 or GL11.
340 */
341 final GL11 gl = (GL11) context.getGL();
342 mGL = gl;
343 mGlCanvas = new Canvas(gl);
344 mUseGL = true;
345 }
346
347 private void destroyGL() {
348 // inform skia that the context is gone
349 nativeAbandonGlCaches();
350
351 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
352 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
353 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
354 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
355 mEgl.eglTerminate(mEglDisplay);
356 mEglContext = null;
357 mEglSurface = null;
358 mEglDisplay = null;
359 mEgl = null;
360 mGlCanvas = null;
361 mGL = null;
362 mUseGL = false;
363 }
364
365 private void checkEglErrors() {
366 if (mUseGL) {
367 int err = mEgl.eglGetError();
368 if (err != EGL10.EGL_SUCCESS) {
369 // something bad has happened revert to
370 // normal rendering.
371 destroyGL();
372 if (err != EGL11.EGL_CONTEXT_LOST) {
373 // we'll try again if it was context lost
374 mGlWanted = false;
375 }
376 }
377 }
378 }
379
380 /**
381 * We have one child
382 */
383 public void setView(View view, WindowManager.LayoutParams attrs,
384 View panelParentView) {
385 synchronized (this) {
386 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700387 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700388 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700389 attrs = mWindowAttributes;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700390 Resources resources = mView.getContext().getResources();
391 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700392 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700393
394 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700395 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
396 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700397 }
398
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700399 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700400 if (attrs != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700401 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700402 attrs.backup();
403 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700404 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700405 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
406
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700407 if (!compatibilityInfo.supportsScreen()) {
408 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
409 }
410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 mSoftInputMode = attrs.softInputMode;
412 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 mAttachInfo.mRootView = view;
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700414 mAttachInfo.mScalingRequired = mTranslator == null ? false : true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700415 mAttachInfo.mApplicationScale =
416 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 if (panelParentView != null) {
418 mAttachInfo.mPanelParentWindowToken
419 = panelParentView.getApplicationWindowToken();
420 }
421 mAdded = true;
422 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 // Schedule the first layout -before- adding to the window
425 // manager, to make sure we do the relayout before receiving
426 // any other events from the system.
427 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700429 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 getHostVisibility(), mAttachInfo.mContentInsets);
431 } catch (RemoteException e) {
432 mAdded = false;
433 mView = null;
434 mAttachInfo.mRootView = null;
435 unscheduleTraversals();
436 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700437 } finally {
438 if (restore) {
439 attrs.restore();
440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700442
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700443 if (mTranslator != null) {
444 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 mPendingContentInsets.set(mAttachInfo.mContentInsets);
447 mPendingVisibleInsets.set(0, 0, 0, 0);
448 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
449 if (res < WindowManagerImpl.ADD_OKAY) {
450 mView = null;
451 mAttachInfo.mRootView = null;
452 mAdded = false;
453 unscheduleTraversals();
454 switch (res) {
455 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
456 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
457 throw new WindowManagerImpl.BadTokenException(
458 "Unable to add window -- token " + attrs.token
459 + " is not valid; is your activity running?");
460 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
461 throw new WindowManagerImpl.BadTokenException(
462 "Unable to add window -- token " + attrs.token
463 + " is not for an application");
464 case WindowManagerImpl.ADD_APP_EXITING:
465 throw new WindowManagerImpl.BadTokenException(
466 "Unable to add window -- app for token " + attrs.token
467 + " is exiting");
468 case WindowManagerImpl.ADD_DUPLICATE_ADD:
469 throw new WindowManagerImpl.BadTokenException(
470 "Unable to add window -- window " + mWindow
471 + " has already been added");
472 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
473 // Silently ignore -- we would have just removed it
474 // right away, anyway.
475 return;
476 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
477 throw new WindowManagerImpl.BadTokenException(
478 "Unable to add window " + mWindow +
479 " -- another window of this type already exists");
480 case WindowManagerImpl.ADD_PERMISSION_DENIED:
481 throw new WindowManagerImpl.BadTokenException(
482 "Unable to add window " + mWindow +
483 " -- permission denied for this window type");
484 }
485 throw new RuntimeException(
486 "Unable to add window -- unknown error code " + res);
487 }
488 view.assignParent(this);
489 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
490 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
491 }
492 }
493 }
494
495 public View getView() {
496 return mView;
497 }
498
499 final WindowLeaked getLocation() {
500 return mLocation;
501 }
502
503 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
504 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700505 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700506 // preserve compatible window flag if exists.
507 int compatibleWindowFlag =
508 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700510 mWindowAttributes.flags |= compatibleWindowFlag;
511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 if (newView) {
513 mSoftInputMode = attrs.softInputMode;
514 requestLayout();
515 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700516 // Don't lose the mode we last auto-computed.
517 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
518 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
519 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
520 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
521 | (oldSoftInputMode
522 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 mWindowAttributesChanged = true;
525 scheduleTraversals();
526 }
527 }
528
529 void handleAppVisibility(boolean visible) {
530 if (mAppVisible != visible) {
531 mAppVisible = visible;
532 scheduleTraversals();
533 }
534 }
535
536 void handleGetNewSurface() {
537 mNewSurfaceNeeded = true;
538 mFullRedrawNeeded = true;
539 scheduleTraversals();
540 }
541
542 /**
543 * {@inheritDoc}
544 */
545 public void requestLayout() {
546 checkThread();
547 mLayoutRequested = true;
548 scheduleTraversals();
549 }
550
551 /**
552 * {@inheritDoc}
553 */
554 public boolean isLayoutRequested() {
555 return mLayoutRequested;
556 }
557
558 public void invalidateChild(View child, Rect dirty) {
559 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700560 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
561 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700563 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700564 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700565 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700566 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700567 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700568 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700569 }
Romain Guy1e095972009-07-07 11:22:45 -0700570 if (mAttachInfo.mScalingRequired) {
571 dirty.inset(-1, -1);
572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 }
574 mDirty.union(dirty);
575 if (!mWillDrawSoon) {
576 scheduleTraversals();
577 }
578 }
579
580 public ViewParent getParent() {
581 return null;
582 }
583
584 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
585 invalidateChild(null, dirty);
586 return null;
587 }
588
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700589 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 if (child != mView) {
591 throw new RuntimeException("child is not mine, honest!");
592 }
593 // Note: don't apply scroll offset, because we want to know its
594 // visibility in the virtual canvas being given to the view hierarchy.
595 return r.intersect(0, 0, mWidth, mHeight);
596 }
597
598 public void bringChildToFront(View child) {
599 }
600
601 public void scheduleTraversals() {
602 if (!mTraversalScheduled) {
603 mTraversalScheduled = true;
604 sendEmptyMessage(DO_TRAVERSAL);
605 }
606 }
607
608 public void unscheduleTraversals() {
609 if (mTraversalScheduled) {
610 mTraversalScheduled = false;
611 removeMessages(DO_TRAVERSAL);
612 }
613 }
614
615 int getHostVisibility() {
616 return mAppVisible ? mView.getVisibility() : View.GONE;
617 }
Romain Guy8506ab42009-06-11 17:35:47 -0700618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 private void performTraversals() {
620 // cache mView since it is used so much below...
621 final View host = mView;
622
623 if (DBG) {
624 System.out.println("======================================");
625 System.out.println("performTraversals");
626 host.debug();
627 }
628
629 if (host == null || !mAdded)
630 return;
631
632 mTraversalScheduled = false;
633 mWillDrawSoon = true;
634 boolean windowResizesToFitContent = false;
635 boolean fullRedrawNeeded = mFullRedrawNeeded;
636 boolean newSurface = false;
637 WindowManager.LayoutParams lp = mWindowAttributes;
638
639 int desiredWindowWidth;
640 int desiredWindowHeight;
641 int childWidthMeasureSpec;
642 int childHeightMeasureSpec;
643
644 final View.AttachInfo attachInfo = mAttachInfo;
645
646 final int viewVisibility = getHostVisibility();
647 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
648 || mNewSurfaceNeeded;
649
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700650 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 WindowManager.LayoutParams params = null;
653 if (mWindowAttributesChanged) {
654 mWindowAttributesChanged = false;
655 params = lp;
656 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700657 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 if (mFirst) {
659 fullRedrawNeeded = true;
660 mLayoutRequested = true;
661
Romain Guy8506ab42009-06-11 17:35:47 -0700662 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700663 mView.getContext().getResources().getDisplayMetrics();
664 desiredWindowWidth = packageMetrics.widthPixels;
665 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
667 // For the very first time, tell the view hierarchy that it
668 // is attached to the window. Note that at this point the surface
669 // object is not initialized to its backing store, but soon it
670 // will be (assuming the window is visible).
671 attachInfo.mSurface = mSurface;
672 attachInfo.mHasWindowFocus = false;
673 attachInfo.mWindowVisibility = viewVisibility;
674 attachInfo.mRecomputeGlobalAttributes = false;
675 attachInfo.mKeepScreenOn = false;
676 viewVisibilityChanged = false;
677 host.dispatchAttachedToWindow(attachInfo, 0);
678 getRunQueue().executeActions(attachInfo.mHandler);
679 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700682 desiredWindowWidth = frame.width();
683 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
685 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700686 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 fullRedrawNeeded = true;
688 mLayoutRequested = true;
689 windowResizesToFitContent = true;
690 }
691 }
692
693 if (viewVisibilityChanged) {
694 attachInfo.mWindowVisibility = viewVisibility;
695 host.dispatchWindowVisibilityChanged(viewVisibility);
696 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
697 if (mUseGL) {
698 destroyGL();
699 }
700 }
701 if (viewVisibility == View.GONE) {
702 // After making a window gone, we will count it as being
703 // shown for the first time the next time it gets focus.
704 mHasHadWindowFocus = false;
705 }
706 }
707
708 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 if (mLayoutRequested) {
711 if (mFirst) {
712 host.fitSystemWindows(mAttachInfo.mContentInsets);
713 // make sure touch mode code executes by setting cached value
714 // to opposite of the added touch mode.
715 mAttachInfo.mInTouchMode = !mAddedTouchMode;
716 ensureTouchModeLocally(mAddedTouchMode);
717 } else {
718 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
719 mAttachInfo.mContentInsets.set(mPendingContentInsets);
720 host.fitSystemWindows(mAttachInfo.mContentInsets);
721 insetsChanged = true;
722 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
723 + mAttachInfo.mContentInsets);
724 }
725 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
726 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
727 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
728 + mAttachInfo.mVisibleInsets);
729 }
730 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
731 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
732 windowResizesToFitContent = true;
733
Romain Guy8506ab42009-06-11 17:35:47 -0700734 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700735 mView.getContext().getResources().getDisplayMetrics();
736 desiredWindowWidth = packageMetrics.widthPixels;
737 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 }
739 }
740
741 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
742 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
743
744 // Ask host how big it wants to be
745 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
746 "Measuring " + host + " in display " + desiredWindowWidth
747 + "x" + desiredWindowHeight + "...");
748 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
749
750 if (DBG) {
751 System.out.println("======================================");
752 System.out.println("performTraversals -- after measure");
753 host.debug();
754 }
755 }
756
757 if (attachInfo.mRecomputeGlobalAttributes) {
758 //Log.i(TAG, "Computing screen on!");
759 attachInfo.mRecomputeGlobalAttributes = false;
760 boolean oldVal = attachInfo.mKeepScreenOn;
761 attachInfo.mKeepScreenOn = false;
762 host.dispatchCollectViewAttributes(0);
763 if (attachInfo.mKeepScreenOn != oldVal) {
764 params = lp;
765 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
766 }
767 }
768
769 if (mFirst || attachInfo.mViewVisibilityChanged) {
770 attachInfo.mViewVisibilityChanged = false;
771 int resizeMode = mSoftInputMode &
772 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
773 // If we are in auto resize mode, then we need to determine
774 // what mode to use now.
775 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
776 final int N = attachInfo.mScrollContainers.size();
777 for (int i=0; i<N; i++) {
778 if (attachInfo.mScrollContainers.get(i).isShown()) {
779 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
780 }
781 }
782 if (resizeMode == 0) {
783 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
784 }
785 if ((lp.softInputMode &
786 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
787 lp.softInputMode = (lp.softInputMode &
788 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
789 resizeMode;
790 params = lp;
791 }
792 }
793 }
Romain Guy8506ab42009-06-11 17:35:47 -0700794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
796 if (!PixelFormat.formatHasAlpha(params.format)) {
797 params.format = PixelFormat.TRANSLUCENT;
798 }
799 }
800
801 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
802 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
803
804 final boolean computesInternalInsets =
805 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
806 boolean insetsPending = false;
807 int relayoutResult = 0;
808 if (mFirst || windowShouldResize || insetsChanged
809 || viewVisibilityChanged || params != null) {
810
811 if (viewVisibility == View.VISIBLE) {
812 // If this window is giving internal insets to the window
813 // manager, and it is being added or changing its visibility,
814 // then we want to first give the window manager "fake"
815 // insets to cause it to effectively ignore the content of
816 // the window during layout. This avoids it briefly causing
817 // other windows to resize/move based on the raw frame of the
818 // window, waiting until we can finish laying out this window
819 // and get back to the window manager with the ultimately
820 // computed insets.
821 insetsPending = computesInternalInsets
822 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
825 if (params == null) {
826 params = mWindowAttributes;
827 }
828 mGlWanted = true;
829 }
830 }
831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 boolean initialized = false;
833 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700834 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 try {
836 boolean hadSurface = mSurface.isValid();
837 int fl = 0;
838 if (params != null) {
839 fl = params.flags;
840 if (attachInfo.mKeepScreenOn) {
841 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
842 }
843 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700844 if (DEBUG_LAYOUT) {
845 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
846 host.mMeasuredHeight + ", params=" + params);
847 }
848 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 if (params != null) {
851 params.flags = fl;
852 }
853
854 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
855 + " content=" + mPendingContentInsets.toShortString()
856 + " visible=" + mPendingVisibleInsets.toShortString()
857 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 contentInsetsChanged = !mPendingContentInsets.equals(
860 mAttachInfo.mContentInsets);
861 visibleInsetsChanged = !mPendingVisibleInsets.equals(
862 mAttachInfo.mVisibleInsets);
863 if (contentInsetsChanged) {
864 mAttachInfo.mContentInsets.set(mPendingContentInsets);
865 host.fitSystemWindows(mAttachInfo.mContentInsets);
866 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
867 + mAttachInfo.mContentInsets);
868 }
869 if (visibleInsetsChanged) {
870 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
871 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
872 + mAttachInfo.mVisibleInsets);
873 }
874
875 if (!hadSurface) {
876 if (mSurface.isValid()) {
877 // If we are creating a new surface, then we need to
878 // completely redraw it. Also, when we get to the
879 // point of drawing it we will hold off and schedule
880 // a new traversal instead. This is so we can tell the
881 // window manager about all of the windows being displayed
882 // before actually drawing them, so it can display then
883 // all at once.
884 newSurface = true;
885 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 if (mGlWanted && !mUseGL) {
888 initializeGL();
889 initialized = mGlCanvas != null;
890 }
891 }
892 } else if (!mSurface.isValid()) {
893 // If the surface has been removed, then reset the scroll
894 // positions.
895 mLastScrolledFocus = null;
896 mScrollY = mCurScrollY = 0;
897 if (mScroller != null) {
898 mScroller.abortAnimation();
899 }
900 }
901 } catch (RemoteException e) {
902 }
903 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700904 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
906 attachInfo.mWindowLeft = frame.left;
907 attachInfo.mWindowTop = frame.top;
908
909 // !!FIXME!! This next section handles the case where we did not get the
910 // window size we asked for. We should avoid this by getting a maximum size from
911 // the window session beforehand.
912 mWidth = frame.width();
913 mHeight = frame.height();
914
915 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -0700916 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
917 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
919
920 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
921 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
922 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
923 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
924 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
925 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
926
927 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
928 + mWidth + " measuredWidth=" + host.mMeasuredWidth
929 + " mHeight=" + mHeight
930 + " measuredHeight" + host.mMeasuredHeight
931 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 // Ask host how big it wants to be
934 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
935
936 // Implementation of weights from WindowManager.LayoutParams
937 // We just grow the dimensions as needed and re-measure if
938 // needs be
939 int width = host.mMeasuredWidth;
940 int height = host.mMeasuredHeight;
941 boolean measureAgain = false;
942
943 if (lp.horizontalWeight > 0.0f) {
944 width += (int) ((mWidth - width) * lp.horizontalWeight);
945 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
946 MeasureSpec.EXACTLY);
947 measureAgain = true;
948 }
949 if (lp.verticalWeight > 0.0f) {
950 height += (int) ((mHeight - height) * lp.verticalWeight);
951 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
952 MeasureSpec.EXACTLY);
953 measureAgain = true;
954 }
955
956 if (measureAgain) {
957 if (DEBUG_LAYOUT) Log.v(TAG,
958 "And hey let's measure once more: width=" + width
959 + " height=" + height);
960 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
961 }
962
963 mLayoutRequested = true;
964 }
965 }
966
967 final boolean didLayout = mLayoutRequested;
968 boolean triggerGlobalLayoutListener = didLayout
969 || attachInfo.mRecomputeGlobalAttributes;
970 if (didLayout) {
971 mLayoutRequested = false;
972 mScrollMayChange = true;
973 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
974 "ViewRoot", "Laying out " + host + " to (" +
975 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700976 long startTime = 0L;
977 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 startTime = SystemClock.elapsedRealtime();
979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
981
Romain Guy13922e02009-05-12 17:56:14 -0700982 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
983 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
984 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
985 + "please refer to the logs with the tag "
986 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
987 }
988 }
989
990 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
992 }
993
994 // By this point all views have been sized and positionned
995 // We can compute the transparent area
996
997 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
998 // start out transparent
999 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1000 host.getLocationInWindow(mTmpLocation);
1001 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1002 mTmpLocation[0] + host.mRight - host.mLeft,
1003 mTmpLocation[1] + host.mBottom - host.mTop);
1004
1005 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001006 if (mTranslator != null) {
1007 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1008 }
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1011 mPreviousTransparentRegion.set(mTransparentRegion);
1012 // reconfigure window manager
1013 try {
1014 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1015 } catch (RemoteException e) {
1016 }
1017 }
1018 }
1019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 if (DBG) {
1021 System.out.println("======================================");
1022 System.out.println("performTraversals -- after setFrame");
1023 host.debug();
1024 }
1025 }
1026
1027 if (triggerGlobalLayoutListener) {
1028 attachInfo.mRecomputeGlobalAttributes = false;
1029 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1030 }
1031
1032 if (computesInternalInsets) {
1033 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1034 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1035 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1036 givenContent.left = givenContent.top = givenContent.right
1037 = givenContent.bottom = givenVisible.left = givenVisible.top
1038 = givenVisible.right = givenVisible.bottom = 0;
1039 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001040 Rect contentInsets = insets.contentInsets;
1041 Rect visibleInsets = insets.visibleInsets;
1042 if (mTranslator != null) {
1043 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1044 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1047 mLastGivenInsets.set(insets);
1048 try {
1049 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001050 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 } catch (RemoteException e) {
1052 }
1053 }
1054 }
Romain Guy8506ab42009-06-11 17:35:47 -07001055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 if (mFirst) {
1057 // handle first focus request
1058 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1059 + mView.hasFocus());
1060 if (mView != null) {
1061 if (!mView.hasFocus()) {
1062 mView.requestFocus(View.FOCUS_FORWARD);
1063 mFocusedView = mRealFocusedView = mView.findFocus();
1064 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1065 + mFocusedView);
1066 } else {
1067 mRealFocusedView = mView.findFocus();
1068 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1069 + mRealFocusedView);
1070 }
1071 }
1072 }
1073
1074 mFirst = false;
1075 mWillDrawSoon = false;
1076 mNewSurfaceNeeded = false;
1077 mViewVisibility = viewVisibility;
1078
1079 if (mAttachInfo.mHasWindowFocus) {
1080 final boolean imTarget = WindowManager.LayoutParams
1081 .mayUseInputMethod(mWindowAttributes.flags);
1082 if (imTarget != mLastWasImTarget) {
1083 mLastWasImTarget = imTarget;
1084 InputMethodManager imm = InputMethodManager.peekInstance();
1085 if (imm != null && imTarget) {
1086 imm.startGettingWindowFocus(mView);
1087 imm.onWindowFocus(mView, mView.findFocus(),
1088 mWindowAttributes.softInputMode,
1089 !mHasHadWindowFocus, mWindowAttributes.flags);
1090 }
1091 }
1092 }
Romain Guy8506ab42009-06-11 17:35:47 -07001093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1095
1096 if (!cancelDraw && !newSurface) {
1097 mFullRedrawNeeded = false;
1098 draw(fullRedrawNeeded);
1099
1100 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1101 || mReportNextDraw) {
1102 if (LOCAL_LOGV) {
1103 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1104 }
1105 mReportNextDraw = false;
1106 try {
1107 sWindowSession.finishDrawing(mWindow);
1108 } catch (RemoteException e) {
1109 }
1110 }
1111 } else {
1112 // We were supposed to report when we are done drawing. Since we canceled the
1113 // draw, remember it here.
1114 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1115 mReportNextDraw = true;
1116 }
1117 if (fullRedrawNeeded) {
1118 mFullRedrawNeeded = true;
1119 }
1120 // Try again
1121 scheduleTraversals();
1122 }
1123 }
1124
1125 public void requestTransparentRegion(View child) {
1126 // the test below should not fail unless someone is messing with us
1127 checkThread();
1128 if (mView == child) {
1129 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1130 // Need to make sure we re-evaluate the window attributes next
1131 // time around, to ensure the window has the correct format.
1132 mWindowAttributesChanged = true;
1133 }
1134 }
1135
1136 /**
1137 * Figures out the measure spec for the root view in a window based on it's
1138 * layout params.
1139 *
1140 * @param windowSize
1141 * The available width or height of the window
1142 *
1143 * @param rootDimension
1144 * The layout params for one dimension (width or height) of the
1145 * window.
1146 *
1147 * @return The measure spec to use to measure the root view.
1148 */
1149 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1150 int measureSpec;
1151 switch (rootDimension) {
1152
1153 case ViewGroup.LayoutParams.FILL_PARENT:
1154 // Window can't resize. Force root view to be windowSize.
1155 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1156 break;
1157 case ViewGroup.LayoutParams.WRAP_CONTENT:
1158 // Window can resize. Set max size for root view.
1159 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1160 break;
1161 default:
1162 // Window wants to be an exact size. Force root view to be that size.
1163 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1164 break;
1165 }
1166 return measureSpec;
1167 }
1168
1169 private void draw(boolean fullRedrawNeeded) {
1170 Surface surface = mSurface;
1171 if (surface == null || !surface.isValid()) {
1172 return;
1173 }
1174
1175 scrollToRectOrFocus(null, false);
1176
1177 if (mAttachInfo.mViewScrollChanged) {
1178 mAttachInfo.mViewScrollChanged = false;
1179 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1180 }
Romain Guy8506ab42009-06-11 17:35:47 -07001181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001183 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 if (scrolling) {
1185 yoff = mScroller.getCurrY();
1186 } else {
1187 yoff = mScrollY;
1188 }
1189 if (mCurScrollY != yoff) {
1190 mCurScrollY = yoff;
1191 fullRedrawNeeded = true;
1192 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001193 float appScale = mAttachInfo.mApplicationScale;
1194 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195
1196 Rect dirty = mDirty;
1197 if (mUseGL) {
1198 if (!dirty.isEmpty()) {
1199 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001200 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 mGL.glDisable(GL_SCISSOR_TEST);
1202 mGL.glClearColor(0, 0, 0, 0);
1203 mGL.glClear(GL_COLOR_BUFFER_BIT);
1204 mGL.glEnable(GL_SCISSOR_TEST);
1205
1206 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001207 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001209
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001210 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1211 try {
1212 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001213 if (mTranslator != null) {
1214 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001215 }
1216 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001217 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1218 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1219 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001220 } finally {
1221 canvas.restoreToCount(saveCount);
1222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223
Romain Guy5bcdff42009-05-14 21:27:18 -07001224 mAttachInfo.mIgnoreDirtyState = false;
1225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1227 checkEglErrors();
1228
Romain Guy13922e02009-05-12 17:56:14 -07001229 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 int now = (int)SystemClock.elapsedRealtime();
1231 if (sDrawTime != 0) {
1232 nativeShowFPS(canvas, now - sDrawTime);
1233 }
1234 sDrawTime = now;
1235 }
1236 }
1237 }
1238 if (scrolling) {
1239 mFullRedrawNeeded = true;
1240 scheduleTraversals();
1241 }
1242 return;
1243 }
1244
Romain Guy5bcdff42009-05-14 21:27:18 -07001245 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001246 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001247 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249
1250 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1251 Log.v("ViewRoot", "Draw " + mView + "/"
1252 + mWindowAttributes.getTitle()
1253 + ": dirty={" + dirty.left + "," + dirty.top
1254 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001255 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1256 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258
1259 Canvas canvas;
1260 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001261 int left = dirty.left;
1262 int top = dirty.top;
1263 int right = dirty.right;
1264 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001266
1267 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1268 bottom != dirty.bottom) {
1269 mAttachInfo.mIgnoreDirtyState = true;
1270 }
1271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 // TODO: Do this in native
1273 canvas.setDensityScale(mDensity);
1274 } catch (Surface.OutOfResourcesException e) {
1275 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1276 // TODO: we should ask the window manager to do something!
1277 // for now we just do nothing
1278 return;
1279 }
1280
1281 try {
Romain Guybb93d552009-03-24 21:04:15 -07001282 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001283 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284
1285 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1286 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1287 + canvas.getWidth() + ", h=" + canvas.getHeight());
1288 //canvas.drawARGB(255, 255, 0, 0);
1289 }
1290
Romain Guy13922e02009-05-12 17:56:14 -07001291 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 startTime = SystemClock.elapsedRealtime();
1293 }
1294
1295 // If this bitmap's format includes an alpha channel, we
1296 // need to clear it before drawing so that the child will
1297 // properly re-composite its drawing on a transparent
1298 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001299 // or
1300 // If we are applying an offset, we need to clear the area
1301 // where the offset doesn't appear to avoid having garbage
1302 // left in the blank areas.
1303 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1305 }
1306
1307 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001308 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001310 mView.mPrivateFlags |= View.DRAWN;
1311
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001312 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001313 Context cxt = mView.getContext();
1314 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -07001315 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1316 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001317 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001318 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001319 try {
1320 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001321 if (mTranslator != null) {
1322 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001323 }
1324 mView.draw(canvas);
1325 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001326 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001327 canvas.restoreToCount(saveCount);
1328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329
Romain Guy5bcdff42009-05-14 21:27:18 -07001330 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1331 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1332 }
1333
Romain Guy13922e02009-05-12 17:56:14 -07001334 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 int now = (int)SystemClock.elapsedRealtime();
1336 if (sDrawTime != 0) {
1337 nativeShowFPS(canvas, now - sDrawTime);
1338 }
1339 sDrawTime = now;
1340 }
1341
Romain Guy13922e02009-05-12 17:56:14 -07001342 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1344 }
1345 }
Romain Guy8506ab42009-06-11 17:35:47 -07001346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 } finally {
1348 surface.unlockCanvasAndPost(canvas);
1349 }
1350
1351 if (LOCAL_LOGV) {
1352 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1353 }
Romain Guy8506ab42009-06-11 17:35:47 -07001354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 if (scrolling) {
1356 mFullRedrawNeeded = true;
1357 scheduleTraversals();
1358 }
1359 }
1360
1361 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1362 final View.AttachInfo attachInfo = mAttachInfo;
1363 final Rect ci = attachInfo.mContentInsets;
1364 final Rect vi = attachInfo.mVisibleInsets;
1365 int scrollY = 0;
1366 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 if (vi.left > ci.left || vi.top > ci.top
1369 || vi.right > ci.right || vi.bottom > ci.bottom) {
1370 // We'll assume that we aren't going to change the scroll
1371 // offset, since we want to avoid that unless it is actually
1372 // going to make the focus visible... otherwise we scroll
1373 // all over the place.
1374 scrollY = mScrollY;
1375 // We can be called for two different situations: during a draw,
1376 // to update the scroll position if the focus has changed (in which
1377 // case 'rectangle' is null), or in response to a
1378 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1379 // is non-null and we just want to scroll to whatever that
1380 // rectangle is).
1381 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001382
1383 // When in touch mode, focus points to the previously focused view,
1384 // which may have been removed from the view hierarchy. The following
1385 // line checks whether the view is still in the hierarchy
1386 if (focus == null || focus.getParent() == null) {
1387 mRealFocusedView = null;
1388 return false;
1389 }
1390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 if (focus != mLastScrolledFocus) {
1392 // If the focus has changed, then ignore any requests to scroll
1393 // to a rectangle; first we want to make sure the entire focus
1394 // view is visible.
1395 rectangle = null;
1396 }
1397 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1398 + " rectangle=" + rectangle + " ci=" + ci
1399 + " vi=" + vi);
1400 if (focus == mLastScrolledFocus && !mScrollMayChange
1401 && rectangle == null) {
1402 // Optimization: if the focus hasn't changed since last
1403 // time, and no layout has happened, then just leave things
1404 // as they are.
1405 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1406 + mScrollY + " vi=" + vi.toShortString());
1407 } else if (focus != null) {
1408 // We need to determine if the currently focused view is
1409 // within the visible part of the window and, if not, apply
1410 // a pan so it can be seen.
1411 mLastScrolledFocus = focus;
1412 mScrollMayChange = false;
1413 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1414 // Try to find the rectangle from the focus view.
1415 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1416 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1417 + mView.getWidth() + " h=" + mView.getHeight()
1418 + " ci=" + ci.toShortString()
1419 + " vi=" + vi.toShortString());
1420 if (rectangle == null) {
1421 focus.getFocusedRect(mTempRect);
1422 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1423 + ": focusRect=" + mTempRect.toShortString());
1424 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1425 focus, mTempRect);
1426 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1427 "Focus in window: focusRect="
1428 + mTempRect.toShortString()
1429 + " visRect=" + mVisRect.toShortString());
1430 } else {
1431 mTempRect.set(rectangle);
1432 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1433 "Request scroll to rect: "
1434 + mTempRect.toShortString()
1435 + " visRect=" + mVisRect.toShortString());
1436 }
1437 if (mTempRect.intersect(mVisRect)) {
1438 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1439 "Focus window visible rect: "
1440 + mTempRect.toShortString());
1441 if (mTempRect.height() >
1442 (mView.getHeight()-vi.top-vi.bottom)) {
1443 // If the focus simply is not going to fit, then
1444 // best is probably just to leave things as-is.
1445 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1446 "Too tall; leaving scrollY=" + scrollY);
1447 } else if ((mTempRect.top-scrollY) < vi.top) {
1448 scrollY -= vi.top - (mTempRect.top-scrollY);
1449 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1450 "Top covered; scrollY=" + scrollY);
1451 } else if ((mTempRect.bottom-scrollY)
1452 > (mView.getHeight()-vi.bottom)) {
1453 scrollY += (mTempRect.bottom-scrollY)
1454 - (mView.getHeight()-vi.bottom);
1455 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1456 "Bottom covered; scrollY=" + scrollY);
1457 }
1458 handled = true;
1459 }
1460 }
1461 }
1462 }
Romain Guy8506ab42009-06-11 17:35:47 -07001463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 if (scrollY != mScrollY) {
1465 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1466 + mScrollY + " , new=" + scrollY);
1467 if (!immediate) {
1468 if (mScroller == null) {
1469 mScroller = new Scroller(mView.getContext());
1470 }
1471 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1472 } else if (mScroller != null) {
1473 mScroller.abortAnimation();
1474 }
1475 mScrollY = scrollY;
1476 }
Romain Guy8506ab42009-06-11 17:35:47 -07001477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 return handled;
1479 }
Romain Guy8506ab42009-06-11 17:35:47 -07001480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 public void requestChildFocus(View child, View focused) {
1482 checkThread();
1483 if (mFocusedView != focused) {
1484 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1485 scheduleTraversals();
1486 }
1487 mFocusedView = mRealFocusedView = focused;
1488 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1489 + mFocusedView);
1490 }
1491
1492 public void clearChildFocus(View child) {
1493 checkThread();
1494
1495 View oldFocus = mFocusedView;
1496
1497 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1498 mFocusedView = mRealFocusedView = null;
1499 if (mView != null && !mView.hasFocus()) {
1500 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1501 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1502 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1503 }
1504 } else if (oldFocus != null) {
1505 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1506 }
1507 }
1508
1509
1510 public void focusableViewAvailable(View v) {
1511 checkThread();
1512
1513 if (mView != null && !mView.hasFocus()) {
1514 v.requestFocus();
1515 } else {
1516 // the one case where will transfer focus away from the current one
1517 // is if the current view is a view group that prefers to give focus
1518 // to its children first AND the view is a descendant of it.
1519 mFocusedView = mView.findFocus();
1520 boolean descendantsHaveDibsOnFocus =
1521 (mFocusedView instanceof ViewGroup) &&
1522 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1523 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1524 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1525 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1526 v.requestFocus();
1527 }
1528 }
1529 }
1530
1531 public void recomputeViewAttributes(View child) {
1532 checkThread();
1533 if (mView == child) {
1534 mAttachInfo.mRecomputeGlobalAttributes = true;
1535 if (!mWillDrawSoon) {
1536 scheduleTraversals();
1537 }
1538 }
1539 }
1540
1541 void dispatchDetachedFromWindow() {
1542 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1543
1544 if (mView != null) {
1545 mView.dispatchDetachedFromWindow();
1546 }
1547
1548 mView = null;
1549 mAttachInfo.mRootView = null;
1550
1551 if (mUseGL) {
1552 destroyGL();
1553 }
1554
1555 try {
1556 sWindowSession.remove(mWindow);
1557 } catch (RemoteException e) {
1558 }
1559 }
Romain Guy8506ab42009-06-11 17:35:47 -07001560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 /**
1562 * Return true if child is an ancestor of parent, (or equal to the parent).
1563 */
1564 private static boolean isViewDescendantOf(View child, View parent) {
1565 if (child == parent) {
1566 return true;
1567 }
1568
1569 final ViewParent theParent = child.getParent();
1570 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1571 }
1572
1573
1574 public final static int DO_TRAVERSAL = 1000;
1575 public final static int DIE = 1001;
1576 public final static int RESIZED = 1002;
1577 public final static int RESIZED_REPORT = 1003;
1578 public final static int WINDOW_FOCUS_CHANGED = 1004;
1579 public final static int DISPATCH_KEY = 1005;
1580 public final static int DISPATCH_POINTER = 1006;
1581 public final static int DISPATCH_TRACKBALL = 1007;
1582 public final static int DISPATCH_APP_VISIBILITY = 1008;
1583 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1584 public final static int FINISHED_EVENT = 1010;
1585 public final static int DISPATCH_KEY_FROM_IME = 1011;
1586 public final static int FINISH_INPUT_CONNECTION = 1012;
1587 public final static int CHECK_FOCUS = 1013;
1588
1589 @Override
1590 public void handleMessage(Message msg) {
1591 switch (msg.what) {
1592 case View.AttachInfo.INVALIDATE_MSG:
1593 ((View) msg.obj).invalidate();
1594 break;
1595 case View.AttachInfo.INVALIDATE_RECT_MSG:
1596 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1597 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1598 info.release();
1599 break;
1600 case DO_TRAVERSAL:
1601 if (mProfile) {
1602 Debug.startMethodTracing("ViewRoot");
1603 }
1604
1605 performTraversals();
1606
1607 if (mProfile) {
1608 Debug.stopMethodTracing();
1609 mProfile = false;
1610 }
1611 break;
1612 case FINISHED_EVENT:
1613 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1614 break;
1615 case DISPATCH_KEY:
1616 if (LOCAL_LOGV) Log.v(
1617 "ViewRoot", "Dispatching key "
1618 + msg.obj + " to " + mView);
1619 deliverKeyEvent((KeyEvent)msg.obj, true);
1620 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001621 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 MotionEvent event = (MotionEvent)msg.obj;
1623
1624 boolean didFinish;
1625 if (event == null) {
1626 try {
1627 event = sWindowSession.getPendingPointerMove(mWindow);
1628 } catch (RemoteException e) {
1629 }
1630 didFinish = true;
1631 } else {
1632 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
1633 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001634 if (event != null && mTranslator != null) {
1635 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 try {
1638 boolean handled;
1639 if (mView != null && mAdded && event != null) {
1640
1641 // enter touch mode on the down
1642 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1643 if (isDown) {
1644 ensureTouchMode(true);
1645 }
1646 if(Config.LOGV) {
1647 captureMotionLog("captureDispatchPointer", event);
1648 }
1649 event.offsetLocation(0, mCurScrollY);
1650 handled = mView.dispatchTouchEvent(event);
1651 if (!handled && isDown) {
1652 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1653
1654 final int edgeFlags = event.getEdgeFlags();
1655 int direction = View.FOCUS_UP;
1656 int x = (int)event.getX();
1657 int y = (int)event.getY();
1658 final int[] deltas = new int[2];
1659
1660 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1661 direction = View.FOCUS_DOWN;
1662 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1663 deltas[0] = edgeSlop;
1664 x += edgeSlop;
1665 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1666 deltas[0] = -edgeSlop;
1667 x -= edgeSlop;
1668 }
1669 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1670 direction = View.FOCUS_UP;
1671 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1672 deltas[0] = edgeSlop;
1673 x += edgeSlop;
1674 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1675 deltas[0] = -edgeSlop;
1676 x -= edgeSlop;
1677 }
1678 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1679 direction = View.FOCUS_RIGHT;
1680 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1681 direction = View.FOCUS_LEFT;
1682 }
1683
1684 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1685 View nearest = FocusFinder.getInstance().findNearestTouchable(
1686 ((ViewGroup) mView), x, y, direction, deltas);
1687 if (nearest != null) {
1688 event.offsetLocation(deltas[0], deltas[1]);
1689 event.setEdgeFlags(0);
1690 mView.dispatchTouchEvent(event);
1691 }
1692 }
1693 }
1694 }
1695 } finally {
1696 if (!didFinish) {
1697 try {
1698 sWindowSession.finishKey(mWindow);
1699 } catch (RemoteException e) {
1700 }
1701 }
1702 if (event != null) {
1703 event.recycle();
1704 }
1705 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1706 // Let the exception fall through -- the looper will catch
1707 // it and take care of the bad app for us.
1708 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001709 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 case DISPATCH_TRACKBALL:
1711 deliverTrackballEvent((MotionEvent)msg.obj);
1712 break;
1713 case DISPATCH_APP_VISIBILITY:
1714 handleAppVisibility(msg.arg1 != 0);
1715 break;
1716 case DISPATCH_GET_NEW_SURFACE:
1717 handleGetNewSurface();
1718 break;
1719 case RESIZED:
1720 Rect coveredInsets = ((Rect[])msg.obj)[0];
1721 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1724 && mPendingContentInsets.equals(coveredInsets)
1725 && mPendingVisibleInsets.equals(visibleInsets)) {
1726 break;
1727 }
1728 // fall through...
1729 case RESIZED_REPORT:
1730 if (mAdded) {
1731 mWinFrame.left = 0;
1732 mWinFrame.right = msg.arg1;
1733 mWinFrame.top = 0;
1734 mWinFrame.bottom = msg.arg2;
1735 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1736 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1737 if (msg.what == RESIZED_REPORT) {
1738 mReportNextDraw = true;
1739 }
1740 requestLayout();
1741 }
1742 break;
1743 case WINDOW_FOCUS_CHANGED: {
1744 if (mAdded) {
1745 boolean hasWindowFocus = msg.arg1 != 0;
1746 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1747 if (hasWindowFocus) {
1748 boolean inTouchMode = msg.arg2 != 0;
1749 ensureTouchModeLocally(inTouchMode);
1750
1751 if (mGlWanted) {
1752 checkEglErrors();
1753 // we lost the gl context, so recreate it.
1754 if (mGlWanted && !mUseGL) {
1755 initializeGL();
1756 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001757 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001758 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001759 (int) (mWidth * appScale + 0.5f),
1760 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762 }
1763 }
1764 }
Romain Guy8506ab42009-06-11 17:35:47 -07001765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 mLastWasImTarget = WindowManager.LayoutParams
1767 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 InputMethodManager imm = InputMethodManager.peekInstance();
1770 if (mView != null) {
1771 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1772 imm.startGettingWindowFocus(mView);
1773 }
1774 mView.dispatchWindowFocusChanged(hasWindowFocus);
1775 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 // Note: must be done after the focus change callbacks,
1778 // so all of the view state is set up correctly.
1779 if (hasWindowFocus) {
1780 if (imm != null && mLastWasImTarget) {
1781 imm.onWindowFocus(mView, mView.findFocus(),
1782 mWindowAttributes.softInputMode,
1783 !mHasHadWindowFocus, mWindowAttributes.flags);
1784 }
1785 // Clear the forward bit. We can just do this directly, since
1786 // the window manager doesn't care about it.
1787 mWindowAttributes.softInputMode &=
1788 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1789 ((WindowManager.LayoutParams)mView.getLayoutParams())
1790 .softInputMode &=
1791 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1792 mHasHadWindowFocus = true;
1793 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001794
1795 if (hasWindowFocus && mView != null) {
1796 sendAccessibilityEvents();
1797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799 } break;
1800 case DIE:
1801 dispatchDetachedFromWindow();
1802 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001803 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 if (LOCAL_LOGV) Log.v(
1805 "ViewRoot", "Dispatching key "
1806 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001807 KeyEvent event = (KeyEvent)msg.obj;
1808 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1809 // The IME is trying to say this event is from the
1810 // system! Bad bad bad!
1811 event = KeyEvent.changeFlags(event,
1812 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001815 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 case FINISH_INPUT_CONNECTION: {
1817 InputMethodManager imm = InputMethodManager.peekInstance();
1818 if (imm != null) {
1819 imm.reportFinishInputConnection((InputConnection)msg.obj);
1820 }
1821 } break;
1822 case CHECK_FOCUS: {
1823 InputMethodManager imm = InputMethodManager.peekInstance();
1824 if (imm != null) {
1825 imm.checkFocus();
1826 }
1827 } break;
1828 }
1829 }
1830
1831 /**
1832 * Something in the current window tells us we need to change the touch mode. For
1833 * example, we are not in touch mode, and the user touches the screen.
1834 *
1835 * If the touch mode has changed, tell the window manager, and handle it locally.
1836 *
1837 * @param inTouchMode Whether we want to be in touch mode.
1838 * @return True if the touch mode changed and focus changed was changed as a result
1839 */
1840 boolean ensureTouchMode(boolean inTouchMode) {
1841 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1842 + "touch mode is " + mAttachInfo.mInTouchMode);
1843 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1844
1845 // tell the window manager
1846 try {
1847 sWindowSession.setInTouchMode(inTouchMode);
1848 } catch (RemoteException e) {
1849 throw new RuntimeException(e);
1850 }
1851
1852 // handle the change
1853 return ensureTouchModeLocally(inTouchMode);
1854 }
1855
1856 /**
1857 * Ensure that the touch mode for this window is set, and if it is changing,
1858 * take the appropriate action.
1859 * @param inTouchMode Whether we want to be in touch mode.
1860 * @return True if the touch mode changed and focus changed was changed as a result
1861 */
1862 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1863 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1864 + "touch mode is " + mAttachInfo.mInTouchMode);
1865
1866 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1867
1868 mAttachInfo.mInTouchMode = inTouchMode;
1869 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1870
1871 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1872 }
1873
1874 private boolean enterTouchMode() {
1875 if (mView != null) {
1876 if (mView.hasFocus()) {
1877 // note: not relying on mFocusedView here because this could
1878 // be when the window is first being added, and mFocused isn't
1879 // set yet.
1880 final View focused = mView.findFocus();
1881 if (focused != null && !focused.isFocusableInTouchMode()) {
1882
1883 final ViewGroup ancestorToTakeFocus =
1884 findAncestorToTakeFocusInTouchMode(focused);
1885 if (ancestorToTakeFocus != null) {
1886 // there is an ancestor that wants focus after its descendants that
1887 // is focusable in touch mode.. give it focus
1888 return ancestorToTakeFocus.requestFocus();
1889 } else {
1890 // nothing appropriate to have focus in touch mode, clear it out
1891 mView.unFocus();
1892 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1893 mFocusedView = null;
1894 return true;
1895 }
1896 }
1897 }
1898 }
1899 return false;
1900 }
1901
1902
1903 /**
1904 * Find an ancestor of focused that wants focus after its descendants and is
1905 * focusable in touch mode.
1906 * @param focused The currently focused view.
1907 * @return An appropriate view, or null if no such view exists.
1908 */
1909 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1910 ViewParent parent = focused.getParent();
1911 while (parent instanceof ViewGroup) {
1912 final ViewGroup vgParent = (ViewGroup) parent;
1913 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1914 && vgParent.isFocusableInTouchMode()) {
1915 return vgParent;
1916 }
1917 if (vgParent.isRootNamespace()) {
1918 return null;
1919 } else {
1920 parent = vgParent.getParent();
1921 }
1922 }
1923 return null;
1924 }
1925
1926 private boolean leaveTouchMode() {
1927 if (mView != null) {
1928 if (mView.hasFocus()) {
1929 // i learned the hard way to not trust mFocusedView :)
1930 mFocusedView = mView.findFocus();
1931 if (!(mFocusedView instanceof ViewGroup)) {
1932 // some view has focus, let it keep it
1933 return false;
1934 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1935 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1936 // some view group has focus, and doesn't prefer its children
1937 // over itself for focus, so let them keep it.
1938 return false;
1939 }
1940 }
1941
1942 // find the best view to give focus to in this brave new non-touch-mode
1943 // world
1944 final View focused = focusSearch(null, View.FOCUS_DOWN);
1945 if (focused != null) {
1946 return focused.requestFocus(View.FOCUS_DOWN);
1947 }
1948 }
1949 return false;
1950 }
1951
1952
1953 private void deliverTrackballEvent(MotionEvent event) {
1954 boolean didFinish;
1955 if (event == null) {
1956 try {
1957 event = sWindowSession.getPendingTrackballMove(mWindow);
1958 } catch (RemoteException e) {
1959 }
1960 didFinish = true;
1961 } else {
1962 didFinish = false;
1963 }
1964
1965 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
1966
1967 boolean handled = false;
1968 try {
1969 if (event == null) {
1970 handled = true;
1971 } else if (mView != null && mAdded) {
1972 handled = mView.dispatchTrackballEvent(event);
1973 if (!handled) {
1974 // we could do something here, like changing the focus
1975 // or something?
1976 }
1977 }
1978 } finally {
1979 if (handled) {
1980 if (!didFinish) {
1981 try {
1982 sWindowSession.finishKey(mWindow);
1983 } catch (RemoteException e) {
1984 }
1985 }
1986 if (event != null) {
1987 event.recycle();
1988 }
1989 // If we reach this, we delivered a trackball event to mView and
1990 // mView consumed it. Because we will not translate the trackball
1991 // event into a key event, touch mode will not exit, so we exit
1992 // touch mode here.
1993 ensureTouchMode(false);
1994 //noinspection ReturnInsideFinallyBlock
1995 return;
1996 }
1997 // Let the exception fall through -- the looper will catch
1998 // it and take care of the bad app for us.
1999 }
2000
2001 final TrackballAxis x = mTrackballAxisX;
2002 final TrackballAxis y = mTrackballAxisY;
2003
2004 long curTime = SystemClock.uptimeMillis();
2005 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2006 // It has been too long since the last movement,
2007 // so restart at the beginning.
2008 x.reset(0);
2009 y.reset(0);
2010 mLastTrackballTime = curTime;
2011 }
2012
2013 try {
2014 final int action = event.getAction();
2015 final int metastate = event.getMetaState();
2016 switch (action) {
2017 case MotionEvent.ACTION_DOWN:
2018 x.reset(2);
2019 y.reset(2);
2020 deliverKeyEvent(new KeyEvent(curTime, curTime,
2021 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2022 0, metastate), false);
2023 break;
2024 case MotionEvent.ACTION_UP:
2025 x.reset(2);
2026 y.reset(2);
2027 deliverKeyEvent(new KeyEvent(curTime, curTime,
2028 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2029 0, metastate), false);
2030 break;
2031 }
2032
2033 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2034 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2035 + " move=" + event.getX()
2036 + " / Y=" + y.position + " step="
2037 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2038 + " move=" + event.getY());
2039 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2040 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2041
2042 // Generate DPAD events based on the trackball movement.
2043 // We pick the axis that has moved the most as the direction of
2044 // the DPAD. When we generate DPAD events for one axis, then the
2045 // other axis is reset -- we don't want to perform DPAD jumps due
2046 // to slight movements in the trackball when making major movements
2047 // along the other axis.
2048 int keycode = 0;
2049 int movement = 0;
2050 float accel = 1;
2051 if (xOff > yOff) {
2052 movement = x.generate((2/event.getXPrecision()));
2053 if (movement != 0) {
2054 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2055 : KeyEvent.KEYCODE_DPAD_LEFT;
2056 accel = x.acceleration;
2057 y.reset(2);
2058 }
2059 } else if (yOff > 0) {
2060 movement = y.generate((2/event.getYPrecision()));
2061 if (movement != 0) {
2062 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2063 : KeyEvent.KEYCODE_DPAD_UP;
2064 accel = y.acceleration;
2065 x.reset(2);
2066 }
2067 }
2068
2069 if (keycode != 0) {
2070 if (movement < 0) movement = -movement;
2071 int accelMovement = (int)(movement * accel);
2072 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2073 + " accelMovement=" + accelMovement
2074 + " accel=" + accel);
2075 if (accelMovement > movement) {
2076 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2077 + keycode);
2078 movement--;
2079 deliverKeyEvent(new KeyEvent(curTime, curTime,
2080 KeyEvent.ACTION_MULTIPLE, keycode,
2081 accelMovement-movement, metastate), false);
2082 }
2083 while (movement > 0) {
2084 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2085 + keycode);
2086 movement--;
2087 curTime = SystemClock.uptimeMillis();
2088 deliverKeyEvent(new KeyEvent(curTime, curTime,
2089 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2090 deliverKeyEvent(new KeyEvent(curTime, curTime,
2091 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2092 }
2093 mLastTrackballTime = curTime;
2094 }
2095 } finally {
2096 if (!didFinish) {
2097 try {
2098 sWindowSession.finishKey(mWindow);
2099 } catch (RemoteException e) {
2100 }
2101 if (event != null) {
2102 event.recycle();
2103 }
2104 }
2105 // Let the exception fall through -- the looper will catch
2106 // it and take care of the bad app for us.
2107 }
2108 }
2109
2110 /**
2111 * @param keyCode The key code
2112 * @return True if the key is directional.
2113 */
2114 static boolean isDirectional(int keyCode) {
2115 switch (keyCode) {
2116 case KeyEvent.KEYCODE_DPAD_LEFT:
2117 case KeyEvent.KEYCODE_DPAD_RIGHT:
2118 case KeyEvent.KEYCODE_DPAD_UP:
2119 case KeyEvent.KEYCODE_DPAD_DOWN:
2120 return true;
2121 }
2122 return false;
2123 }
2124
2125 /**
2126 * Returns true if this key is a keyboard key.
2127 * @param keyEvent The key event.
2128 * @return whether this key is a keyboard key.
2129 */
2130 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2131 final int convertedKey = keyEvent.getUnicodeChar();
2132 return convertedKey > 0;
2133 }
2134
2135
2136
2137 /**
2138 * See if the key event means we should leave touch mode (and leave touch
2139 * mode if so).
2140 * @param event The key event.
2141 * @return Whether this key event should be consumed (meaning the act of
2142 * leaving touch mode alone is considered the event).
2143 */
2144 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2145 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2146 return false;
2147 }
2148 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2149 return false;
2150 }
2151
2152 // only relevant if we are in touch mode
2153 if (!mAttachInfo.mInTouchMode) {
2154 return false;
2155 }
2156
2157 // if something like an edit text has focus and the user is typing,
2158 // leave touch mode
2159 //
2160 // note: the condition of not being a keyboard key is kind of a hacky
2161 // approximation of whether we think the focused view will want the
2162 // key; if we knew for sure whether the focused view would consume
2163 // the event, that would be better.
2164 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2165 mFocusedView = mView.findFocus();
2166 if ((mFocusedView instanceof ViewGroup)
2167 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2168 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2169 // something has focus, but is holding it weakly as a container
2170 return false;
2171 }
2172 if (ensureTouchMode(false)) {
2173 throw new IllegalStateException("should not have changed focus "
2174 + "when leaving touch mode while a view has focus.");
2175 }
2176 return false;
2177 }
2178
2179 if (isDirectional(event.getKeyCode())) {
2180 // no view has focus, so we leave touch mode (and find something
2181 // to give focus to). the event is consumed if we were able to
2182 // find something to give focus to.
2183 return ensureTouchMode(false);
2184 }
2185 return false;
2186 }
2187
2188 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002189 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 */
2191 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002192 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 if (ev == null ||
2194 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2195 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
Romain Guy8506ab42009-06-11 17:35:47 -07002197
2198 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 sb.append(ev.getDownTime()).append(',');
2200 sb.append(ev.getEventTime()).append(',');
2201 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002202 sb.append(ev.getX()).append(',');
2203 sb.append(ev.getY()).append(',');
2204 sb.append(ev.getPressure()).append(',');
2205 sb.append(ev.getSize()).append(',');
2206 sb.append(ev.getMetaState()).append(',');
2207 sb.append(ev.getXPrecision()).append(',');
2208 sb.append(ev.getYPrecision()).append(',');
2209 sb.append(ev.getDeviceId()).append(',');
2210 sb.append(ev.getEdgeFlags());
2211 Log.d(TAG, sb.toString());
2212 }
2213 /**
2214 * log motion events
2215 */
2216 private static void captureKeyLog(String subTag, KeyEvent ev) {
2217 //check dynamic switch
2218 if (ev == null ||
2219 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2220 return;
2221 }
2222 StringBuilder sb = new StringBuilder(subTag + ": ");
2223 sb.append(ev.getDownTime()).append(',');
2224 sb.append(ev.getEventTime()).append(',');
2225 sb.append(ev.getAction()).append(',');
2226 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 sb.append(ev.getRepeatCount()).append(',');
2228 sb.append(ev.getMetaState()).append(',');
2229 sb.append(ev.getDeviceId()).append(',');
2230 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002231 Log.d(TAG, sb.toString());
2232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233
2234 int enqueuePendingEvent(Object event, boolean sendDone) {
2235 int seq = mPendingEventSeq+1;
2236 if (seq < 0) seq = 0;
2237 mPendingEventSeq = seq;
2238 mPendingEvents.put(seq, event);
2239 return sendDone ? seq : -seq;
2240 }
2241
2242 Object retrievePendingEvent(int seq) {
2243 if (seq < 0) seq = -seq;
2244 Object event = mPendingEvents.get(seq);
2245 if (event != null) {
2246 mPendingEvents.remove(seq);
2247 }
2248 return event;
2249 }
Romain Guy8506ab42009-06-11 17:35:47 -07002250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2252 // If mView is null, we just consume the key event because it doesn't
2253 // make sense to do anything else with it.
2254 boolean handled = mView != null
2255 ? mView.dispatchKeyEventPreIme(event) : true;
2256 if (handled) {
2257 if (sendDone) {
2258 if (LOCAL_LOGV) Log.v(
2259 "ViewRoot", "Telling window manager key is finished");
2260 try {
2261 sWindowSession.finishKey(mWindow);
2262 } catch (RemoteException e) {
2263 }
2264 }
2265 return;
2266 }
2267 // If it is possible for this window to interact with the input
2268 // method window, then we want to first dispatch our key events
2269 // to the input method.
2270 if (mLastWasImTarget) {
2271 InputMethodManager imm = InputMethodManager.peekInstance();
2272 if (imm != null && mView != null) {
2273 int seq = enqueuePendingEvent(event, sendDone);
2274 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2275 + seq + " event=" + event);
2276 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2277 mInputMethodCallback);
2278 return;
2279 }
2280 }
2281 deliverKeyEventToViewHierarchy(event, sendDone);
2282 }
2283
2284 void handleFinishedEvent(int seq, boolean handled) {
2285 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2286 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2287 + " handled=" + handled + " event=" + event);
2288 if (event != null) {
2289 final boolean sendDone = seq >= 0;
2290 if (!handled) {
2291 deliverKeyEventToViewHierarchy(event, sendDone);
2292 return;
2293 } else if (sendDone) {
2294 if (LOCAL_LOGV) Log.v(
2295 "ViewRoot", "Telling window manager key is finished");
2296 try {
2297 sWindowSession.finishKey(mWindow);
2298 } catch (RemoteException e) {
2299 }
2300 } else {
2301 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2302 + " handled=" + handled + " ev=" + event
2303 + ") neither delivering nor finishing key");
2304 }
2305 }
2306 }
Romain Guy8506ab42009-06-11 17:35:47 -07002307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2309 try {
2310 if (mView != null && mAdded) {
2311 final int action = event.getAction();
2312 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2313
2314 if (checkForLeavingTouchModeAndConsume(event)) {
2315 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002316 }
2317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 if (Config.LOGV) {
2319 captureKeyLog("captureDispatchKeyEvent", event);
2320 }
2321 boolean keyHandled = mView.dispatchKeyEvent(event);
2322
2323 if (!keyHandled && isDown) {
2324 int direction = 0;
2325 switch (event.getKeyCode()) {
2326 case KeyEvent.KEYCODE_DPAD_LEFT:
2327 direction = View.FOCUS_LEFT;
2328 break;
2329 case KeyEvent.KEYCODE_DPAD_RIGHT:
2330 direction = View.FOCUS_RIGHT;
2331 break;
2332 case KeyEvent.KEYCODE_DPAD_UP:
2333 direction = View.FOCUS_UP;
2334 break;
2335 case KeyEvent.KEYCODE_DPAD_DOWN:
2336 direction = View.FOCUS_DOWN;
2337 break;
2338 }
2339
2340 if (direction != 0) {
2341
2342 View focused = mView != null ? mView.findFocus() : null;
2343 if (focused != null) {
2344 View v = focused.focusSearch(direction);
2345 boolean focusPassed = false;
2346 if (v != null && v != focused) {
2347 // do the math the get the interesting rect
2348 // of previous focused into the coord system of
2349 // newly focused view
2350 focused.getFocusedRect(mTempRect);
2351 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2352 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2353 focusPassed = v.requestFocus(direction, mTempRect);
2354 }
2355
2356 if (!focusPassed) {
2357 mView.dispatchUnhandledMove(focused, direction);
2358 } else {
2359 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2360 }
2361 }
2362 }
2363 }
2364 }
2365
2366 } finally {
2367 if (sendDone) {
2368 if (LOCAL_LOGV) Log.v(
2369 "ViewRoot", "Telling window manager key is finished");
2370 try {
2371 sWindowSession.finishKey(mWindow);
2372 } catch (RemoteException e) {
2373 }
2374 }
2375 // Let the exception fall through -- the looper will catch
2376 // it and take care of the bad app for us.
2377 }
2378 }
2379
2380 private AudioManager getAudioManager() {
2381 if (mView == null) {
2382 throw new IllegalStateException("getAudioManager called when there is no mView");
2383 }
2384 if (mAudioManager == null) {
2385 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2386 }
2387 return mAudioManager;
2388 }
2389
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002390 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2391 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002392
2393 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002394 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002395 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002396 restore = true;
2397 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002398 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002399 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002400 if (params != null) {
2401 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002402 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002403 int relayoutResult = sWindowSession.relayout(
2404 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002405 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2406 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002407 viewVisibility, insetsPending, mWinFrame,
2408 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002409 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002410 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002411 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002412
2413 if (mTranslator != null) {
2414 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2415 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2416 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002417 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002418 return relayoutResult;
2419 }
Romain Guy8506ab42009-06-11 17:35:47 -07002420
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002421 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 * {@inheritDoc}
2423 */
2424 public void playSoundEffect(int effectId) {
2425 checkThread();
2426
2427 final AudioManager audioManager = getAudioManager();
2428
2429 switch (effectId) {
2430 case SoundEffectConstants.CLICK:
2431 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2432 return;
2433 case SoundEffectConstants.NAVIGATION_DOWN:
2434 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2435 return;
2436 case SoundEffectConstants.NAVIGATION_LEFT:
2437 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2438 return;
2439 case SoundEffectConstants.NAVIGATION_RIGHT:
2440 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2441 return;
2442 case SoundEffectConstants.NAVIGATION_UP:
2443 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2444 return;
2445 default:
2446 throw new IllegalArgumentException("unknown effect id " + effectId +
2447 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2448 }
2449 }
2450
2451 /**
2452 * {@inheritDoc}
2453 */
2454 public boolean performHapticFeedback(int effectId, boolean always) {
2455 try {
2456 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2457 } catch (RemoteException e) {
2458 return false;
2459 }
2460 }
2461
2462 /**
2463 * {@inheritDoc}
2464 */
2465 public View focusSearch(View focused, int direction) {
2466 checkThread();
2467 if (!(mView instanceof ViewGroup)) {
2468 return null;
2469 }
2470 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2471 }
2472
2473 public void debug() {
2474 mView.debug();
2475 }
2476
2477 public void die(boolean immediate) {
2478 checkThread();
2479 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2480 synchronized (this) {
2481 if (mAdded && !mFirst) {
2482 int viewVisibility = mView.getVisibility();
2483 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2484 if (mWindowAttributesChanged || viewVisibilityChanged) {
2485 // If layout params have been changed, first give them
2486 // to the window manager to make sure it has the correct
2487 // animation info.
2488 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002489 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2490 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 sWindowSession.finishDrawing(mWindow);
2492 }
2493 } catch (RemoteException e) {
2494 }
2495 }
2496
2497 mSurface = null;
2498 }
2499 if (mAdded) {
2500 mAdded = false;
2501 if (immediate) {
2502 dispatchDetachedFromWindow();
2503 } else if (mView != null) {
2504 sendEmptyMessage(DIE);
2505 }
2506 }
2507 }
2508 }
2509
2510 public void dispatchFinishedEvent(int seq, boolean handled) {
2511 Message msg = obtainMessage(FINISHED_EVENT);
2512 msg.arg1 = seq;
2513 msg.arg2 = handled ? 1 : 0;
2514 sendMessage(msg);
2515 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 public void dispatchResized(int w, int h, Rect coveredInsets,
2518 Rect visibleInsets, boolean reportDraw) {
2519 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2520 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2521 + " visibleInsets=" + visibleInsets.toShortString()
2522 + " reportDraw=" + reportDraw);
2523 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002524 if (mTranslator != null) {
2525 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2526 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2527 w *= mTranslator.applicationInvertedScale;
2528 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002529 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002530 msg.arg1 = w;
2531 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2533 sendMessage(msg);
2534 }
2535
2536 public void dispatchKey(KeyEvent event) {
2537 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2538 //noinspection ConstantConditions
2539 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2540 if (Config.LOGD) Log.d("keydisp",
2541 "===================================================");
2542 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2543 debug();
2544
2545 if (Config.LOGD) Log.d("keydisp",
2546 "===================================================");
2547 }
2548 }
2549
2550 Message msg = obtainMessage(DISPATCH_KEY);
2551 msg.obj = event;
2552
2553 if (LOCAL_LOGV) Log.v(
2554 "ViewRoot", "sending key " + event + " to " + mView);
2555
2556 sendMessageAtTime(msg, event.getEventTime());
2557 }
2558
2559 public void dispatchPointer(MotionEvent event, long eventTime) {
2560 Message msg = obtainMessage(DISPATCH_POINTER);
2561 msg.obj = event;
2562 sendMessageAtTime(msg, eventTime);
2563 }
2564
2565 public void dispatchTrackball(MotionEvent event, long eventTime) {
2566 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2567 msg.obj = event;
2568 sendMessageAtTime(msg, eventTime);
2569 }
2570
2571 public void dispatchAppVisibility(boolean visible) {
2572 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2573 msg.arg1 = visible ? 1 : 0;
2574 sendMessage(msg);
2575 }
2576
2577 public void dispatchGetNewSurface() {
2578 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2579 sendMessage(msg);
2580 }
2581
2582 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2583 Message msg = Message.obtain();
2584 msg.what = WINDOW_FOCUS_CHANGED;
2585 msg.arg1 = hasFocus ? 1 : 0;
2586 msg.arg2 = inTouchMode ? 1 : 0;
2587 sendMessage(msg);
2588 }
2589
svetoslavganov75986cf2009-05-14 22:28:01 -07002590 /**
2591 * The window is getting focus so if there is anything focused/selected
2592 * send an {@link AccessibilityEvent} to announce that.
2593 */
2594 private void sendAccessibilityEvents() {
2595 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2596 return;
2597 }
2598 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2599 View focusedView = mView.findFocus();
2600 if (focusedView != null && focusedView != mView) {
2601 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2602 }
2603 }
2604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 public boolean showContextMenuForChild(View originalView) {
2606 return false;
2607 }
2608
2609 public void createContextMenu(ContextMenu menu) {
2610 }
2611
2612 public void childDrawableStateChanged(View child) {
2613 }
2614
2615 protected Rect getWindowFrame() {
2616 return mWinFrame;
2617 }
2618
2619 void checkThread() {
2620 if (mThread != Thread.currentThread()) {
2621 throw new CalledFromWrongThreadException(
2622 "Only the original thread that created a view hierarchy can touch its views.");
2623 }
2624 }
2625
2626 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2627 // ViewRoot never intercepts touch event, so this can be a no-op
2628 }
2629
2630 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2631 boolean immediate) {
2632 return scrollToRectOrFocus(rectangle, immediate);
2633 }
Romain Guy8506ab42009-06-11 17:35:47 -07002634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 static class InputMethodCallback extends IInputMethodCallback.Stub {
2636 private WeakReference<ViewRoot> mViewRoot;
2637
2638 public InputMethodCallback(ViewRoot viewRoot) {
2639 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2640 }
Romain Guy8506ab42009-06-11 17:35:47 -07002641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 public void finishedEvent(int seq, boolean handled) {
2643 final ViewRoot viewRoot = mViewRoot.get();
2644 if (viewRoot != null) {
2645 viewRoot.dispatchFinishedEvent(seq, handled);
2646 }
2647 }
2648
2649 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2650 // Stub -- not for use in the client.
2651 }
2652 }
Romain Guy8506ab42009-06-11 17:35:47 -07002653
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002654 static class EventCompletion extends Handler {
2655 final IWindow mWindow;
2656 final KeyEvent mKeyEvent;
2657 final boolean mIsPointer;
2658 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002659
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002660 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2661 boolean isPointer, MotionEvent motion) {
2662 super(looper);
2663 mWindow = window;
2664 mKeyEvent = key;
2665 mIsPointer = isPointer;
2666 mMotionEvent = motion;
2667 sendEmptyMessage(0);
2668 }
Romain Guy8506ab42009-06-11 17:35:47 -07002669
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002670 @Override
2671 public void handleMessage(Message msg) {
2672 if (mKeyEvent != null) {
2673 try {
2674 sWindowSession.finishKey(mWindow);
2675 } catch (RemoteException e) {
2676 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002677 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002678 boolean didFinish;
2679 MotionEvent event = mMotionEvent;
2680 if (event == null) {
2681 try {
2682 event = sWindowSession.getPendingPointerMove(mWindow);
2683 } catch (RemoteException e) {
2684 }
2685 didFinish = true;
2686 } else {
2687 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2688 }
2689 if (!didFinish) {
2690 try {
2691 sWindowSession.finishKey(mWindow);
2692 } catch (RemoteException e) {
2693 }
2694 }
2695 } else {
2696 MotionEvent event = mMotionEvent;
2697 if (event == null) {
2698 try {
2699 event = sWindowSession.getPendingTrackballMove(mWindow);
2700 } catch (RemoteException e) {
2701 }
2702 } else {
2703 try {
2704 sWindowSession.finishKey(mWindow);
2705 } catch (RemoteException e) {
2706 }
2707 }
2708 }
2709 }
2710 }
Romain Guy8506ab42009-06-11 17:35:47 -07002711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002713 private final WeakReference<ViewRoot> mViewRoot;
2714 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002716 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002718 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 }
2720
2721 public void resized(int w, int h, Rect coveredInsets,
2722 Rect visibleInsets, boolean reportDraw) {
2723 final ViewRoot viewRoot = mViewRoot.get();
2724 if (viewRoot != null) {
2725 viewRoot.dispatchResized(w, h, coveredInsets,
2726 visibleInsets, reportDraw);
2727 }
2728 }
2729
2730 public void dispatchKey(KeyEvent event) {
2731 final ViewRoot viewRoot = mViewRoot.get();
2732 if (viewRoot != null) {
2733 viewRoot.dispatchKey(event);
2734 } else {
2735 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002736 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 }
2738 }
2739
2740 public void dispatchPointer(MotionEvent event, long eventTime) {
2741 final ViewRoot viewRoot = mViewRoot.get();
2742 if (viewRoot != null) {
2743 viewRoot.dispatchPointer(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002744 } else {
2745 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
2747 }
2748
2749 public void dispatchTrackball(MotionEvent event, long eventTime) {
2750 final ViewRoot viewRoot = mViewRoot.get();
2751 if (viewRoot != null) {
2752 viewRoot.dispatchTrackball(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002753 } else {
2754 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
2756 }
2757
2758 public void dispatchAppVisibility(boolean visible) {
2759 final ViewRoot viewRoot = mViewRoot.get();
2760 if (viewRoot != null) {
2761 viewRoot.dispatchAppVisibility(visible);
2762 }
2763 }
2764
2765 public void dispatchGetNewSurface() {
2766 final ViewRoot viewRoot = mViewRoot.get();
2767 if (viewRoot != null) {
2768 viewRoot.dispatchGetNewSurface();
2769 }
2770 }
2771
2772 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2773 final ViewRoot viewRoot = mViewRoot.get();
2774 if (viewRoot != null) {
2775 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2776 }
2777 }
2778
2779 private static int checkCallingPermission(String permission) {
2780 if (!Process.supportsProcesses()) {
2781 return PackageManager.PERMISSION_GRANTED;
2782 }
2783
2784 try {
2785 return ActivityManagerNative.getDefault().checkPermission(
2786 permission, Binder.getCallingPid(), Binder.getCallingUid());
2787 } catch (RemoteException e) {
2788 return PackageManager.PERMISSION_DENIED;
2789 }
2790 }
2791
2792 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2793 final ViewRoot viewRoot = mViewRoot.get();
2794 if (viewRoot != null) {
2795 final View view = viewRoot.mView;
2796 if (view != null) {
2797 if (checkCallingPermission(Manifest.permission.DUMP) !=
2798 PackageManager.PERMISSION_GRANTED) {
2799 throw new SecurityException("Insufficient permissions to invoke"
2800 + " executeCommand() from pid=" + Binder.getCallingPid()
2801 + ", uid=" + Binder.getCallingUid());
2802 }
2803
2804 OutputStream clientStream = null;
2805 try {
2806 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2807 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2808 } catch (IOException e) {
2809 e.printStackTrace();
2810 } finally {
2811 if (clientStream != null) {
2812 try {
2813 clientStream.close();
2814 } catch (IOException e) {
2815 e.printStackTrace();
2816 }
2817 }
2818 }
2819 }
2820 }
2821 }
2822 }
2823
2824 /**
2825 * Maintains state information for a single trackball axis, generating
2826 * discrete (DPAD) movements based on raw trackball motion.
2827 */
2828 static final class TrackballAxis {
2829 /**
2830 * The maximum amount of acceleration we will apply.
2831 */
2832 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 /**
2835 * The maximum amount of time (in milliseconds) between events in order
2836 * for us to consider the user to be doing fast trackball movements,
2837 * and thus apply an acceleration.
2838 */
2839 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 /**
2842 * Scaling factor to the time (in milliseconds) between events to how
2843 * much to multiple/divide the current acceleration. When movement
2844 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2845 * FAST_MOVE_TIME it divides it.
2846 */
2847 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 float position;
2850 float absPosition;
2851 float acceleration = 1;
2852 long lastMoveTime = 0;
2853 int step;
2854 int dir;
2855 int nonAccelMovement;
2856
2857 void reset(int _step) {
2858 position = 0;
2859 acceleration = 1;
2860 lastMoveTime = 0;
2861 step = _step;
2862 dir = 0;
2863 }
2864
2865 /**
2866 * Add trackball movement into the state. If the direction of movement
2867 * has been reversed, the state is reset before adding the
2868 * movement (so that you don't have to compensate for any previously
2869 * collected movement before see the result of the movement in the
2870 * new direction).
2871 *
2872 * @return Returns the absolute value of the amount of movement
2873 * collected so far.
2874 */
2875 float collect(float off, long time, String axis) {
2876 long normTime;
2877 if (off > 0) {
2878 normTime = (long)(off * FAST_MOVE_TIME);
2879 if (dir < 0) {
2880 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2881 position = 0;
2882 step = 0;
2883 acceleration = 1;
2884 lastMoveTime = 0;
2885 }
2886 dir = 1;
2887 } else if (off < 0) {
2888 normTime = (long)((-off) * FAST_MOVE_TIME);
2889 if (dir > 0) {
2890 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2891 position = 0;
2892 step = 0;
2893 acceleration = 1;
2894 lastMoveTime = 0;
2895 }
2896 dir = -1;
2897 } else {
2898 normTime = 0;
2899 }
Romain Guy8506ab42009-06-11 17:35:47 -07002900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 // The number of milliseconds between each movement that is
2902 // considered "normal" and will not result in any acceleration
2903 // or deceleration, scaled by the offset we have here.
2904 if (normTime > 0) {
2905 long delta = time - lastMoveTime;
2906 lastMoveTime = time;
2907 float acc = acceleration;
2908 if (delta < normTime) {
2909 // The user is scrolling rapidly, so increase acceleration.
2910 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2911 if (scale > 1) acc *= scale;
2912 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2913 + off + " normTime=" + normTime + " delta=" + delta
2914 + " scale=" + scale + " acc=" + acc);
2915 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2916 } else {
2917 // The user is scrolling slowly, so decrease acceleration.
2918 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
2919 if (scale > 1) acc /= scale;
2920 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
2921 + off + " normTime=" + normTime + " delta=" + delta
2922 + " scale=" + scale + " acc=" + acc);
2923 acceleration = acc > 1 ? acc : 1;
2924 }
2925 }
2926 position += off;
2927 return (absPosition = Math.abs(position));
2928 }
2929
2930 /**
2931 * Generate the number of discrete movement events appropriate for
2932 * the currently collected trackball movement.
2933 *
2934 * @param precision The minimum movement required to generate the
2935 * first discrete movement.
2936 *
2937 * @return Returns the number of discrete movements, either positive
2938 * or negative, or 0 if there is not enough trackball movement yet
2939 * for a discrete movement.
2940 */
2941 int generate(float precision) {
2942 int movement = 0;
2943 nonAccelMovement = 0;
2944 do {
2945 final int dir = position >= 0 ? 1 : -1;
2946 switch (step) {
2947 // If we are going to execute the first step, then we want
2948 // to do this as soon as possible instead of waiting for
2949 // a full movement, in order to make things look responsive.
2950 case 0:
2951 if (absPosition < precision) {
2952 return movement;
2953 }
2954 movement += dir;
2955 nonAccelMovement += dir;
2956 step = 1;
2957 break;
2958 // If we have generated the first movement, then we need
2959 // to wait for the second complete trackball motion before
2960 // generating the second discrete movement.
2961 case 1:
2962 if (absPosition < 2) {
2963 return movement;
2964 }
2965 movement += dir;
2966 nonAccelMovement += dir;
2967 position += dir > 0 ? -2 : 2;
2968 absPosition = Math.abs(position);
2969 step = 2;
2970 break;
2971 // After the first two, we generate discrete movements
2972 // consistently with the trackball, applying an acceleration
2973 // if the trackball is moving quickly. This is a simple
2974 // acceleration on top of what we already compute based
2975 // on how quickly the wheel is being turned, to apply
2976 // a longer increasing acceleration to continuous movement
2977 // in one direction.
2978 default:
2979 if (absPosition < 1) {
2980 return movement;
2981 }
2982 movement += dir;
2983 position += dir >= 0 ? -1 : 1;
2984 absPosition = Math.abs(position);
2985 float acc = acceleration;
2986 acc *= 1.1f;
2987 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
2988 break;
2989 }
2990 } while (true);
2991 }
2992 }
2993
2994 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
2995 public CalledFromWrongThreadException(String msg) {
2996 super(msg);
2997 }
2998 }
2999
3000 private SurfaceHolder mHolder = new SurfaceHolder() {
3001 // we only need a SurfaceHolder for opengl. it would be nice
3002 // to implement everything else though, especially the callback
3003 // support (opengl doesn't make use of it right now, but eventually
3004 // will).
3005 public Surface getSurface() {
3006 return mSurface;
3007 }
3008
3009 public boolean isCreating() {
3010 return false;
3011 }
3012
3013 public void addCallback(Callback callback) {
3014 }
3015
3016 public void removeCallback(Callback callback) {
3017 }
3018
3019 public void setFixedSize(int width, int height) {
3020 }
3021
3022 public void setSizeFromLayout() {
3023 }
3024
3025 public void setFormat(int format) {
3026 }
3027
3028 public void setType(int type) {
3029 }
3030
3031 public void setKeepScreenOn(boolean screenOn) {
3032 }
3033
3034 public Canvas lockCanvas() {
3035 return null;
3036 }
3037
3038 public Canvas lockCanvas(Rect dirty) {
3039 return null;
3040 }
3041
3042 public void unlockCanvasAndPost(Canvas canvas) {
3043 }
3044 public Rect getSurfaceFrame() {
3045 return null;
3046 }
3047 };
3048
3049 static RunQueue getRunQueue() {
3050 RunQueue rq = sRunQueues.get();
3051 if (rq != null) {
3052 return rq;
3053 }
3054 rq = new RunQueue();
3055 sRunQueues.set(rq);
3056 return rq;
3057 }
Romain Guy8506ab42009-06-11 17:35:47 -07003058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 /**
3060 * @hide
3061 */
3062 static final class RunQueue {
3063 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3064
3065 void post(Runnable action) {
3066 postDelayed(action, 0);
3067 }
3068
3069 void postDelayed(Runnable action, long delayMillis) {
3070 HandlerAction handlerAction = new HandlerAction();
3071 handlerAction.action = action;
3072 handlerAction.delay = delayMillis;
3073
3074 synchronized (mActions) {
3075 mActions.add(handlerAction);
3076 }
3077 }
3078
3079 void removeCallbacks(Runnable action) {
3080 final HandlerAction handlerAction = new HandlerAction();
3081 handlerAction.action = action;
3082
3083 synchronized (mActions) {
3084 final ArrayList<HandlerAction> actions = mActions;
3085
3086 while (actions.remove(handlerAction)) {
3087 // Keep going
3088 }
3089 }
3090 }
3091
3092 void executeActions(Handler handler) {
3093 synchronized (mActions) {
3094 final ArrayList<HandlerAction> actions = mActions;
3095 final int count = actions.size();
3096
3097 for (int i = 0; i < count; i++) {
3098 final HandlerAction handlerAction = actions.get(i);
3099 handler.postDelayed(handlerAction.action, handlerAction.delay);
3100 }
3101
3102 mActions.clear();
3103 }
3104 }
3105
3106 private static class HandlerAction {
3107 Runnable action;
3108 long delay;
3109
3110 @Override
3111 public boolean equals(Object o) {
3112 if (this == o) return true;
3113 if (o == null || getClass() != o.getClass()) return false;
3114
3115 HandlerAction that = (HandlerAction) o;
3116
3117 return !(action != null ? !action.equals(that.action) : that.action != null);
3118
3119 }
3120
3121 @Override
3122 public int hashCode() {
3123 int result = action != null ? action.hashCode() : 0;
3124 result = 31 * result + (int) (delay ^ (delay >>> 32));
3125 return result;
3126 }
3127 }
3128 }
3129
3130 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3131
3132 // inform skia to just abandon its texture cache IDs
3133 // doesn't call glDeleteTextures
3134 private static native void nativeAbandonGlCaches();
3135}