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