blob: eab3799a90595e28c180cd950b89f03dad9fdc65 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 if (newView) {
503 mSoftInputMode = attrs.softInputMode;
504 requestLayout();
505 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700506 // Don't lose the mode we last auto-computed.
507 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
508 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
509 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
510 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
511 | (oldSoftInputMode
512 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 mWindowAttributesChanged = true;
515 scheduleTraversals();
516 }
517 }
518
519 void handleAppVisibility(boolean visible) {
520 if (mAppVisible != visible) {
521 mAppVisible = visible;
522 scheduleTraversals();
523 }
524 }
525
526 void handleGetNewSurface() {
527 mNewSurfaceNeeded = true;
528 mFullRedrawNeeded = true;
529 scheduleTraversals();
530 }
531
532 /**
533 * {@inheritDoc}
534 */
535 public void requestLayout() {
536 checkThread();
537 mLayoutRequested = true;
538 scheduleTraversals();
539 }
540
541 /**
542 * {@inheritDoc}
543 */
544 public boolean isLayoutRequested() {
545 return mLayoutRequested;
546 }
547
548 public void invalidateChild(View child, Rect dirty) {
549 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700550 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
551 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700553 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700554 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700555 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700556 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700557 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700558 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700559 }
Romain Guy1e095972009-07-07 11:22:45 -0700560 if (mAttachInfo.mScalingRequired) {
561 dirty.inset(-1, -1);
562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 }
564 mDirty.union(dirty);
565 if (!mWillDrawSoon) {
566 scheduleTraversals();
567 }
568 }
569
570 public ViewParent getParent() {
571 return null;
572 }
573
574 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
575 invalidateChild(null, dirty);
576 return null;
577 }
578
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700579 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 if (child != mView) {
581 throw new RuntimeException("child is not mine, honest!");
582 }
583 // Note: don't apply scroll offset, because we want to know its
584 // visibility in the virtual canvas being given to the view hierarchy.
585 return r.intersect(0, 0, mWidth, mHeight);
586 }
587
588 public void bringChildToFront(View child) {
589 }
590
591 public void scheduleTraversals() {
592 if (!mTraversalScheduled) {
593 mTraversalScheduled = true;
594 sendEmptyMessage(DO_TRAVERSAL);
595 }
596 }
597
598 public void unscheduleTraversals() {
599 if (mTraversalScheduled) {
600 mTraversalScheduled = false;
601 removeMessages(DO_TRAVERSAL);
602 }
603 }
604
605 int getHostVisibility() {
606 return mAppVisible ? mView.getVisibility() : View.GONE;
607 }
Romain Guy8506ab42009-06-11 17:35:47 -0700608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 private void performTraversals() {
610 // cache mView since it is used so much below...
611 final View host = mView;
612
613 if (DBG) {
614 System.out.println("======================================");
615 System.out.println("performTraversals");
616 host.debug();
617 }
618
619 if (host == null || !mAdded)
620 return;
621
622 mTraversalScheduled = false;
623 mWillDrawSoon = true;
624 boolean windowResizesToFitContent = false;
625 boolean fullRedrawNeeded = mFullRedrawNeeded;
626 boolean newSurface = false;
627 WindowManager.LayoutParams lp = mWindowAttributes;
628
629 int desiredWindowWidth;
630 int desiredWindowHeight;
631 int childWidthMeasureSpec;
632 int childHeightMeasureSpec;
633
634 final View.AttachInfo attachInfo = mAttachInfo;
635
636 final int viewVisibility = getHostVisibility();
637 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
638 || mNewSurfaceNeeded;
639
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700640 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 WindowManager.LayoutParams params = null;
643 if (mWindowAttributesChanged) {
644 mWindowAttributesChanged = false;
645 params = lp;
646 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700647 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 if (mFirst) {
649 fullRedrawNeeded = true;
650 mLayoutRequested = true;
651
Romain Guy8506ab42009-06-11 17:35:47 -0700652 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700653 mView.getContext().getResources().getDisplayMetrics();
654 desiredWindowWidth = packageMetrics.widthPixels;
655 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656
657 // For the very first time, tell the view hierarchy that it
658 // is attached to the window. Note that at this point the surface
659 // object is not initialized to its backing store, but soon it
660 // will be (assuming the window is visible).
661 attachInfo.mSurface = mSurface;
662 attachInfo.mHasWindowFocus = false;
663 attachInfo.mWindowVisibility = viewVisibility;
664 attachInfo.mRecomputeGlobalAttributes = false;
665 attachInfo.mKeepScreenOn = false;
666 viewVisibilityChanged = false;
667 host.dispatchAttachedToWindow(attachInfo, 0);
668 getRunQueue().executeActions(attachInfo.mHandler);
669 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700672 desiredWindowWidth = frame.width();
673 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
675 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700676 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 fullRedrawNeeded = true;
678 mLayoutRequested = true;
679 windowResizesToFitContent = true;
680 }
681 }
682
683 if (viewVisibilityChanged) {
684 attachInfo.mWindowVisibility = viewVisibility;
685 host.dispatchWindowVisibilityChanged(viewVisibility);
686 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
687 if (mUseGL) {
688 destroyGL();
689 }
690 }
691 if (viewVisibility == View.GONE) {
692 // After making a window gone, we will count it as being
693 // shown for the first time the next time it gets focus.
694 mHasHadWindowFocus = false;
695 }
696 }
697
698 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 if (mLayoutRequested) {
701 if (mFirst) {
702 host.fitSystemWindows(mAttachInfo.mContentInsets);
703 // make sure touch mode code executes by setting cached value
704 // to opposite of the added touch mode.
705 mAttachInfo.mInTouchMode = !mAddedTouchMode;
706 ensureTouchModeLocally(mAddedTouchMode);
707 } else {
708 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
709 mAttachInfo.mContentInsets.set(mPendingContentInsets);
710 host.fitSystemWindows(mAttachInfo.mContentInsets);
711 insetsChanged = true;
712 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
713 + mAttachInfo.mContentInsets);
714 }
715 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
716 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
717 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
718 + mAttachInfo.mVisibleInsets);
719 }
720 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
721 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
722 windowResizesToFitContent = true;
723
Romain Guy8506ab42009-06-11 17:35:47 -0700724 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700725 mView.getContext().getResources().getDisplayMetrics();
726 desiredWindowWidth = packageMetrics.widthPixels;
727 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 }
729 }
730
731 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
732 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
733
734 // Ask host how big it wants to be
735 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
736 "Measuring " + host + " in display " + desiredWindowWidth
737 + "x" + desiredWindowHeight + "...");
738 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
739
740 if (DBG) {
741 System.out.println("======================================");
742 System.out.println("performTraversals -- after measure");
743 host.debug();
744 }
745 }
746
747 if (attachInfo.mRecomputeGlobalAttributes) {
748 //Log.i(TAG, "Computing screen on!");
749 attachInfo.mRecomputeGlobalAttributes = false;
750 boolean oldVal = attachInfo.mKeepScreenOn;
751 attachInfo.mKeepScreenOn = false;
752 host.dispatchCollectViewAttributes(0);
753 if (attachInfo.mKeepScreenOn != oldVal) {
754 params = lp;
755 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
756 }
757 }
758
759 if (mFirst || attachInfo.mViewVisibilityChanged) {
760 attachInfo.mViewVisibilityChanged = false;
761 int resizeMode = mSoftInputMode &
762 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
763 // If we are in auto resize mode, then we need to determine
764 // what mode to use now.
765 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
766 final int N = attachInfo.mScrollContainers.size();
767 for (int i=0; i<N; i++) {
768 if (attachInfo.mScrollContainers.get(i).isShown()) {
769 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
770 }
771 }
772 if (resizeMode == 0) {
773 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
774 }
775 if ((lp.softInputMode &
776 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
777 lp.softInputMode = (lp.softInputMode &
778 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
779 resizeMode;
780 params = lp;
781 }
782 }
783 }
Romain Guy8506ab42009-06-11 17:35:47 -0700784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
786 if (!PixelFormat.formatHasAlpha(params.format)) {
787 params.format = PixelFormat.TRANSLUCENT;
788 }
789 }
790
791 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
792 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
793
794 final boolean computesInternalInsets =
795 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
796 boolean insetsPending = false;
797 int relayoutResult = 0;
798 if (mFirst || windowShouldResize || insetsChanged
799 || viewVisibilityChanged || params != null) {
800
801 if (viewVisibility == View.VISIBLE) {
802 // If this window is giving internal insets to the window
803 // manager, and it is being added or changing its visibility,
804 // then we want to first give the window manager "fake"
805 // insets to cause it to effectively ignore the content of
806 // the window during layout. This avoids it briefly causing
807 // other windows to resize/move based on the raw frame of the
808 // window, waiting until we can finish laying out this window
809 // and get back to the window manager with the ultimately
810 // computed insets.
811 insetsPending = computesInternalInsets
812 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
815 if (params == null) {
816 params = mWindowAttributes;
817 }
818 mGlWanted = true;
819 }
820 }
821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 boolean initialized = false;
823 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700824 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 try {
826 boolean hadSurface = mSurface.isValid();
827 int fl = 0;
828 if (params != null) {
829 fl = params.flags;
830 if (attachInfo.mKeepScreenOn) {
831 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
832 }
833 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700834 if (DEBUG_LAYOUT) {
835 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
836 host.mMeasuredHeight + ", params=" + params);
837 }
838 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 if (params != null) {
841 params.flags = fl;
842 }
843
844 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
845 + " content=" + mPendingContentInsets.toShortString()
846 + " visible=" + mPendingVisibleInsets.toShortString()
847 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 contentInsetsChanged = !mPendingContentInsets.equals(
850 mAttachInfo.mContentInsets);
851 visibleInsetsChanged = !mPendingVisibleInsets.equals(
852 mAttachInfo.mVisibleInsets);
853 if (contentInsetsChanged) {
854 mAttachInfo.mContentInsets.set(mPendingContentInsets);
855 host.fitSystemWindows(mAttachInfo.mContentInsets);
856 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
857 + mAttachInfo.mContentInsets);
858 }
859 if (visibleInsetsChanged) {
860 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
861 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
862 + mAttachInfo.mVisibleInsets);
863 }
864
865 if (!hadSurface) {
866 if (mSurface.isValid()) {
867 // If we are creating a new surface, then we need to
868 // completely redraw it. Also, when we get to the
869 // point of drawing it we will hold off and schedule
870 // a new traversal instead. This is so we can tell the
871 // window manager about all of the windows being displayed
872 // before actually drawing them, so it can display then
873 // all at once.
874 newSurface = true;
875 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 if (mGlWanted && !mUseGL) {
878 initializeGL();
879 initialized = mGlCanvas != null;
880 }
881 }
882 } else if (!mSurface.isValid()) {
883 // If the surface has been removed, then reset the scroll
884 // positions.
885 mLastScrolledFocus = null;
886 mScrollY = mCurScrollY = 0;
887 if (mScroller != null) {
888 mScroller.abortAnimation();
889 }
890 }
891 } catch (RemoteException e) {
892 }
893 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700894 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895
896 attachInfo.mWindowLeft = frame.left;
897 attachInfo.mWindowTop = frame.top;
898
899 // !!FIXME!! This next section handles the case where we did not get the
900 // window size we asked for. We should avoid this by getting a maximum size from
901 // the window session beforehand.
902 mWidth = frame.width();
903 mHeight = frame.height();
904
905 if (initialized) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700906 mGlCanvas.setViewport((int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
908
909 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
910 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
911 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
912 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
913 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
914 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
915
916 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
917 + mWidth + " measuredWidth=" + host.mMeasuredWidth
918 + " mHeight=" + mHeight
919 + " measuredHeight" + host.mMeasuredHeight
920 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 // Ask host how big it wants to be
923 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
924
925 // Implementation of weights from WindowManager.LayoutParams
926 // We just grow the dimensions as needed and re-measure if
927 // needs be
928 int width = host.mMeasuredWidth;
929 int height = host.mMeasuredHeight;
930 boolean measureAgain = false;
931
932 if (lp.horizontalWeight > 0.0f) {
933 width += (int) ((mWidth - width) * lp.horizontalWeight);
934 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
935 MeasureSpec.EXACTLY);
936 measureAgain = true;
937 }
938 if (lp.verticalWeight > 0.0f) {
939 height += (int) ((mHeight - height) * lp.verticalWeight);
940 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
941 MeasureSpec.EXACTLY);
942 measureAgain = true;
943 }
944
945 if (measureAgain) {
946 if (DEBUG_LAYOUT) Log.v(TAG,
947 "And hey let's measure once more: width=" + width
948 + " height=" + height);
949 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
950 }
951
952 mLayoutRequested = true;
953 }
954 }
955
956 final boolean didLayout = mLayoutRequested;
957 boolean triggerGlobalLayoutListener = didLayout
958 || attachInfo.mRecomputeGlobalAttributes;
959 if (didLayout) {
960 mLayoutRequested = false;
961 mScrollMayChange = true;
962 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
963 "ViewRoot", "Laying out " + host + " to (" +
964 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700965 long startTime = 0L;
966 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 startTime = SystemClock.elapsedRealtime();
968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
970
Romain Guy13922e02009-05-12 17:56:14 -0700971 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
972 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
973 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
974 + "please refer to the logs with the tag "
975 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
976 }
977 }
978
979 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
981 }
982
983 // By this point all views have been sized and positionned
984 // We can compute the transparent area
985
986 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
987 // start out transparent
988 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
989 host.getLocationInWindow(mTmpLocation);
990 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
991 mTmpLocation[0] + host.mRight - host.mLeft,
992 mTmpLocation[1] + host.mBottom - host.mTop);
993
994 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700995 if (mTranslator != null) {
996 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
997 }
998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1000 mPreviousTransparentRegion.set(mTransparentRegion);
1001 // reconfigure window manager
1002 try {
1003 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1004 } catch (RemoteException e) {
1005 }
1006 }
1007 }
1008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 if (DBG) {
1010 System.out.println("======================================");
1011 System.out.println("performTraversals -- after setFrame");
1012 host.debug();
1013 }
1014 }
1015
1016 if (triggerGlobalLayoutListener) {
1017 attachInfo.mRecomputeGlobalAttributes = false;
1018 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1019 }
1020
1021 if (computesInternalInsets) {
1022 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1023 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1024 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1025 givenContent.left = givenContent.top = givenContent.right
1026 = givenContent.bottom = givenVisible.left = givenVisible.top
1027 = givenVisible.right = givenVisible.bottom = 0;
1028 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001029 Rect contentInsets = insets.contentInsets;
1030 Rect visibleInsets = insets.visibleInsets;
1031 if (mTranslator != null) {
1032 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1033 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1036 mLastGivenInsets.set(insets);
1037 try {
1038 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001039 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 } catch (RemoteException e) {
1041 }
1042 }
1043 }
Romain Guy8506ab42009-06-11 17:35:47 -07001044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 if (mFirst) {
1046 // handle first focus request
1047 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1048 + mView.hasFocus());
1049 if (mView != null) {
1050 if (!mView.hasFocus()) {
1051 mView.requestFocus(View.FOCUS_FORWARD);
1052 mFocusedView = mRealFocusedView = mView.findFocus();
1053 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1054 + mFocusedView);
1055 } else {
1056 mRealFocusedView = mView.findFocus();
1057 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1058 + mRealFocusedView);
1059 }
1060 }
1061 }
1062
1063 mFirst = false;
1064 mWillDrawSoon = false;
1065 mNewSurfaceNeeded = false;
1066 mViewVisibility = viewVisibility;
1067
1068 if (mAttachInfo.mHasWindowFocus) {
1069 final boolean imTarget = WindowManager.LayoutParams
1070 .mayUseInputMethod(mWindowAttributes.flags);
1071 if (imTarget != mLastWasImTarget) {
1072 mLastWasImTarget = imTarget;
1073 InputMethodManager imm = InputMethodManager.peekInstance();
1074 if (imm != null && imTarget) {
1075 imm.startGettingWindowFocus(mView);
1076 imm.onWindowFocus(mView, mView.findFocus(),
1077 mWindowAttributes.softInputMode,
1078 !mHasHadWindowFocus, mWindowAttributes.flags);
1079 }
1080 }
1081 }
Romain Guy8506ab42009-06-11 17:35:47 -07001082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1084
1085 if (!cancelDraw && !newSurface) {
1086 mFullRedrawNeeded = false;
1087 draw(fullRedrawNeeded);
1088
1089 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1090 || mReportNextDraw) {
1091 if (LOCAL_LOGV) {
1092 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1093 }
1094 mReportNextDraw = false;
1095 try {
1096 sWindowSession.finishDrawing(mWindow);
1097 } catch (RemoteException e) {
1098 }
1099 }
1100 } else {
1101 // We were supposed to report when we are done drawing. Since we canceled the
1102 // draw, remember it here.
1103 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1104 mReportNextDraw = true;
1105 }
1106 if (fullRedrawNeeded) {
1107 mFullRedrawNeeded = true;
1108 }
1109 // Try again
1110 scheduleTraversals();
1111 }
1112 }
1113
1114 public void requestTransparentRegion(View child) {
1115 // the test below should not fail unless someone is messing with us
1116 checkThread();
1117 if (mView == child) {
1118 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1119 // Need to make sure we re-evaluate the window attributes next
1120 // time around, to ensure the window has the correct format.
1121 mWindowAttributesChanged = true;
1122 }
1123 }
1124
1125 /**
1126 * Figures out the measure spec for the root view in a window based on it's
1127 * layout params.
1128 *
1129 * @param windowSize
1130 * The available width or height of the window
1131 *
1132 * @param rootDimension
1133 * The layout params for one dimension (width or height) of the
1134 * window.
1135 *
1136 * @return The measure spec to use to measure the root view.
1137 */
1138 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1139 int measureSpec;
1140 switch (rootDimension) {
1141
1142 case ViewGroup.LayoutParams.FILL_PARENT:
1143 // Window can't resize. Force root view to be windowSize.
1144 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1145 break;
1146 case ViewGroup.LayoutParams.WRAP_CONTENT:
1147 // Window can resize. Set max size for root view.
1148 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1149 break;
1150 default:
1151 // Window wants to be an exact size. Force root view to be that size.
1152 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1153 break;
1154 }
1155 return measureSpec;
1156 }
1157
1158 private void draw(boolean fullRedrawNeeded) {
1159 Surface surface = mSurface;
1160 if (surface == null || !surface.isValid()) {
1161 return;
1162 }
1163
1164 scrollToRectOrFocus(null, false);
1165
1166 if (mAttachInfo.mViewScrollChanged) {
1167 mAttachInfo.mViewScrollChanged = false;
1168 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1169 }
Romain Guy8506ab42009-06-11 17:35:47 -07001170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001172 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 if (scrolling) {
1174 yoff = mScroller.getCurrY();
1175 } else {
1176 yoff = mScrollY;
1177 }
1178 if (mCurScrollY != yoff) {
1179 mCurScrollY = yoff;
1180 fullRedrawNeeded = true;
1181 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001182 float appScale = mAttachInfo.mApplicationScale;
1183 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184
1185 Rect dirty = mDirty;
1186 if (mUseGL) {
1187 if (!dirty.isEmpty()) {
1188 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001189 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 mGL.glDisable(GL_SCISSOR_TEST);
1191 mGL.glClearColor(0, 0, 0, 0);
1192 mGL.glClear(GL_COLOR_BUFFER_BIT);
1193 mGL.glEnable(GL_SCISSOR_TEST);
1194
1195 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001196 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001198
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001199 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1200 try {
1201 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001202 if (mTranslator != null) {
1203 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001204 }
1205 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001206 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1207 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1208 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001209 } finally {
1210 canvas.restoreToCount(saveCount);
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212
Romain Guy5bcdff42009-05-14 21:27:18 -07001213 mAttachInfo.mIgnoreDirtyState = false;
1214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1216 checkEglErrors();
1217
Romain Guy13922e02009-05-12 17:56:14 -07001218 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 int now = (int)SystemClock.elapsedRealtime();
1220 if (sDrawTime != 0) {
1221 nativeShowFPS(canvas, now - sDrawTime);
1222 }
1223 sDrawTime = now;
1224 }
1225 }
1226 }
1227 if (scrolling) {
1228 mFullRedrawNeeded = true;
1229 scheduleTraversals();
1230 }
1231 return;
1232 }
1233
Romain Guy5bcdff42009-05-14 21:27:18 -07001234 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001235 mAttachInfo.mIgnoreDirtyState = true;
1236 dirty.union(0, 0, (int) (mWidth * appScale), (int) (mHeight * appScale));
Romain Guy5bcdff42009-05-14 21:27:18 -07001237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238
1239 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1240 Log.v("ViewRoot", "Draw " + mView + "/"
1241 + mWindowAttributes.getTitle()
1242 + ": dirty={" + dirty.left + "," + dirty.top
1243 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001244 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1245 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247
1248 Canvas canvas;
1249 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001250 int left = dirty.left;
1251 int top = dirty.top;
1252 int right = dirty.right;
1253 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001255
1256 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1257 bottom != dirty.bottom) {
1258 mAttachInfo.mIgnoreDirtyState = true;
1259 }
1260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 // TODO: Do this in native
1262 canvas.setDensityScale(mDensity);
1263 } catch (Surface.OutOfResourcesException e) {
1264 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1265 // TODO: we should ask the window manager to do something!
1266 // for now we just do nothing
1267 return;
1268 }
1269
1270 try {
Romain Guybb93d552009-03-24 21:04:15 -07001271 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001272 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273
1274 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1275 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1276 + canvas.getWidth() + ", h=" + canvas.getHeight());
1277 //canvas.drawARGB(255, 255, 0, 0);
1278 }
1279
Romain Guy13922e02009-05-12 17:56:14 -07001280 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 startTime = SystemClock.elapsedRealtime();
1282 }
1283
1284 // If this bitmap's format includes an alpha channel, we
1285 // need to clear it before drawing so that the child will
1286 // properly re-composite its drawing on a transparent
1287 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001288 // or
1289 // If we are applying an offset, we need to clear the area
1290 // where the offset doesn't appear to avoid having garbage
1291 // left in the blank areas.
1292 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1294 }
1295
1296 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001297 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001299 mView.mPrivateFlags |= View.DRAWN;
1300
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001301 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001302 Context cxt = mView.getContext();
1303 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001304 ", metrics=" + mView.getContext().getResources().getDisplayMetrics());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001305 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001306 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001307 try {
1308 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001309 if (mTranslator != null) {
1310 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001311 }
1312 mView.draw(canvas);
1313 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001314 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001315 canvas.restoreToCount(saveCount);
1316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317
Romain Guy5bcdff42009-05-14 21:27:18 -07001318 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1319 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1320 }
1321
Romain Guy13922e02009-05-12 17:56:14 -07001322 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 int now = (int)SystemClock.elapsedRealtime();
1324 if (sDrawTime != 0) {
1325 nativeShowFPS(canvas, now - sDrawTime);
1326 }
1327 sDrawTime = now;
1328 }
1329
Romain Guy13922e02009-05-12 17:56:14 -07001330 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1332 }
1333 }
Romain Guy8506ab42009-06-11 17:35:47 -07001334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 } finally {
1336 surface.unlockCanvasAndPost(canvas);
1337 }
1338
1339 if (LOCAL_LOGV) {
1340 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1341 }
Romain Guy8506ab42009-06-11 17:35:47 -07001342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 if (scrolling) {
1344 mFullRedrawNeeded = true;
1345 scheduleTraversals();
1346 }
1347 }
1348
1349 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1350 final View.AttachInfo attachInfo = mAttachInfo;
1351 final Rect ci = attachInfo.mContentInsets;
1352 final Rect vi = attachInfo.mVisibleInsets;
1353 int scrollY = 0;
1354 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 if (vi.left > ci.left || vi.top > ci.top
1357 || vi.right > ci.right || vi.bottom > ci.bottom) {
1358 // We'll assume that we aren't going to change the scroll
1359 // offset, since we want to avoid that unless it is actually
1360 // going to make the focus visible... otherwise we scroll
1361 // all over the place.
1362 scrollY = mScrollY;
1363 // We can be called for two different situations: during a draw,
1364 // to update the scroll position if the focus has changed (in which
1365 // case 'rectangle' is null), or in response to a
1366 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1367 // is non-null and we just want to scroll to whatever that
1368 // rectangle is).
1369 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001370
1371 // When in touch mode, focus points to the previously focused view,
1372 // which may have been removed from the view hierarchy. The following
1373 // line checks whether the view is still in the hierarchy
1374 if (focus == null || focus.getParent() == null) {
1375 mRealFocusedView = null;
1376 return false;
1377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 if (focus != mLastScrolledFocus) {
1380 // If the focus has changed, then ignore any requests to scroll
1381 // to a rectangle; first we want to make sure the entire focus
1382 // view is visible.
1383 rectangle = null;
1384 }
1385 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1386 + " rectangle=" + rectangle + " ci=" + ci
1387 + " vi=" + vi);
1388 if (focus == mLastScrolledFocus && !mScrollMayChange
1389 && rectangle == null) {
1390 // Optimization: if the focus hasn't changed since last
1391 // time, and no layout has happened, then just leave things
1392 // as they are.
1393 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1394 + mScrollY + " vi=" + vi.toShortString());
1395 } else if (focus != null) {
1396 // We need to determine if the currently focused view is
1397 // within the visible part of the window and, if not, apply
1398 // a pan so it can be seen.
1399 mLastScrolledFocus = focus;
1400 mScrollMayChange = false;
1401 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1402 // Try to find the rectangle from the focus view.
1403 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1404 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1405 + mView.getWidth() + " h=" + mView.getHeight()
1406 + " ci=" + ci.toShortString()
1407 + " vi=" + vi.toShortString());
1408 if (rectangle == null) {
1409 focus.getFocusedRect(mTempRect);
1410 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1411 + ": focusRect=" + mTempRect.toShortString());
1412 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1413 focus, mTempRect);
1414 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1415 "Focus in window: focusRect="
1416 + mTempRect.toShortString()
1417 + " visRect=" + mVisRect.toShortString());
1418 } else {
1419 mTempRect.set(rectangle);
1420 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1421 "Request scroll to rect: "
1422 + mTempRect.toShortString()
1423 + " visRect=" + mVisRect.toShortString());
1424 }
1425 if (mTempRect.intersect(mVisRect)) {
1426 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1427 "Focus window visible rect: "
1428 + mTempRect.toShortString());
1429 if (mTempRect.height() >
1430 (mView.getHeight()-vi.top-vi.bottom)) {
1431 // If the focus simply is not going to fit, then
1432 // best is probably just to leave things as-is.
1433 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1434 "Too tall; leaving scrollY=" + scrollY);
1435 } else if ((mTempRect.top-scrollY) < vi.top) {
1436 scrollY -= vi.top - (mTempRect.top-scrollY);
1437 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1438 "Top covered; scrollY=" + scrollY);
1439 } else if ((mTempRect.bottom-scrollY)
1440 > (mView.getHeight()-vi.bottom)) {
1441 scrollY += (mTempRect.bottom-scrollY)
1442 - (mView.getHeight()-vi.bottom);
1443 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1444 "Bottom covered; scrollY=" + scrollY);
1445 }
1446 handled = true;
1447 }
1448 }
1449 }
1450 }
Romain Guy8506ab42009-06-11 17:35:47 -07001451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 if (scrollY != mScrollY) {
1453 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1454 + mScrollY + " , new=" + scrollY);
1455 if (!immediate) {
1456 if (mScroller == null) {
1457 mScroller = new Scroller(mView.getContext());
1458 }
1459 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1460 } else if (mScroller != null) {
1461 mScroller.abortAnimation();
1462 }
1463 mScrollY = scrollY;
1464 }
Romain Guy8506ab42009-06-11 17:35:47 -07001465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 return handled;
1467 }
Romain Guy8506ab42009-06-11 17:35:47 -07001468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 public void requestChildFocus(View child, View focused) {
1470 checkThread();
1471 if (mFocusedView != focused) {
1472 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1473 scheduleTraversals();
1474 }
1475 mFocusedView = mRealFocusedView = focused;
1476 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1477 + mFocusedView);
1478 }
1479
1480 public void clearChildFocus(View child) {
1481 checkThread();
1482
1483 View oldFocus = mFocusedView;
1484
1485 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1486 mFocusedView = mRealFocusedView = null;
1487 if (mView != null && !mView.hasFocus()) {
1488 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1489 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1490 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1491 }
1492 } else if (oldFocus != null) {
1493 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1494 }
1495 }
1496
1497
1498 public void focusableViewAvailable(View v) {
1499 checkThread();
1500
1501 if (mView != null && !mView.hasFocus()) {
1502 v.requestFocus();
1503 } else {
1504 // the one case where will transfer focus away from the current one
1505 // is if the current view is a view group that prefers to give focus
1506 // to its children first AND the view is a descendant of it.
1507 mFocusedView = mView.findFocus();
1508 boolean descendantsHaveDibsOnFocus =
1509 (mFocusedView instanceof ViewGroup) &&
1510 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1511 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1512 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1513 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1514 v.requestFocus();
1515 }
1516 }
1517 }
1518
1519 public void recomputeViewAttributes(View child) {
1520 checkThread();
1521 if (mView == child) {
1522 mAttachInfo.mRecomputeGlobalAttributes = true;
1523 if (!mWillDrawSoon) {
1524 scheduleTraversals();
1525 }
1526 }
1527 }
1528
1529 void dispatchDetachedFromWindow() {
1530 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1531
1532 if (mView != null) {
1533 mView.dispatchDetachedFromWindow();
1534 }
1535
1536 mView = null;
1537 mAttachInfo.mRootView = null;
1538
1539 if (mUseGL) {
1540 destroyGL();
1541 }
1542
1543 try {
1544 sWindowSession.remove(mWindow);
1545 } catch (RemoteException e) {
1546 }
1547 }
Romain Guy8506ab42009-06-11 17:35:47 -07001548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 /**
1550 * Return true if child is an ancestor of parent, (or equal to the parent).
1551 */
1552 private static boolean isViewDescendantOf(View child, View parent) {
1553 if (child == parent) {
1554 return true;
1555 }
1556
1557 final ViewParent theParent = child.getParent();
1558 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1559 }
1560
1561
1562 public final static int DO_TRAVERSAL = 1000;
1563 public final static int DIE = 1001;
1564 public final static int RESIZED = 1002;
1565 public final static int RESIZED_REPORT = 1003;
1566 public final static int WINDOW_FOCUS_CHANGED = 1004;
1567 public final static int DISPATCH_KEY = 1005;
1568 public final static int DISPATCH_POINTER = 1006;
1569 public final static int DISPATCH_TRACKBALL = 1007;
1570 public final static int DISPATCH_APP_VISIBILITY = 1008;
1571 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1572 public final static int FINISHED_EVENT = 1010;
1573 public final static int DISPATCH_KEY_FROM_IME = 1011;
1574 public final static int FINISH_INPUT_CONNECTION = 1012;
1575 public final static int CHECK_FOCUS = 1013;
1576
1577 @Override
1578 public void handleMessage(Message msg) {
1579 switch (msg.what) {
1580 case View.AttachInfo.INVALIDATE_MSG:
1581 ((View) msg.obj).invalidate();
1582 break;
1583 case View.AttachInfo.INVALIDATE_RECT_MSG:
1584 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1585 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1586 info.release();
1587 break;
1588 case DO_TRAVERSAL:
1589 if (mProfile) {
1590 Debug.startMethodTracing("ViewRoot");
1591 }
1592
1593 performTraversals();
1594
1595 if (mProfile) {
1596 Debug.stopMethodTracing();
1597 mProfile = false;
1598 }
1599 break;
1600 case FINISHED_EVENT:
1601 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1602 break;
1603 case DISPATCH_KEY:
1604 if (LOCAL_LOGV) Log.v(
1605 "ViewRoot", "Dispatching key "
1606 + msg.obj + " to " + mView);
1607 deliverKeyEvent((KeyEvent)msg.obj, true);
1608 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001609 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 MotionEvent event = (MotionEvent)msg.obj;
1611
1612 boolean didFinish;
1613 if (event == null) {
1614 try {
1615 event = sWindowSession.getPendingPointerMove(mWindow);
1616 } catch (RemoteException e) {
1617 }
1618 didFinish = true;
1619 } else {
1620 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
1621 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001622 if (event != null && mTranslator != null) {
1623 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 try {
1626 boolean handled;
1627 if (mView != null && mAdded && event != null) {
1628
1629 // enter touch mode on the down
1630 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1631 if (isDown) {
1632 ensureTouchMode(true);
1633 }
1634 if(Config.LOGV) {
1635 captureMotionLog("captureDispatchPointer", event);
1636 }
1637 event.offsetLocation(0, mCurScrollY);
1638 handled = mView.dispatchTouchEvent(event);
1639 if (!handled && isDown) {
1640 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1641
1642 final int edgeFlags = event.getEdgeFlags();
1643 int direction = View.FOCUS_UP;
1644 int x = (int)event.getX();
1645 int y = (int)event.getY();
1646 final int[] deltas = new int[2];
1647
1648 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1649 direction = View.FOCUS_DOWN;
1650 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1651 deltas[0] = edgeSlop;
1652 x += edgeSlop;
1653 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1654 deltas[0] = -edgeSlop;
1655 x -= edgeSlop;
1656 }
1657 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1658 direction = View.FOCUS_UP;
1659 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1660 deltas[0] = edgeSlop;
1661 x += edgeSlop;
1662 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1663 deltas[0] = -edgeSlop;
1664 x -= edgeSlop;
1665 }
1666 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1667 direction = View.FOCUS_RIGHT;
1668 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1669 direction = View.FOCUS_LEFT;
1670 }
1671
1672 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1673 View nearest = FocusFinder.getInstance().findNearestTouchable(
1674 ((ViewGroup) mView), x, y, direction, deltas);
1675 if (nearest != null) {
1676 event.offsetLocation(deltas[0], deltas[1]);
1677 event.setEdgeFlags(0);
1678 mView.dispatchTouchEvent(event);
1679 }
1680 }
1681 }
1682 }
1683 } finally {
1684 if (!didFinish) {
1685 try {
1686 sWindowSession.finishKey(mWindow);
1687 } catch (RemoteException e) {
1688 }
1689 }
1690 if (event != null) {
1691 event.recycle();
1692 }
1693 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1694 // Let the exception fall through -- the looper will catch
1695 // it and take care of the bad app for us.
1696 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001697 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 case DISPATCH_TRACKBALL:
1699 deliverTrackballEvent((MotionEvent)msg.obj);
1700 break;
1701 case DISPATCH_APP_VISIBILITY:
1702 handleAppVisibility(msg.arg1 != 0);
1703 break;
1704 case DISPATCH_GET_NEW_SURFACE:
1705 handleGetNewSurface();
1706 break;
1707 case RESIZED:
1708 Rect coveredInsets = ((Rect[])msg.obj)[0];
1709 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1712 && mPendingContentInsets.equals(coveredInsets)
1713 && mPendingVisibleInsets.equals(visibleInsets)) {
1714 break;
1715 }
1716 // fall through...
1717 case RESIZED_REPORT:
1718 if (mAdded) {
1719 mWinFrame.left = 0;
1720 mWinFrame.right = msg.arg1;
1721 mWinFrame.top = 0;
1722 mWinFrame.bottom = msg.arg2;
1723 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1724 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1725 if (msg.what == RESIZED_REPORT) {
1726 mReportNextDraw = true;
1727 }
1728 requestLayout();
1729 }
1730 break;
1731 case WINDOW_FOCUS_CHANGED: {
1732 if (mAdded) {
1733 boolean hasWindowFocus = msg.arg1 != 0;
1734 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1735 if (hasWindowFocus) {
1736 boolean inTouchMode = msg.arg2 != 0;
1737 ensureTouchModeLocally(inTouchMode);
1738
1739 if (mGlWanted) {
1740 checkEglErrors();
1741 // we lost the gl context, so recreate it.
1742 if (mGlWanted && !mUseGL) {
1743 initializeGL();
1744 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001745 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001746 mGlCanvas.setViewport(
1747 (int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
1749 }
1750 }
1751 }
Romain Guy8506ab42009-06-11 17:35:47 -07001752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 mLastWasImTarget = WindowManager.LayoutParams
1754 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 InputMethodManager imm = InputMethodManager.peekInstance();
1757 if (mView != null) {
1758 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1759 imm.startGettingWindowFocus(mView);
1760 }
1761 mView.dispatchWindowFocusChanged(hasWindowFocus);
1762 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 // Note: must be done after the focus change callbacks,
1765 // so all of the view state is set up correctly.
1766 if (hasWindowFocus) {
1767 if (imm != null && mLastWasImTarget) {
1768 imm.onWindowFocus(mView, mView.findFocus(),
1769 mWindowAttributes.softInputMode,
1770 !mHasHadWindowFocus, mWindowAttributes.flags);
1771 }
1772 // Clear the forward bit. We can just do this directly, since
1773 // the window manager doesn't care about it.
1774 mWindowAttributes.softInputMode &=
1775 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1776 ((WindowManager.LayoutParams)mView.getLayoutParams())
1777 .softInputMode &=
1778 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1779 mHasHadWindowFocus = true;
1780 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001781
1782 if (hasWindowFocus && mView != null) {
1783 sendAccessibilityEvents();
1784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 }
1786 } break;
1787 case DIE:
1788 dispatchDetachedFromWindow();
1789 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001790 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 if (LOCAL_LOGV) Log.v(
1792 "ViewRoot", "Dispatching key "
1793 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001794 KeyEvent event = (KeyEvent)msg.obj;
1795 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1796 // The IME is trying to say this event is from the
1797 // system! Bad bad bad!
1798 event = KeyEvent.changeFlags(event,
1799 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001802 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 case FINISH_INPUT_CONNECTION: {
1804 InputMethodManager imm = InputMethodManager.peekInstance();
1805 if (imm != null) {
1806 imm.reportFinishInputConnection((InputConnection)msg.obj);
1807 }
1808 } break;
1809 case CHECK_FOCUS: {
1810 InputMethodManager imm = InputMethodManager.peekInstance();
1811 if (imm != null) {
1812 imm.checkFocus();
1813 }
1814 } break;
1815 }
1816 }
1817
1818 /**
1819 * Something in the current window tells us we need to change the touch mode. For
1820 * example, we are not in touch mode, and the user touches the screen.
1821 *
1822 * If the touch mode has changed, tell the window manager, and handle it locally.
1823 *
1824 * @param inTouchMode Whether we want to be in touch mode.
1825 * @return True if the touch mode changed and focus changed was changed as a result
1826 */
1827 boolean ensureTouchMode(boolean inTouchMode) {
1828 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1829 + "touch mode is " + mAttachInfo.mInTouchMode);
1830 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1831
1832 // tell the window manager
1833 try {
1834 sWindowSession.setInTouchMode(inTouchMode);
1835 } catch (RemoteException e) {
1836 throw new RuntimeException(e);
1837 }
1838
1839 // handle the change
1840 return ensureTouchModeLocally(inTouchMode);
1841 }
1842
1843 /**
1844 * Ensure that the touch mode for this window is set, and if it is changing,
1845 * take the appropriate action.
1846 * @param inTouchMode Whether we want to be in touch mode.
1847 * @return True if the touch mode changed and focus changed was changed as a result
1848 */
1849 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1850 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1851 + "touch mode is " + mAttachInfo.mInTouchMode);
1852
1853 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1854
1855 mAttachInfo.mInTouchMode = inTouchMode;
1856 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1857
1858 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1859 }
1860
1861 private boolean enterTouchMode() {
1862 if (mView != null) {
1863 if (mView.hasFocus()) {
1864 // note: not relying on mFocusedView here because this could
1865 // be when the window is first being added, and mFocused isn't
1866 // set yet.
1867 final View focused = mView.findFocus();
1868 if (focused != null && !focused.isFocusableInTouchMode()) {
1869
1870 final ViewGroup ancestorToTakeFocus =
1871 findAncestorToTakeFocusInTouchMode(focused);
1872 if (ancestorToTakeFocus != null) {
1873 // there is an ancestor that wants focus after its descendants that
1874 // is focusable in touch mode.. give it focus
1875 return ancestorToTakeFocus.requestFocus();
1876 } else {
1877 // nothing appropriate to have focus in touch mode, clear it out
1878 mView.unFocus();
1879 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1880 mFocusedView = null;
1881 return true;
1882 }
1883 }
1884 }
1885 }
1886 return false;
1887 }
1888
1889
1890 /**
1891 * Find an ancestor of focused that wants focus after its descendants and is
1892 * focusable in touch mode.
1893 * @param focused The currently focused view.
1894 * @return An appropriate view, or null if no such view exists.
1895 */
1896 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1897 ViewParent parent = focused.getParent();
1898 while (parent instanceof ViewGroup) {
1899 final ViewGroup vgParent = (ViewGroup) parent;
1900 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1901 && vgParent.isFocusableInTouchMode()) {
1902 return vgParent;
1903 }
1904 if (vgParent.isRootNamespace()) {
1905 return null;
1906 } else {
1907 parent = vgParent.getParent();
1908 }
1909 }
1910 return null;
1911 }
1912
1913 private boolean leaveTouchMode() {
1914 if (mView != null) {
1915 if (mView.hasFocus()) {
1916 // i learned the hard way to not trust mFocusedView :)
1917 mFocusedView = mView.findFocus();
1918 if (!(mFocusedView instanceof ViewGroup)) {
1919 // some view has focus, let it keep it
1920 return false;
1921 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1922 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1923 // some view group has focus, and doesn't prefer its children
1924 // over itself for focus, so let them keep it.
1925 return false;
1926 }
1927 }
1928
1929 // find the best view to give focus to in this brave new non-touch-mode
1930 // world
1931 final View focused = focusSearch(null, View.FOCUS_DOWN);
1932 if (focused != null) {
1933 return focused.requestFocus(View.FOCUS_DOWN);
1934 }
1935 }
1936 return false;
1937 }
1938
1939
1940 private void deliverTrackballEvent(MotionEvent event) {
1941 boolean didFinish;
1942 if (event == null) {
1943 try {
1944 event = sWindowSession.getPendingTrackballMove(mWindow);
1945 } catch (RemoteException e) {
1946 }
1947 didFinish = true;
1948 } else {
1949 didFinish = false;
1950 }
1951
1952 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
1953
1954 boolean handled = false;
1955 try {
1956 if (event == null) {
1957 handled = true;
1958 } else if (mView != null && mAdded) {
1959 handled = mView.dispatchTrackballEvent(event);
1960 if (!handled) {
1961 // we could do something here, like changing the focus
1962 // or something?
1963 }
1964 }
1965 } finally {
1966 if (handled) {
1967 if (!didFinish) {
1968 try {
1969 sWindowSession.finishKey(mWindow);
1970 } catch (RemoteException e) {
1971 }
1972 }
1973 if (event != null) {
1974 event.recycle();
1975 }
1976 // If we reach this, we delivered a trackball event to mView and
1977 // mView consumed it. Because we will not translate the trackball
1978 // event into a key event, touch mode will not exit, so we exit
1979 // touch mode here.
1980 ensureTouchMode(false);
1981 //noinspection ReturnInsideFinallyBlock
1982 return;
1983 }
1984 // Let the exception fall through -- the looper will catch
1985 // it and take care of the bad app for us.
1986 }
1987
1988 final TrackballAxis x = mTrackballAxisX;
1989 final TrackballAxis y = mTrackballAxisY;
1990
1991 long curTime = SystemClock.uptimeMillis();
1992 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
1993 // It has been too long since the last movement,
1994 // so restart at the beginning.
1995 x.reset(0);
1996 y.reset(0);
1997 mLastTrackballTime = curTime;
1998 }
1999
2000 try {
2001 final int action = event.getAction();
2002 final int metastate = event.getMetaState();
2003 switch (action) {
2004 case MotionEvent.ACTION_DOWN:
2005 x.reset(2);
2006 y.reset(2);
2007 deliverKeyEvent(new KeyEvent(curTime, curTime,
2008 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2009 0, metastate), false);
2010 break;
2011 case MotionEvent.ACTION_UP:
2012 x.reset(2);
2013 y.reset(2);
2014 deliverKeyEvent(new KeyEvent(curTime, curTime,
2015 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2016 0, metastate), false);
2017 break;
2018 }
2019
2020 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2021 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2022 + " move=" + event.getX()
2023 + " / Y=" + y.position + " step="
2024 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2025 + " move=" + event.getY());
2026 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2027 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2028
2029 // Generate DPAD events based on the trackball movement.
2030 // We pick the axis that has moved the most as the direction of
2031 // the DPAD. When we generate DPAD events for one axis, then the
2032 // other axis is reset -- we don't want to perform DPAD jumps due
2033 // to slight movements in the trackball when making major movements
2034 // along the other axis.
2035 int keycode = 0;
2036 int movement = 0;
2037 float accel = 1;
2038 if (xOff > yOff) {
2039 movement = x.generate((2/event.getXPrecision()));
2040 if (movement != 0) {
2041 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2042 : KeyEvent.KEYCODE_DPAD_LEFT;
2043 accel = x.acceleration;
2044 y.reset(2);
2045 }
2046 } else if (yOff > 0) {
2047 movement = y.generate((2/event.getYPrecision()));
2048 if (movement != 0) {
2049 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2050 : KeyEvent.KEYCODE_DPAD_UP;
2051 accel = y.acceleration;
2052 x.reset(2);
2053 }
2054 }
2055
2056 if (keycode != 0) {
2057 if (movement < 0) movement = -movement;
2058 int accelMovement = (int)(movement * accel);
2059 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2060 + " accelMovement=" + accelMovement
2061 + " accel=" + accel);
2062 if (accelMovement > movement) {
2063 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2064 + keycode);
2065 movement--;
2066 deliverKeyEvent(new KeyEvent(curTime, curTime,
2067 KeyEvent.ACTION_MULTIPLE, keycode,
2068 accelMovement-movement, metastate), false);
2069 }
2070 while (movement > 0) {
2071 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2072 + keycode);
2073 movement--;
2074 curTime = SystemClock.uptimeMillis();
2075 deliverKeyEvent(new KeyEvent(curTime, curTime,
2076 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2077 deliverKeyEvent(new KeyEvent(curTime, curTime,
2078 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2079 }
2080 mLastTrackballTime = curTime;
2081 }
2082 } finally {
2083 if (!didFinish) {
2084 try {
2085 sWindowSession.finishKey(mWindow);
2086 } catch (RemoteException e) {
2087 }
2088 if (event != null) {
2089 event.recycle();
2090 }
2091 }
2092 // Let the exception fall through -- the looper will catch
2093 // it and take care of the bad app for us.
2094 }
2095 }
2096
2097 /**
2098 * @param keyCode The key code
2099 * @return True if the key is directional.
2100 */
2101 static boolean isDirectional(int keyCode) {
2102 switch (keyCode) {
2103 case KeyEvent.KEYCODE_DPAD_LEFT:
2104 case KeyEvent.KEYCODE_DPAD_RIGHT:
2105 case KeyEvent.KEYCODE_DPAD_UP:
2106 case KeyEvent.KEYCODE_DPAD_DOWN:
2107 return true;
2108 }
2109 return false;
2110 }
2111
2112 /**
2113 * Returns true if this key is a keyboard key.
2114 * @param keyEvent The key event.
2115 * @return whether this key is a keyboard key.
2116 */
2117 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2118 final int convertedKey = keyEvent.getUnicodeChar();
2119 return convertedKey > 0;
2120 }
2121
2122
2123
2124 /**
2125 * See if the key event means we should leave touch mode (and leave touch
2126 * mode if so).
2127 * @param event The key event.
2128 * @return Whether this key event should be consumed (meaning the act of
2129 * leaving touch mode alone is considered the event).
2130 */
2131 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2132 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2133 return false;
2134 }
2135 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2136 return false;
2137 }
2138
2139 // only relevant if we are in touch mode
2140 if (!mAttachInfo.mInTouchMode) {
2141 return false;
2142 }
2143
2144 // if something like an edit text has focus and the user is typing,
2145 // leave touch mode
2146 //
2147 // note: the condition of not being a keyboard key is kind of a hacky
2148 // approximation of whether we think the focused view will want the
2149 // key; if we knew for sure whether the focused view would consume
2150 // the event, that would be better.
2151 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2152 mFocusedView = mView.findFocus();
2153 if ((mFocusedView instanceof ViewGroup)
2154 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2155 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2156 // something has focus, but is holding it weakly as a container
2157 return false;
2158 }
2159 if (ensureTouchMode(false)) {
2160 throw new IllegalStateException("should not have changed focus "
2161 + "when leaving touch mode while a view has focus.");
2162 }
2163 return false;
2164 }
2165
2166 if (isDirectional(event.getKeyCode())) {
2167 // no view has focus, so we leave touch mode (and find something
2168 // to give focus to). the event is consumed if we were able to
2169 // find something to give focus to.
2170 return ensureTouchMode(false);
2171 }
2172 return false;
2173 }
2174
2175 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002176 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 */
2178 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002179 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 if (ev == null ||
2181 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2182 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
Romain Guy8506ab42009-06-11 17:35:47 -07002184
2185 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 sb.append(ev.getDownTime()).append(',');
2187 sb.append(ev.getEventTime()).append(',');
2188 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002189 sb.append(ev.getX()).append(',');
2190 sb.append(ev.getY()).append(',');
2191 sb.append(ev.getPressure()).append(',');
2192 sb.append(ev.getSize()).append(',');
2193 sb.append(ev.getMetaState()).append(',');
2194 sb.append(ev.getXPrecision()).append(',');
2195 sb.append(ev.getYPrecision()).append(',');
2196 sb.append(ev.getDeviceId()).append(',');
2197 sb.append(ev.getEdgeFlags());
2198 Log.d(TAG, sb.toString());
2199 }
2200 /**
2201 * log motion events
2202 */
2203 private static void captureKeyLog(String subTag, KeyEvent ev) {
2204 //check dynamic switch
2205 if (ev == null ||
2206 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2207 return;
2208 }
2209 StringBuilder sb = new StringBuilder(subTag + ": ");
2210 sb.append(ev.getDownTime()).append(',');
2211 sb.append(ev.getEventTime()).append(',');
2212 sb.append(ev.getAction()).append(',');
2213 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 sb.append(ev.getRepeatCount()).append(',');
2215 sb.append(ev.getMetaState()).append(',');
2216 sb.append(ev.getDeviceId()).append(',');
2217 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002218 Log.d(TAG, sb.toString());
2219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220
2221 int enqueuePendingEvent(Object event, boolean sendDone) {
2222 int seq = mPendingEventSeq+1;
2223 if (seq < 0) seq = 0;
2224 mPendingEventSeq = seq;
2225 mPendingEvents.put(seq, event);
2226 return sendDone ? seq : -seq;
2227 }
2228
2229 Object retrievePendingEvent(int seq) {
2230 if (seq < 0) seq = -seq;
2231 Object event = mPendingEvents.get(seq);
2232 if (event != null) {
2233 mPendingEvents.remove(seq);
2234 }
2235 return event;
2236 }
Romain Guy8506ab42009-06-11 17:35:47 -07002237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2239 // If mView is null, we just consume the key event because it doesn't
2240 // make sense to do anything else with it.
2241 boolean handled = mView != null
2242 ? mView.dispatchKeyEventPreIme(event) : true;
2243 if (handled) {
2244 if (sendDone) {
2245 if (LOCAL_LOGV) Log.v(
2246 "ViewRoot", "Telling window manager key is finished");
2247 try {
2248 sWindowSession.finishKey(mWindow);
2249 } catch (RemoteException e) {
2250 }
2251 }
2252 return;
2253 }
2254 // If it is possible for this window to interact with the input
2255 // method window, then we want to first dispatch our key events
2256 // to the input method.
2257 if (mLastWasImTarget) {
2258 InputMethodManager imm = InputMethodManager.peekInstance();
2259 if (imm != null && mView != null) {
2260 int seq = enqueuePendingEvent(event, sendDone);
2261 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2262 + seq + " event=" + event);
2263 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2264 mInputMethodCallback);
2265 return;
2266 }
2267 }
2268 deliverKeyEventToViewHierarchy(event, sendDone);
2269 }
2270
2271 void handleFinishedEvent(int seq, boolean handled) {
2272 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2273 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2274 + " handled=" + handled + " event=" + event);
2275 if (event != null) {
2276 final boolean sendDone = seq >= 0;
2277 if (!handled) {
2278 deliverKeyEventToViewHierarchy(event, sendDone);
2279 return;
2280 } else if (sendDone) {
2281 if (LOCAL_LOGV) Log.v(
2282 "ViewRoot", "Telling window manager key is finished");
2283 try {
2284 sWindowSession.finishKey(mWindow);
2285 } catch (RemoteException e) {
2286 }
2287 } else {
2288 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2289 + " handled=" + handled + " ev=" + event
2290 + ") neither delivering nor finishing key");
2291 }
2292 }
2293 }
Romain Guy8506ab42009-06-11 17:35:47 -07002294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2296 try {
2297 if (mView != null && mAdded) {
2298 final int action = event.getAction();
2299 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2300
2301 if (checkForLeavingTouchModeAndConsume(event)) {
2302 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002303 }
2304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 if (Config.LOGV) {
2306 captureKeyLog("captureDispatchKeyEvent", event);
2307 }
2308 boolean keyHandled = mView.dispatchKeyEvent(event);
2309
2310 if (!keyHandled && isDown) {
2311 int direction = 0;
2312 switch (event.getKeyCode()) {
2313 case KeyEvent.KEYCODE_DPAD_LEFT:
2314 direction = View.FOCUS_LEFT;
2315 break;
2316 case KeyEvent.KEYCODE_DPAD_RIGHT:
2317 direction = View.FOCUS_RIGHT;
2318 break;
2319 case KeyEvent.KEYCODE_DPAD_UP:
2320 direction = View.FOCUS_UP;
2321 break;
2322 case KeyEvent.KEYCODE_DPAD_DOWN:
2323 direction = View.FOCUS_DOWN;
2324 break;
2325 }
2326
2327 if (direction != 0) {
2328
2329 View focused = mView != null ? mView.findFocus() : null;
2330 if (focused != null) {
2331 View v = focused.focusSearch(direction);
2332 boolean focusPassed = false;
2333 if (v != null && v != focused) {
2334 // do the math the get the interesting rect
2335 // of previous focused into the coord system of
2336 // newly focused view
2337 focused.getFocusedRect(mTempRect);
2338 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2339 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2340 focusPassed = v.requestFocus(direction, mTempRect);
2341 }
2342
2343 if (!focusPassed) {
2344 mView.dispatchUnhandledMove(focused, direction);
2345 } else {
2346 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2347 }
2348 }
2349 }
2350 }
2351 }
2352
2353 } finally {
2354 if (sendDone) {
2355 if (LOCAL_LOGV) Log.v(
2356 "ViewRoot", "Telling window manager key is finished");
2357 try {
2358 sWindowSession.finishKey(mWindow);
2359 } catch (RemoteException e) {
2360 }
2361 }
2362 // Let the exception fall through -- the looper will catch
2363 // it and take care of the bad app for us.
2364 }
2365 }
2366
2367 private AudioManager getAudioManager() {
2368 if (mView == null) {
2369 throw new IllegalStateException("getAudioManager called when there is no mView");
2370 }
2371 if (mAudioManager == null) {
2372 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2373 }
2374 return mAudioManager;
2375 }
2376
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002377 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2378 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002379
2380 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002381 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002382 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002383 restore = true;
2384 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002385 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002386 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002387 if (params != null) {
2388 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002389 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002390 int relayoutResult = sWindowSession.relayout(
2391 mWindow, params,
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002392 (int) (mView.mMeasuredWidth * appScale),
2393 (int) (mView.mMeasuredHeight * appScale),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002394 viewVisibility, insetsPending, mWinFrame,
2395 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002396 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002397 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002398 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002399
2400 if (mTranslator != null) {
2401 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2402 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2403 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002404 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002405 return relayoutResult;
2406 }
Romain Guy8506ab42009-06-11 17:35:47 -07002407
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 * {@inheritDoc}
2410 */
2411 public void playSoundEffect(int effectId) {
2412 checkThread();
2413
2414 final AudioManager audioManager = getAudioManager();
2415
2416 switch (effectId) {
2417 case SoundEffectConstants.CLICK:
2418 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2419 return;
2420 case SoundEffectConstants.NAVIGATION_DOWN:
2421 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2422 return;
2423 case SoundEffectConstants.NAVIGATION_LEFT:
2424 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2425 return;
2426 case SoundEffectConstants.NAVIGATION_RIGHT:
2427 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2428 return;
2429 case SoundEffectConstants.NAVIGATION_UP:
2430 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2431 return;
2432 default:
2433 throw new IllegalArgumentException("unknown effect id " + effectId +
2434 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2435 }
2436 }
2437
2438 /**
2439 * {@inheritDoc}
2440 */
2441 public boolean performHapticFeedback(int effectId, boolean always) {
2442 try {
2443 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2444 } catch (RemoteException e) {
2445 return false;
2446 }
2447 }
2448
2449 /**
2450 * {@inheritDoc}
2451 */
2452 public View focusSearch(View focused, int direction) {
2453 checkThread();
2454 if (!(mView instanceof ViewGroup)) {
2455 return null;
2456 }
2457 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2458 }
2459
2460 public void debug() {
2461 mView.debug();
2462 }
2463
2464 public void die(boolean immediate) {
2465 checkThread();
2466 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2467 synchronized (this) {
2468 if (mAdded && !mFirst) {
2469 int viewVisibility = mView.getVisibility();
2470 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2471 if (mWindowAttributesChanged || viewVisibilityChanged) {
2472 // If layout params have been changed, first give them
2473 // to the window manager to make sure it has the correct
2474 // animation info.
2475 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002476 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2477 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 sWindowSession.finishDrawing(mWindow);
2479 }
2480 } catch (RemoteException e) {
2481 }
2482 }
2483
2484 mSurface = null;
2485 }
2486 if (mAdded) {
2487 mAdded = false;
2488 if (immediate) {
2489 dispatchDetachedFromWindow();
2490 } else if (mView != null) {
2491 sendEmptyMessage(DIE);
2492 }
2493 }
2494 }
2495 }
2496
2497 public void dispatchFinishedEvent(int seq, boolean handled) {
2498 Message msg = obtainMessage(FINISHED_EVENT);
2499 msg.arg1 = seq;
2500 msg.arg2 = handled ? 1 : 0;
2501 sendMessage(msg);
2502 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 public void dispatchResized(int w, int h, Rect coveredInsets,
2505 Rect visibleInsets, boolean reportDraw) {
2506 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2507 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2508 + " visibleInsets=" + visibleInsets.toShortString()
2509 + " reportDraw=" + reportDraw);
2510 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002511 if (mTranslator != null) {
2512 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2513 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2514 w *= mTranslator.applicationInvertedScale;
2515 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002516 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002517 msg.arg1 = w;
2518 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2520 sendMessage(msg);
2521 }
2522
2523 public void dispatchKey(KeyEvent event) {
2524 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2525 //noinspection ConstantConditions
2526 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2527 if (Config.LOGD) Log.d("keydisp",
2528 "===================================================");
2529 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2530 debug();
2531
2532 if (Config.LOGD) Log.d("keydisp",
2533 "===================================================");
2534 }
2535 }
2536
2537 Message msg = obtainMessage(DISPATCH_KEY);
2538 msg.obj = event;
2539
2540 if (LOCAL_LOGV) Log.v(
2541 "ViewRoot", "sending key " + event + " to " + mView);
2542
2543 sendMessageAtTime(msg, event.getEventTime());
2544 }
2545
2546 public void dispatchPointer(MotionEvent event, long eventTime) {
2547 Message msg = obtainMessage(DISPATCH_POINTER);
2548 msg.obj = event;
2549 sendMessageAtTime(msg, eventTime);
2550 }
2551
2552 public void dispatchTrackball(MotionEvent event, long eventTime) {
2553 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2554 msg.obj = event;
2555 sendMessageAtTime(msg, eventTime);
2556 }
2557
2558 public void dispatchAppVisibility(boolean visible) {
2559 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2560 msg.arg1 = visible ? 1 : 0;
2561 sendMessage(msg);
2562 }
2563
2564 public void dispatchGetNewSurface() {
2565 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2566 sendMessage(msg);
2567 }
2568
2569 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2570 Message msg = Message.obtain();
2571 msg.what = WINDOW_FOCUS_CHANGED;
2572 msg.arg1 = hasFocus ? 1 : 0;
2573 msg.arg2 = inTouchMode ? 1 : 0;
2574 sendMessage(msg);
2575 }
2576
svetoslavganov75986cf2009-05-14 22:28:01 -07002577 /**
2578 * The window is getting focus so if there is anything focused/selected
2579 * send an {@link AccessibilityEvent} to announce that.
2580 */
2581 private void sendAccessibilityEvents() {
2582 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2583 return;
2584 }
2585 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2586 View focusedView = mView.findFocus();
2587 if (focusedView != null && focusedView != mView) {
2588 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2589 }
2590 }
2591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 public boolean showContextMenuForChild(View originalView) {
2593 return false;
2594 }
2595
2596 public void createContextMenu(ContextMenu menu) {
2597 }
2598
2599 public void childDrawableStateChanged(View child) {
2600 }
2601
2602 protected Rect getWindowFrame() {
2603 return mWinFrame;
2604 }
2605
2606 void checkThread() {
2607 if (mThread != Thread.currentThread()) {
2608 throw new CalledFromWrongThreadException(
2609 "Only the original thread that created a view hierarchy can touch its views.");
2610 }
2611 }
2612
2613 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2614 // ViewRoot never intercepts touch event, so this can be a no-op
2615 }
2616
2617 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2618 boolean immediate) {
2619 return scrollToRectOrFocus(rectangle, immediate);
2620 }
Romain Guy8506ab42009-06-11 17:35:47 -07002621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 static class InputMethodCallback extends IInputMethodCallback.Stub {
2623 private WeakReference<ViewRoot> mViewRoot;
2624
2625 public InputMethodCallback(ViewRoot viewRoot) {
2626 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2627 }
Romain Guy8506ab42009-06-11 17:35:47 -07002628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 public void finishedEvent(int seq, boolean handled) {
2630 final ViewRoot viewRoot = mViewRoot.get();
2631 if (viewRoot != null) {
2632 viewRoot.dispatchFinishedEvent(seq, handled);
2633 }
2634 }
2635
2636 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2637 // Stub -- not for use in the client.
2638 }
2639 }
Romain Guy8506ab42009-06-11 17:35:47 -07002640
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002641 static class EventCompletion extends Handler {
2642 final IWindow mWindow;
2643 final KeyEvent mKeyEvent;
2644 final boolean mIsPointer;
2645 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002646
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002647 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2648 boolean isPointer, MotionEvent motion) {
2649 super(looper);
2650 mWindow = window;
2651 mKeyEvent = key;
2652 mIsPointer = isPointer;
2653 mMotionEvent = motion;
2654 sendEmptyMessage(0);
2655 }
Romain Guy8506ab42009-06-11 17:35:47 -07002656
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002657 @Override
2658 public void handleMessage(Message msg) {
2659 if (mKeyEvent != null) {
2660 try {
2661 sWindowSession.finishKey(mWindow);
2662 } catch (RemoteException e) {
2663 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002664 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002665 boolean didFinish;
2666 MotionEvent event = mMotionEvent;
2667 if (event == null) {
2668 try {
2669 event = sWindowSession.getPendingPointerMove(mWindow);
2670 } catch (RemoteException e) {
2671 }
2672 didFinish = true;
2673 } else {
2674 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2675 }
2676 if (!didFinish) {
2677 try {
2678 sWindowSession.finishKey(mWindow);
2679 } catch (RemoteException e) {
2680 }
2681 }
2682 } else {
2683 MotionEvent event = mMotionEvent;
2684 if (event == null) {
2685 try {
2686 event = sWindowSession.getPendingTrackballMove(mWindow);
2687 } catch (RemoteException e) {
2688 }
2689 } else {
2690 try {
2691 sWindowSession.finishKey(mWindow);
2692 } catch (RemoteException e) {
2693 }
2694 }
2695 }
2696 }
2697 }
Romain Guy8506ab42009-06-11 17:35:47 -07002698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002700 private final WeakReference<ViewRoot> mViewRoot;
2701 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002703 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002705 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
2707
2708 public void resized(int w, int h, Rect coveredInsets,
2709 Rect visibleInsets, boolean reportDraw) {
2710 final ViewRoot viewRoot = mViewRoot.get();
2711 if (viewRoot != null) {
2712 viewRoot.dispatchResized(w, h, coveredInsets,
2713 visibleInsets, reportDraw);
2714 }
2715 }
2716
2717 public void dispatchKey(KeyEvent event) {
2718 final ViewRoot viewRoot = mViewRoot.get();
2719 if (viewRoot != null) {
2720 viewRoot.dispatchKey(event);
2721 } else {
2722 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002723 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725 }
2726
2727 public void dispatchPointer(MotionEvent event, long eventTime) {
2728 final ViewRoot viewRoot = mViewRoot.get();
2729 if (viewRoot != null) {
2730 viewRoot.dispatchPointer(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002731 } else {
2732 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 }
2734 }
2735
2736 public void dispatchTrackball(MotionEvent event, long eventTime) {
2737 final ViewRoot viewRoot = mViewRoot.get();
2738 if (viewRoot != null) {
2739 viewRoot.dispatchTrackball(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002740 } else {
2741 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 }
2743 }
2744
2745 public void dispatchAppVisibility(boolean visible) {
2746 final ViewRoot viewRoot = mViewRoot.get();
2747 if (viewRoot != null) {
2748 viewRoot.dispatchAppVisibility(visible);
2749 }
2750 }
2751
2752 public void dispatchGetNewSurface() {
2753 final ViewRoot viewRoot = mViewRoot.get();
2754 if (viewRoot != null) {
2755 viewRoot.dispatchGetNewSurface();
2756 }
2757 }
2758
2759 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2760 final ViewRoot viewRoot = mViewRoot.get();
2761 if (viewRoot != null) {
2762 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2763 }
2764 }
2765
2766 private static int checkCallingPermission(String permission) {
2767 if (!Process.supportsProcesses()) {
2768 return PackageManager.PERMISSION_GRANTED;
2769 }
2770
2771 try {
2772 return ActivityManagerNative.getDefault().checkPermission(
2773 permission, Binder.getCallingPid(), Binder.getCallingUid());
2774 } catch (RemoteException e) {
2775 return PackageManager.PERMISSION_DENIED;
2776 }
2777 }
2778
2779 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2780 final ViewRoot viewRoot = mViewRoot.get();
2781 if (viewRoot != null) {
2782 final View view = viewRoot.mView;
2783 if (view != null) {
2784 if (checkCallingPermission(Manifest.permission.DUMP) !=
2785 PackageManager.PERMISSION_GRANTED) {
2786 throw new SecurityException("Insufficient permissions to invoke"
2787 + " executeCommand() from pid=" + Binder.getCallingPid()
2788 + ", uid=" + Binder.getCallingUid());
2789 }
2790
2791 OutputStream clientStream = null;
2792 try {
2793 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2794 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2795 } catch (IOException e) {
2796 e.printStackTrace();
2797 } finally {
2798 if (clientStream != null) {
2799 try {
2800 clientStream.close();
2801 } catch (IOException e) {
2802 e.printStackTrace();
2803 }
2804 }
2805 }
2806 }
2807 }
2808 }
2809 }
2810
2811 /**
2812 * Maintains state information for a single trackball axis, generating
2813 * discrete (DPAD) movements based on raw trackball motion.
2814 */
2815 static final class TrackballAxis {
2816 /**
2817 * The maximum amount of acceleration we will apply.
2818 */
2819 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 /**
2822 * The maximum amount of time (in milliseconds) between events in order
2823 * for us to consider the user to be doing fast trackball movements,
2824 * and thus apply an acceleration.
2825 */
2826 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 /**
2829 * Scaling factor to the time (in milliseconds) between events to how
2830 * much to multiple/divide the current acceleration. When movement
2831 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2832 * FAST_MOVE_TIME it divides it.
2833 */
2834 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 float position;
2837 float absPosition;
2838 float acceleration = 1;
2839 long lastMoveTime = 0;
2840 int step;
2841 int dir;
2842 int nonAccelMovement;
2843
2844 void reset(int _step) {
2845 position = 0;
2846 acceleration = 1;
2847 lastMoveTime = 0;
2848 step = _step;
2849 dir = 0;
2850 }
2851
2852 /**
2853 * Add trackball movement into the state. If the direction of movement
2854 * has been reversed, the state is reset before adding the
2855 * movement (so that you don't have to compensate for any previously
2856 * collected movement before see the result of the movement in the
2857 * new direction).
2858 *
2859 * @return Returns the absolute value of the amount of movement
2860 * collected so far.
2861 */
2862 float collect(float off, long time, String axis) {
2863 long normTime;
2864 if (off > 0) {
2865 normTime = (long)(off * FAST_MOVE_TIME);
2866 if (dir < 0) {
2867 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2868 position = 0;
2869 step = 0;
2870 acceleration = 1;
2871 lastMoveTime = 0;
2872 }
2873 dir = 1;
2874 } else if (off < 0) {
2875 normTime = (long)((-off) * FAST_MOVE_TIME);
2876 if (dir > 0) {
2877 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2878 position = 0;
2879 step = 0;
2880 acceleration = 1;
2881 lastMoveTime = 0;
2882 }
2883 dir = -1;
2884 } else {
2885 normTime = 0;
2886 }
Romain Guy8506ab42009-06-11 17:35:47 -07002887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 // The number of milliseconds between each movement that is
2889 // considered "normal" and will not result in any acceleration
2890 // or deceleration, scaled by the offset we have here.
2891 if (normTime > 0) {
2892 long delta = time - lastMoveTime;
2893 lastMoveTime = time;
2894 float acc = acceleration;
2895 if (delta < normTime) {
2896 // The user is scrolling rapidly, so increase acceleration.
2897 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2898 if (scale > 1) acc *= scale;
2899 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2900 + off + " normTime=" + normTime + " delta=" + delta
2901 + " scale=" + scale + " acc=" + acc);
2902 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2903 } else {
2904 // The user is scrolling slowly, so decrease acceleration.
2905 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
2906 if (scale > 1) acc /= scale;
2907 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
2908 + off + " normTime=" + normTime + " delta=" + delta
2909 + " scale=" + scale + " acc=" + acc);
2910 acceleration = acc > 1 ? acc : 1;
2911 }
2912 }
2913 position += off;
2914 return (absPosition = Math.abs(position));
2915 }
2916
2917 /**
2918 * Generate the number of discrete movement events appropriate for
2919 * the currently collected trackball movement.
2920 *
2921 * @param precision The minimum movement required to generate the
2922 * first discrete movement.
2923 *
2924 * @return Returns the number of discrete movements, either positive
2925 * or negative, or 0 if there is not enough trackball movement yet
2926 * for a discrete movement.
2927 */
2928 int generate(float precision) {
2929 int movement = 0;
2930 nonAccelMovement = 0;
2931 do {
2932 final int dir = position >= 0 ? 1 : -1;
2933 switch (step) {
2934 // If we are going to execute the first step, then we want
2935 // to do this as soon as possible instead of waiting for
2936 // a full movement, in order to make things look responsive.
2937 case 0:
2938 if (absPosition < precision) {
2939 return movement;
2940 }
2941 movement += dir;
2942 nonAccelMovement += dir;
2943 step = 1;
2944 break;
2945 // If we have generated the first movement, then we need
2946 // to wait for the second complete trackball motion before
2947 // generating the second discrete movement.
2948 case 1:
2949 if (absPosition < 2) {
2950 return movement;
2951 }
2952 movement += dir;
2953 nonAccelMovement += dir;
2954 position += dir > 0 ? -2 : 2;
2955 absPosition = Math.abs(position);
2956 step = 2;
2957 break;
2958 // After the first two, we generate discrete movements
2959 // consistently with the trackball, applying an acceleration
2960 // if the trackball is moving quickly. This is a simple
2961 // acceleration on top of what we already compute based
2962 // on how quickly the wheel is being turned, to apply
2963 // a longer increasing acceleration to continuous movement
2964 // in one direction.
2965 default:
2966 if (absPosition < 1) {
2967 return movement;
2968 }
2969 movement += dir;
2970 position += dir >= 0 ? -1 : 1;
2971 absPosition = Math.abs(position);
2972 float acc = acceleration;
2973 acc *= 1.1f;
2974 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
2975 break;
2976 }
2977 } while (true);
2978 }
2979 }
2980
2981 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
2982 public CalledFromWrongThreadException(String msg) {
2983 super(msg);
2984 }
2985 }
2986
2987 private SurfaceHolder mHolder = new SurfaceHolder() {
2988 // we only need a SurfaceHolder for opengl. it would be nice
2989 // to implement everything else though, especially the callback
2990 // support (opengl doesn't make use of it right now, but eventually
2991 // will).
2992 public Surface getSurface() {
2993 return mSurface;
2994 }
2995
2996 public boolean isCreating() {
2997 return false;
2998 }
2999
3000 public void addCallback(Callback callback) {
3001 }
3002
3003 public void removeCallback(Callback callback) {
3004 }
3005
3006 public void setFixedSize(int width, int height) {
3007 }
3008
3009 public void setSizeFromLayout() {
3010 }
3011
3012 public void setFormat(int format) {
3013 }
3014
3015 public void setType(int type) {
3016 }
3017
3018 public void setKeepScreenOn(boolean screenOn) {
3019 }
3020
3021 public Canvas lockCanvas() {
3022 return null;
3023 }
3024
3025 public Canvas lockCanvas(Rect dirty) {
3026 return null;
3027 }
3028
3029 public void unlockCanvasAndPost(Canvas canvas) {
3030 }
3031 public Rect getSurfaceFrame() {
3032 return null;
3033 }
3034 };
3035
3036 static RunQueue getRunQueue() {
3037 RunQueue rq = sRunQueues.get();
3038 if (rq != null) {
3039 return rq;
3040 }
3041 rq = new RunQueue();
3042 sRunQueues.set(rq);
3043 return rq;
3044 }
Romain Guy8506ab42009-06-11 17:35:47 -07003045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 /**
3047 * @hide
3048 */
3049 static final class RunQueue {
3050 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3051
3052 void post(Runnable action) {
3053 postDelayed(action, 0);
3054 }
3055
3056 void postDelayed(Runnable action, long delayMillis) {
3057 HandlerAction handlerAction = new HandlerAction();
3058 handlerAction.action = action;
3059 handlerAction.delay = delayMillis;
3060
3061 synchronized (mActions) {
3062 mActions.add(handlerAction);
3063 }
3064 }
3065
3066 void removeCallbacks(Runnable action) {
3067 final HandlerAction handlerAction = new HandlerAction();
3068 handlerAction.action = action;
3069
3070 synchronized (mActions) {
3071 final ArrayList<HandlerAction> actions = mActions;
3072
3073 while (actions.remove(handlerAction)) {
3074 // Keep going
3075 }
3076 }
3077 }
3078
3079 void executeActions(Handler handler) {
3080 synchronized (mActions) {
3081 final ArrayList<HandlerAction> actions = mActions;
3082 final int count = actions.size();
3083
3084 for (int i = 0; i < count; i++) {
3085 final HandlerAction handlerAction = actions.get(i);
3086 handler.postDelayed(handlerAction.action, handlerAction.delay);
3087 }
3088
3089 mActions.clear();
3090 }
3091 }
3092
3093 private static class HandlerAction {
3094 Runnable action;
3095 long delay;
3096
3097 @Override
3098 public boolean equals(Object o) {
3099 if (this == o) return true;
3100 if (o == null || getClass() != o.getClass()) return false;
3101
3102 HandlerAction that = (HandlerAction) o;
3103
3104 return !(action != null ? !action.equals(that.action) : that.action != null);
3105
3106 }
3107
3108 @Override
3109 public int hashCode() {
3110 int result = action != null ? action.hashCode() : 0;
3111 result = 31 * result + (int) (delay ^ (delay >>> 32));
3112 return result;
3113 }
3114 }
3115 }
3116
3117 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3118
3119 // inform skia to just abandon its texture cache IDs
3120 // doesn't call glDeleteTextures
3121 private static native void nativeAbandonGlCaches();
3122}