blob: 65457c5e9de8df9c1c1232986ab12c6995b95cd4 [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 Oshima64f59342009-06-21 00:03:11 -0700388
389 CompatibilityInfo compatibilityInfo =
390 mView.getContext().getResources().getCompatibilityInfo();
391 mTranslator = compatibilityInfo.getTranslator(attrs);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700392 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700393 if (attrs != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700394 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700395 attrs.backup();
396 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700397 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700398 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 mSoftInputMode = attrs.softInputMode;
401 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 mAttachInfo.mRootView = view;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700403 mAttachInfo.mScalingRequired =
404 mTranslator == null ? false : mTranslator.scalingRequired;
405 mAttachInfo.mApplicationScale =
406 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 if (panelParentView != null) {
408 mAttachInfo.mPanelParentWindowToken
409 = panelParentView.getApplicationWindowToken();
410 }
411 mAdded = true;
412 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 // Schedule the first layout -before- adding to the window
415 // manager, to make sure we do the relayout before receiving
416 // any other events from the system.
417 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700419 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 getHostVisibility(), mAttachInfo.mContentInsets);
421 } catch (RemoteException e) {
422 mAdded = false;
423 mView = null;
424 mAttachInfo.mRootView = null;
425 unscheduleTraversals();
426 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700427 } finally {
428 if (restore) {
429 attrs.restore();
430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700432
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700433 if (mTranslator != null) {
434 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 mPendingContentInsets.set(mAttachInfo.mContentInsets);
437 mPendingVisibleInsets.set(0, 0, 0, 0);
438 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
439 if (res < WindowManagerImpl.ADD_OKAY) {
440 mView = null;
441 mAttachInfo.mRootView = null;
442 mAdded = false;
443 unscheduleTraversals();
444 switch (res) {
445 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
446 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
447 throw new WindowManagerImpl.BadTokenException(
448 "Unable to add window -- token " + attrs.token
449 + " is not valid; is your activity running?");
450 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
451 throw new WindowManagerImpl.BadTokenException(
452 "Unable to add window -- token " + attrs.token
453 + " is not for an application");
454 case WindowManagerImpl.ADD_APP_EXITING:
455 throw new WindowManagerImpl.BadTokenException(
456 "Unable to add window -- app for token " + attrs.token
457 + " is exiting");
458 case WindowManagerImpl.ADD_DUPLICATE_ADD:
459 throw new WindowManagerImpl.BadTokenException(
460 "Unable to add window -- window " + mWindow
461 + " has already been added");
462 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
463 // Silently ignore -- we would have just removed it
464 // right away, anyway.
465 return;
466 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
467 throw new WindowManagerImpl.BadTokenException(
468 "Unable to add window " + mWindow +
469 " -- another window of this type already exists");
470 case WindowManagerImpl.ADD_PERMISSION_DENIED:
471 throw new WindowManagerImpl.BadTokenException(
472 "Unable to add window " + mWindow +
473 " -- permission denied for this window type");
474 }
475 throw new RuntimeException(
476 "Unable to add window -- unknown error code " + res);
477 }
478 view.assignParent(this);
479 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
480 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
481 }
482 }
483 }
484
485 public View getView() {
486 return mView;
487 }
488
489 final WindowLeaked getLocation() {
490 return mLocation;
491 }
492
493 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
494 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700495 int oldSoftInputMode = mWindowAttributes.softInputMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 if (newView) {
499 mSoftInputMode = attrs.softInputMode;
500 requestLayout();
501 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700502 // Don't lose the mode we last auto-computed.
503 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
504 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
505 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
506 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
507 | (oldSoftInputMode
508 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 mWindowAttributesChanged = true;
511 scheduleTraversals();
512 }
513 }
514
515 void handleAppVisibility(boolean visible) {
516 if (mAppVisible != visible) {
517 mAppVisible = visible;
518 scheduleTraversals();
519 }
520 }
521
522 void handleGetNewSurface() {
523 mNewSurfaceNeeded = true;
524 mFullRedrawNeeded = true;
525 scheduleTraversals();
526 }
527
528 /**
529 * {@inheritDoc}
530 */
531 public void requestLayout() {
532 checkThread();
533 mLayoutRequested = true;
534 scheduleTraversals();
535 }
536
537 /**
538 * {@inheritDoc}
539 */
540 public boolean isLayoutRequested() {
541 return mLayoutRequested;
542 }
543
544 public void invalidateChild(View child, Rect dirty) {
545 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700546 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
547 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 mTempRect.set(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700549 if (mCurScrollY != 0) {
550 mTempRect.offset(0, -mCurScrollY);
551 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700552 if (mTranslator != null) {
553 mTranslator.translateRectInAppWindowToScreen(mTempRect);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 dirty = mTempRect;
556 }
557 mDirty.union(dirty);
558 if (!mWillDrawSoon) {
559 scheduleTraversals();
560 }
561 }
562
563 public ViewParent getParent() {
564 return null;
565 }
566
567 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
568 invalidateChild(null, dirty);
569 return null;
570 }
571
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700572 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 if (child != mView) {
574 throw new RuntimeException("child is not mine, honest!");
575 }
576 // Note: don't apply scroll offset, because we want to know its
577 // visibility in the virtual canvas being given to the view hierarchy.
578 return r.intersect(0, 0, mWidth, mHeight);
579 }
580
581 public void bringChildToFront(View child) {
582 }
583
584 public void scheduleTraversals() {
585 if (!mTraversalScheduled) {
586 mTraversalScheduled = true;
587 sendEmptyMessage(DO_TRAVERSAL);
588 }
589 }
590
591 public void unscheduleTraversals() {
592 if (mTraversalScheduled) {
593 mTraversalScheduled = false;
594 removeMessages(DO_TRAVERSAL);
595 }
596 }
597
598 int getHostVisibility() {
599 return mAppVisible ? mView.getVisibility() : View.GONE;
600 }
Romain Guy8506ab42009-06-11 17:35:47 -0700601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 private void performTraversals() {
603 // cache mView since it is used so much below...
604 final View host = mView;
605
606 if (DBG) {
607 System.out.println("======================================");
608 System.out.println("performTraversals");
609 host.debug();
610 }
611
612 if (host == null || !mAdded)
613 return;
614
615 mTraversalScheduled = false;
616 mWillDrawSoon = true;
617 boolean windowResizesToFitContent = false;
618 boolean fullRedrawNeeded = mFullRedrawNeeded;
619 boolean newSurface = false;
620 WindowManager.LayoutParams lp = mWindowAttributes;
621
622 int desiredWindowWidth;
623 int desiredWindowHeight;
624 int childWidthMeasureSpec;
625 int childHeightMeasureSpec;
626
627 final View.AttachInfo attachInfo = mAttachInfo;
628
629 final int viewVisibility = getHostVisibility();
630 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
631 || mNewSurfaceNeeded;
632
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700633 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 WindowManager.LayoutParams params = null;
636 if (mWindowAttributesChanged) {
637 mWindowAttributesChanged = false;
638 params = lp;
639 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700640 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 if (mFirst) {
642 fullRedrawNeeded = true;
643 mLayoutRequested = true;
644
Romain Guy8506ab42009-06-11 17:35:47 -0700645 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700646 mView.getContext().getResources().getDisplayMetrics();
647 desiredWindowWidth = packageMetrics.widthPixels;
648 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649
650 // For the very first time, tell the view hierarchy that it
651 // is attached to the window. Note that at this point the surface
652 // object is not initialized to its backing store, but soon it
653 // will be (assuming the window is visible).
654 attachInfo.mSurface = mSurface;
655 attachInfo.mHasWindowFocus = false;
656 attachInfo.mWindowVisibility = viewVisibility;
657 attachInfo.mRecomputeGlobalAttributes = false;
658 attachInfo.mKeepScreenOn = false;
659 viewVisibilityChanged = false;
660 host.dispatchAttachedToWindow(attachInfo, 0);
661 getRunQueue().executeActions(attachInfo.mHandler);
662 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700665 desiredWindowWidth = frame.width();
666 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
668 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700669 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 fullRedrawNeeded = true;
671 mLayoutRequested = true;
672 windowResizesToFitContent = true;
673 }
674 }
675
676 if (viewVisibilityChanged) {
677 attachInfo.mWindowVisibility = viewVisibility;
678 host.dispatchWindowVisibilityChanged(viewVisibility);
679 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
680 if (mUseGL) {
681 destroyGL();
682 }
683 }
684 if (viewVisibility == View.GONE) {
685 // After making a window gone, we will count it as being
686 // shown for the first time the next time it gets focus.
687 mHasHadWindowFocus = false;
688 }
689 }
690
691 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 if (mLayoutRequested) {
694 if (mFirst) {
695 host.fitSystemWindows(mAttachInfo.mContentInsets);
696 // make sure touch mode code executes by setting cached value
697 // to opposite of the added touch mode.
698 mAttachInfo.mInTouchMode = !mAddedTouchMode;
699 ensureTouchModeLocally(mAddedTouchMode);
700 } else {
701 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
702 mAttachInfo.mContentInsets.set(mPendingContentInsets);
703 host.fitSystemWindows(mAttachInfo.mContentInsets);
704 insetsChanged = true;
705 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
706 + mAttachInfo.mContentInsets);
707 }
708 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
709 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
710 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
711 + mAttachInfo.mVisibleInsets);
712 }
713 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
714 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
715 windowResizesToFitContent = true;
716
Romain Guy8506ab42009-06-11 17:35:47 -0700717 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700718 mView.getContext().getResources().getDisplayMetrics();
719 desiredWindowWidth = packageMetrics.widthPixels;
720 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
722 }
723
724 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
725 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
726
727 // Ask host how big it wants to be
728 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
729 "Measuring " + host + " in display " + desiredWindowWidth
730 + "x" + desiredWindowHeight + "...");
731 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
732
733 if (DBG) {
734 System.out.println("======================================");
735 System.out.println("performTraversals -- after measure");
736 host.debug();
737 }
738 }
739
740 if (attachInfo.mRecomputeGlobalAttributes) {
741 //Log.i(TAG, "Computing screen on!");
742 attachInfo.mRecomputeGlobalAttributes = false;
743 boolean oldVal = attachInfo.mKeepScreenOn;
744 attachInfo.mKeepScreenOn = false;
745 host.dispatchCollectViewAttributes(0);
746 if (attachInfo.mKeepScreenOn != oldVal) {
747 params = lp;
748 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
749 }
750 }
751
752 if (mFirst || attachInfo.mViewVisibilityChanged) {
753 attachInfo.mViewVisibilityChanged = false;
754 int resizeMode = mSoftInputMode &
755 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
756 // If we are in auto resize mode, then we need to determine
757 // what mode to use now.
758 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
759 final int N = attachInfo.mScrollContainers.size();
760 for (int i=0; i<N; i++) {
761 if (attachInfo.mScrollContainers.get(i).isShown()) {
762 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
763 }
764 }
765 if (resizeMode == 0) {
766 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
767 }
768 if ((lp.softInputMode &
769 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
770 lp.softInputMode = (lp.softInputMode &
771 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
772 resizeMode;
773 params = lp;
774 }
775 }
776 }
Romain Guy8506ab42009-06-11 17:35:47 -0700777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
779 if (!PixelFormat.formatHasAlpha(params.format)) {
780 params.format = PixelFormat.TRANSLUCENT;
781 }
782 }
783
784 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
785 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
786
787 final boolean computesInternalInsets =
788 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
789 boolean insetsPending = false;
790 int relayoutResult = 0;
791 if (mFirst || windowShouldResize || insetsChanged
792 || viewVisibilityChanged || params != null) {
793
794 if (viewVisibility == View.VISIBLE) {
795 // If this window is giving internal insets to the window
796 // manager, and it is being added or changing its visibility,
797 // then we want to first give the window manager "fake"
798 // insets to cause it to effectively ignore the content of
799 // the window during layout. This avoids it briefly causing
800 // other windows to resize/move based on the raw frame of the
801 // window, waiting until we can finish laying out this window
802 // and get back to the window manager with the ultimately
803 // computed insets.
804 insetsPending = computesInternalInsets
805 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
808 if (params == null) {
809 params = mWindowAttributes;
810 }
811 mGlWanted = true;
812 }
813 }
814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 boolean initialized = false;
816 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700817 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 try {
819 boolean hadSurface = mSurface.isValid();
820 int fl = 0;
821 if (params != null) {
822 fl = params.flags;
823 if (attachInfo.mKeepScreenOn) {
824 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
825 }
826 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700827 if (DEBUG_LAYOUT) {
828 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
829 host.mMeasuredHeight + ", params=" + params);
830 }
831 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 if (params != null) {
834 params.flags = fl;
835 }
836
837 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
838 + " content=" + mPendingContentInsets.toShortString()
839 + " visible=" + mPendingVisibleInsets.toShortString()
840 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 contentInsetsChanged = !mPendingContentInsets.equals(
843 mAttachInfo.mContentInsets);
844 visibleInsetsChanged = !mPendingVisibleInsets.equals(
845 mAttachInfo.mVisibleInsets);
846 if (contentInsetsChanged) {
847 mAttachInfo.mContentInsets.set(mPendingContentInsets);
848 host.fitSystemWindows(mAttachInfo.mContentInsets);
849 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
850 + mAttachInfo.mContentInsets);
851 }
852 if (visibleInsetsChanged) {
853 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
854 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
855 + mAttachInfo.mVisibleInsets);
856 }
857
858 if (!hadSurface) {
859 if (mSurface.isValid()) {
860 // If we are creating a new surface, then we need to
861 // completely redraw it. Also, when we get to the
862 // point of drawing it we will hold off and schedule
863 // a new traversal instead. This is so we can tell the
864 // window manager about all of the windows being displayed
865 // before actually drawing them, so it can display then
866 // all at once.
867 newSurface = true;
868 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 if (mGlWanted && !mUseGL) {
871 initializeGL();
872 initialized = mGlCanvas != null;
873 }
874 }
875 } else if (!mSurface.isValid()) {
876 // If the surface has been removed, then reset the scroll
877 // positions.
878 mLastScrolledFocus = null;
879 mScrollY = mCurScrollY = 0;
880 if (mScroller != null) {
881 mScroller.abortAnimation();
882 }
883 }
884 } catch (RemoteException e) {
885 }
886 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700887 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888
889 attachInfo.mWindowLeft = frame.left;
890 attachInfo.mWindowTop = frame.top;
891
892 // !!FIXME!! This next section handles the case where we did not get the
893 // window size we asked for. We should avoid this by getting a maximum size from
894 // the window session beforehand.
895 mWidth = frame.width();
896 mHeight = frame.height();
897
898 if (initialized) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700899 mGlCanvas.setViewport((int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 }
901
902 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
903 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
904 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
905 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
906 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
907 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
908
909 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
910 + mWidth + " measuredWidth=" + host.mMeasuredWidth
911 + " mHeight=" + mHeight
912 + " measuredHeight" + host.mMeasuredHeight
913 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 // Ask host how big it wants to be
916 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
917
918 // Implementation of weights from WindowManager.LayoutParams
919 // We just grow the dimensions as needed and re-measure if
920 // needs be
921 int width = host.mMeasuredWidth;
922 int height = host.mMeasuredHeight;
923 boolean measureAgain = false;
924
925 if (lp.horizontalWeight > 0.0f) {
926 width += (int) ((mWidth - width) * lp.horizontalWeight);
927 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
928 MeasureSpec.EXACTLY);
929 measureAgain = true;
930 }
931 if (lp.verticalWeight > 0.0f) {
932 height += (int) ((mHeight - height) * lp.verticalWeight);
933 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
934 MeasureSpec.EXACTLY);
935 measureAgain = true;
936 }
937
938 if (measureAgain) {
939 if (DEBUG_LAYOUT) Log.v(TAG,
940 "And hey let's measure once more: width=" + width
941 + " height=" + height);
942 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
943 }
944
945 mLayoutRequested = true;
946 }
947 }
948
949 final boolean didLayout = mLayoutRequested;
950 boolean triggerGlobalLayoutListener = didLayout
951 || attachInfo.mRecomputeGlobalAttributes;
952 if (didLayout) {
953 mLayoutRequested = false;
954 mScrollMayChange = true;
955 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
956 "ViewRoot", "Laying out " + host + " to (" +
957 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700958 long startTime = 0L;
959 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 startTime = SystemClock.elapsedRealtime();
961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
963
Romain Guy13922e02009-05-12 17:56:14 -0700964 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
965 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
966 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
967 + "please refer to the logs with the tag "
968 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
969 }
970 }
971
972 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
974 }
975
976 // By this point all views have been sized and positionned
977 // We can compute the transparent area
978
979 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
980 // start out transparent
981 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
982 host.getLocationInWindow(mTmpLocation);
983 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
984 mTmpLocation[0] + host.mRight - host.mLeft,
985 mTmpLocation[1] + host.mBottom - host.mTop);
986
987 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700988 if (mTranslator != null) {
989 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
990 }
991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
993 mPreviousTransparentRegion.set(mTransparentRegion);
994 // reconfigure window manager
995 try {
996 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
997 } catch (RemoteException e) {
998 }
999 }
1000 }
1001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 if (DBG) {
1003 System.out.println("======================================");
1004 System.out.println("performTraversals -- after setFrame");
1005 host.debug();
1006 }
1007 }
1008
1009 if (triggerGlobalLayoutListener) {
1010 attachInfo.mRecomputeGlobalAttributes = false;
1011 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1012 }
1013
1014 if (computesInternalInsets) {
1015 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1016 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1017 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1018 givenContent.left = givenContent.top = givenContent.right
1019 = givenContent.bottom = givenVisible.left = givenVisible.top
1020 = givenVisible.right = givenVisible.bottom = 0;
1021 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001022 Rect contentInsets = insets.contentInsets;
1023 Rect visibleInsets = insets.visibleInsets;
1024 if (mTranslator != null) {
1025 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1026 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1029 mLastGivenInsets.set(insets);
1030 try {
1031 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001032 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 } catch (RemoteException e) {
1034 }
1035 }
1036 }
Romain Guy8506ab42009-06-11 17:35:47 -07001037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 if (mFirst) {
1039 // handle first focus request
1040 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1041 + mView.hasFocus());
1042 if (mView != null) {
1043 if (!mView.hasFocus()) {
1044 mView.requestFocus(View.FOCUS_FORWARD);
1045 mFocusedView = mRealFocusedView = mView.findFocus();
1046 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1047 + mFocusedView);
1048 } else {
1049 mRealFocusedView = mView.findFocus();
1050 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1051 + mRealFocusedView);
1052 }
1053 }
1054 }
1055
1056 mFirst = false;
1057 mWillDrawSoon = false;
1058 mNewSurfaceNeeded = false;
1059 mViewVisibility = viewVisibility;
1060
1061 if (mAttachInfo.mHasWindowFocus) {
1062 final boolean imTarget = WindowManager.LayoutParams
1063 .mayUseInputMethod(mWindowAttributes.flags);
1064 if (imTarget != mLastWasImTarget) {
1065 mLastWasImTarget = imTarget;
1066 InputMethodManager imm = InputMethodManager.peekInstance();
1067 if (imm != null && imTarget) {
1068 imm.startGettingWindowFocus(mView);
1069 imm.onWindowFocus(mView, mView.findFocus(),
1070 mWindowAttributes.softInputMode,
1071 !mHasHadWindowFocus, mWindowAttributes.flags);
1072 }
1073 }
1074 }
Romain Guy8506ab42009-06-11 17:35:47 -07001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1077
1078 if (!cancelDraw && !newSurface) {
1079 mFullRedrawNeeded = false;
1080 draw(fullRedrawNeeded);
1081
1082 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1083 || mReportNextDraw) {
1084 if (LOCAL_LOGV) {
1085 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1086 }
1087 mReportNextDraw = false;
1088 try {
1089 sWindowSession.finishDrawing(mWindow);
1090 } catch (RemoteException e) {
1091 }
1092 }
1093 } else {
1094 // We were supposed to report when we are done drawing. Since we canceled the
1095 // draw, remember it here.
1096 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1097 mReportNextDraw = true;
1098 }
1099 if (fullRedrawNeeded) {
1100 mFullRedrawNeeded = true;
1101 }
1102 // Try again
1103 scheduleTraversals();
1104 }
1105 }
1106
1107 public void requestTransparentRegion(View child) {
1108 // the test below should not fail unless someone is messing with us
1109 checkThread();
1110 if (mView == child) {
1111 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1112 // Need to make sure we re-evaluate the window attributes next
1113 // time around, to ensure the window has the correct format.
1114 mWindowAttributesChanged = true;
1115 }
1116 }
1117
1118 /**
1119 * Figures out the measure spec for the root view in a window based on it's
1120 * layout params.
1121 *
1122 * @param windowSize
1123 * The available width or height of the window
1124 *
1125 * @param rootDimension
1126 * The layout params for one dimension (width or height) of the
1127 * window.
1128 *
1129 * @return The measure spec to use to measure the root view.
1130 */
1131 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1132 int measureSpec;
1133 switch (rootDimension) {
1134
1135 case ViewGroup.LayoutParams.FILL_PARENT:
1136 // Window can't resize. Force root view to be windowSize.
1137 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1138 break;
1139 case ViewGroup.LayoutParams.WRAP_CONTENT:
1140 // Window can resize. Set max size for root view.
1141 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1142 break;
1143 default:
1144 // Window wants to be an exact size. Force root view to be that size.
1145 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1146 break;
1147 }
1148 return measureSpec;
1149 }
1150
1151 private void draw(boolean fullRedrawNeeded) {
1152 Surface surface = mSurface;
1153 if (surface == null || !surface.isValid()) {
1154 return;
1155 }
1156
1157 scrollToRectOrFocus(null, false);
1158
1159 if (mAttachInfo.mViewScrollChanged) {
1160 mAttachInfo.mViewScrollChanged = false;
1161 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1162 }
Romain Guy8506ab42009-06-11 17:35:47 -07001163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001165 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 if (scrolling) {
1167 yoff = mScroller.getCurrY();
1168 } else {
1169 yoff = mScrollY;
1170 }
1171 if (mCurScrollY != yoff) {
1172 mCurScrollY = yoff;
1173 fullRedrawNeeded = true;
1174 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001175 float appScale = mAttachInfo.mApplicationScale;
1176 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177
1178 Rect dirty = mDirty;
1179 if (mUseGL) {
1180 if (!dirty.isEmpty()) {
1181 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001182 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 mGL.glDisable(GL_SCISSOR_TEST);
1184 mGL.glClearColor(0, 0, 0, 0);
1185 mGL.glClear(GL_COLOR_BUFFER_BIT);
1186 mGL.glEnable(GL_SCISSOR_TEST);
1187
1188 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001189 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001191
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001192 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1193 try {
1194 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001195 if (mTranslator != null) {
1196 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001197 }
1198 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001199 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1200 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1201 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001202 } finally {
1203 canvas.restoreToCount(saveCount);
1204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205
Romain Guy5bcdff42009-05-14 21:27:18 -07001206 mAttachInfo.mIgnoreDirtyState = false;
1207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1209 checkEglErrors();
1210
Romain Guy13922e02009-05-12 17:56:14 -07001211 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 int now = (int)SystemClock.elapsedRealtime();
1213 if (sDrawTime != 0) {
1214 nativeShowFPS(canvas, now - sDrawTime);
1215 }
1216 sDrawTime = now;
1217 }
1218 }
1219 }
1220 if (scrolling) {
1221 mFullRedrawNeeded = true;
1222 scheduleTraversals();
1223 }
1224 return;
1225 }
1226
Romain Guy5bcdff42009-05-14 21:27:18 -07001227 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001228 mAttachInfo.mIgnoreDirtyState = true;
1229 dirty.union(0, 0, (int) (mWidth * appScale), (int) (mHeight * appScale));
Romain Guy5bcdff42009-05-14 21:27:18 -07001230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231
1232 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1233 Log.v("ViewRoot", "Draw " + mView + "/"
1234 + mWindowAttributes.getTitle()
1235 + ": dirty={" + dirty.left + "," + dirty.top
1236 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001237 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1238 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 }
1240
1241 Canvas canvas;
1242 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001243 int left = dirty.left;
1244 int top = dirty.top;
1245 int right = dirty.right;
1246 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001248
1249 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1250 bottom != dirty.bottom) {
1251 mAttachInfo.mIgnoreDirtyState = true;
1252 }
1253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 // TODO: Do this in native
1255 canvas.setDensityScale(mDensity);
1256 } catch (Surface.OutOfResourcesException e) {
1257 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1258 // TODO: we should ask the window manager to do something!
1259 // for now we just do nothing
1260 return;
1261 }
1262
1263 try {
Romain Guybb93d552009-03-24 21:04:15 -07001264 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001265 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266
1267 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1268 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1269 + canvas.getWidth() + ", h=" + canvas.getHeight());
1270 //canvas.drawARGB(255, 255, 0, 0);
1271 }
1272
Romain Guy13922e02009-05-12 17:56:14 -07001273 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 startTime = SystemClock.elapsedRealtime();
1275 }
1276
1277 // If this bitmap's format includes an alpha channel, we
1278 // need to clear it before drawing so that the child will
1279 // properly re-composite its drawing on a transparent
1280 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001281 // or
1282 // If we are applying an offset, we need to clear the area
1283 // where the offset doesn't appear to avoid having garbage
1284 // left in the blank areas.
1285 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1287 }
1288
1289 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001290 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001292 mView.mPrivateFlags |= View.DRAWN;
1293
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001294 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001295 Context cxt = mView.getContext();
1296 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001297 ", metrics=" + mView.getContext().getResources().getDisplayMetrics());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001298 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001299 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001300 try {
1301 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001302 if (mTranslator != null) {
1303 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001304 }
1305 mView.draw(canvas);
1306 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001307 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001308 canvas.restoreToCount(saveCount);
1309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310
Romain Guy5bcdff42009-05-14 21:27:18 -07001311 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1312 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1313 }
1314
Romain Guy13922e02009-05-12 17:56:14 -07001315 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 int now = (int)SystemClock.elapsedRealtime();
1317 if (sDrawTime != 0) {
1318 nativeShowFPS(canvas, now - sDrawTime);
1319 }
1320 sDrawTime = now;
1321 }
1322
Romain Guy13922e02009-05-12 17:56:14 -07001323 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1325 }
1326 }
Romain Guy8506ab42009-06-11 17:35:47 -07001327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 } finally {
1329 surface.unlockCanvasAndPost(canvas);
1330 }
1331
1332 if (LOCAL_LOGV) {
1333 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1334 }
Romain Guy8506ab42009-06-11 17:35:47 -07001335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 if (scrolling) {
1337 mFullRedrawNeeded = true;
1338 scheduleTraversals();
1339 }
1340 }
1341
1342 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1343 final View.AttachInfo attachInfo = mAttachInfo;
1344 final Rect ci = attachInfo.mContentInsets;
1345 final Rect vi = attachInfo.mVisibleInsets;
1346 int scrollY = 0;
1347 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 if (vi.left > ci.left || vi.top > ci.top
1350 || vi.right > ci.right || vi.bottom > ci.bottom) {
1351 // We'll assume that we aren't going to change the scroll
1352 // offset, since we want to avoid that unless it is actually
1353 // going to make the focus visible... otherwise we scroll
1354 // all over the place.
1355 scrollY = mScrollY;
1356 // We can be called for two different situations: during a draw,
1357 // to update the scroll position if the focus has changed (in which
1358 // case 'rectangle' is null), or in response to a
1359 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1360 // is non-null and we just want to scroll to whatever that
1361 // rectangle is).
1362 View focus = mRealFocusedView;
1363 if (focus != mLastScrolledFocus) {
1364 // If the focus has changed, then ignore any requests to scroll
1365 // to a rectangle; first we want to make sure the entire focus
1366 // view is visible.
1367 rectangle = null;
1368 }
1369 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1370 + " rectangle=" + rectangle + " ci=" + ci
1371 + " vi=" + vi);
1372 if (focus == mLastScrolledFocus && !mScrollMayChange
1373 && rectangle == null) {
1374 // Optimization: if the focus hasn't changed since last
1375 // time, and no layout has happened, then just leave things
1376 // as they are.
1377 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1378 + mScrollY + " vi=" + vi.toShortString());
1379 } else if (focus != null) {
1380 // We need to determine if the currently focused view is
1381 // within the visible part of the window and, if not, apply
1382 // a pan so it can be seen.
1383 mLastScrolledFocus = focus;
1384 mScrollMayChange = false;
1385 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1386 // Try to find the rectangle from the focus view.
1387 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1388 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1389 + mView.getWidth() + " h=" + mView.getHeight()
1390 + " ci=" + ci.toShortString()
1391 + " vi=" + vi.toShortString());
1392 if (rectangle == null) {
1393 focus.getFocusedRect(mTempRect);
1394 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1395 + ": focusRect=" + mTempRect.toShortString());
1396 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1397 focus, mTempRect);
1398 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1399 "Focus in window: focusRect="
1400 + mTempRect.toShortString()
1401 + " visRect=" + mVisRect.toShortString());
1402 } else {
1403 mTempRect.set(rectangle);
1404 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1405 "Request scroll to rect: "
1406 + mTempRect.toShortString()
1407 + " visRect=" + mVisRect.toShortString());
1408 }
1409 if (mTempRect.intersect(mVisRect)) {
1410 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1411 "Focus window visible rect: "
1412 + mTempRect.toShortString());
1413 if (mTempRect.height() >
1414 (mView.getHeight()-vi.top-vi.bottom)) {
1415 // If the focus simply is not going to fit, then
1416 // best is probably just to leave things as-is.
1417 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1418 "Too tall; leaving scrollY=" + scrollY);
1419 } else if ((mTempRect.top-scrollY) < vi.top) {
1420 scrollY -= vi.top - (mTempRect.top-scrollY);
1421 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1422 "Top covered; scrollY=" + scrollY);
1423 } else if ((mTempRect.bottom-scrollY)
1424 > (mView.getHeight()-vi.bottom)) {
1425 scrollY += (mTempRect.bottom-scrollY)
1426 - (mView.getHeight()-vi.bottom);
1427 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1428 "Bottom covered; scrollY=" + scrollY);
1429 }
1430 handled = true;
1431 }
1432 }
1433 }
1434 }
Romain Guy8506ab42009-06-11 17:35:47 -07001435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 if (scrollY != mScrollY) {
1437 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1438 + mScrollY + " , new=" + scrollY);
1439 if (!immediate) {
1440 if (mScroller == null) {
1441 mScroller = new Scroller(mView.getContext());
1442 }
1443 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1444 } else if (mScroller != null) {
1445 mScroller.abortAnimation();
1446 }
1447 mScrollY = scrollY;
1448 }
Romain Guy8506ab42009-06-11 17:35:47 -07001449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 return handled;
1451 }
Romain Guy8506ab42009-06-11 17:35:47 -07001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 public void requestChildFocus(View child, View focused) {
1454 checkThread();
1455 if (mFocusedView != focused) {
1456 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1457 scheduleTraversals();
1458 }
1459 mFocusedView = mRealFocusedView = focused;
1460 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1461 + mFocusedView);
1462 }
1463
1464 public void clearChildFocus(View child) {
1465 checkThread();
1466
1467 View oldFocus = mFocusedView;
1468
1469 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1470 mFocusedView = mRealFocusedView = null;
1471 if (mView != null && !mView.hasFocus()) {
1472 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1473 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1474 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1475 }
1476 } else if (oldFocus != null) {
1477 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1478 }
1479 }
1480
1481
1482 public void focusableViewAvailable(View v) {
1483 checkThread();
1484
1485 if (mView != null && !mView.hasFocus()) {
1486 v.requestFocus();
1487 } else {
1488 // the one case where will transfer focus away from the current one
1489 // is if the current view is a view group that prefers to give focus
1490 // to its children first AND the view is a descendant of it.
1491 mFocusedView = mView.findFocus();
1492 boolean descendantsHaveDibsOnFocus =
1493 (mFocusedView instanceof ViewGroup) &&
1494 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1495 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1496 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1497 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1498 v.requestFocus();
1499 }
1500 }
1501 }
1502
1503 public void recomputeViewAttributes(View child) {
1504 checkThread();
1505 if (mView == child) {
1506 mAttachInfo.mRecomputeGlobalAttributes = true;
1507 if (!mWillDrawSoon) {
1508 scheduleTraversals();
1509 }
1510 }
1511 }
1512
1513 void dispatchDetachedFromWindow() {
1514 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1515
1516 if (mView != null) {
1517 mView.dispatchDetachedFromWindow();
1518 }
1519
1520 mView = null;
1521 mAttachInfo.mRootView = null;
1522
1523 if (mUseGL) {
1524 destroyGL();
1525 }
1526
1527 try {
1528 sWindowSession.remove(mWindow);
1529 } catch (RemoteException e) {
1530 }
1531 }
Romain Guy8506ab42009-06-11 17:35:47 -07001532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 /**
1534 * Return true if child is an ancestor of parent, (or equal to the parent).
1535 */
1536 private static boolean isViewDescendantOf(View child, View parent) {
1537 if (child == parent) {
1538 return true;
1539 }
1540
1541 final ViewParent theParent = child.getParent();
1542 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1543 }
1544
1545
1546 public final static int DO_TRAVERSAL = 1000;
1547 public final static int DIE = 1001;
1548 public final static int RESIZED = 1002;
1549 public final static int RESIZED_REPORT = 1003;
1550 public final static int WINDOW_FOCUS_CHANGED = 1004;
1551 public final static int DISPATCH_KEY = 1005;
1552 public final static int DISPATCH_POINTER = 1006;
1553 public final static int DISPATCH_TRACKBALL = 1007;
1554 public final static int DISPATCH_APP_VISIBILITY = 1008;
1555 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1556 public final static int FINISHED_EVENT = 1010;
1557 public final static int DISPATCH_KEY_FROM_IME = 1011;
1558 public final static int FINISH_INPUT_CONNECTION = 1012;
1559 public final static int CHECK_FOCUS = 1013;
1560
1561 @Override
1562 public void handleMessage(Message msg) {
1563 switch (msg.what) {
1564 case View.AttachInfo.INVALIDATE_MSG:
1565 ((View) msg.obj).invalidate();
1566 break;
1567 case View.AttachInfo.INVALIDATE_RECT_MSG:
1568 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1569 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1570 info.release();
1571 break;
1572 case DO_TRAVERSAL:
1573 if (mProfile) {
1574 Debug.startMethodTracing("ViewRoot");
1575 }
1576
1577 performTraversals();
1578
1579 if (mProfile) {
1580 Debug.stopMethodTracing();
1581 mProfile = false;
1582 }
1583 break;
1584 case FINISHED_EVENT:
1585 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1586 break;
1587 case DISPATCH_KEY:
1588 if (LOCAL_LOGV) Log.v(
1589 "ViewRoot", "Dispatching key "
1590 + msg.obj + " to " + mView);
1591 deliverKeyEvent((KeyEvent)msg.obj, true);
1592 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001593 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 MotionEvent event = (MotionEvent)msg.obj;
1595
1596 boolean didFinish;
1597 if (event == null) {
1598 try {
1599 event = sWindowSession.getPendingPointerMove(mWindow);
1600 } catch (RemoteException e) {
1601 }
1602 didFinish = true;
1603 } else {
1604 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
1605 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001606 if (event != null && mTranslator != null) {
1607 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 try {
1610 boolean handled;
1611 if (mView != null && mAdded && event != null) {
1612
1613 // enter touch mode on the down
1614 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1615 if (isDown) {
1616 ensureTouchMode(true);
1617 }
1618 if(Config.LOGV) {
1619 captureMotionLog("captureDispatchPointer", event);
1620 }
1621 event.offsetLocation(0, mCurScrollY);
1622 handled = mView.dispatchTouchEvent(event);
1623 if (!handled && isDown) {
1624 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1625
1626 final int edgeFlags = event.getEdgeFlags();
1627 int direction = View.FOCUS_UP;
1628 int x = (int)event.getX();
1629 int y = (int)event.getY();
1630 final int[] deltas = new int[2];
1631
1632 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1633 direction = View.FOCUS_DOWN;
1634 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1635 deltas[0] = edgeSlop;
1636 x += edgeSlop;
1637 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1638 deltas[0] = -edgeSlop;
1639 x -= edgeSlop;
1640 }
1641 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1642 direction = View.FOCUS_UP;
1643 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1644 deltas[0] = edgeSlop;
1645 x += edgeSlop;
1646 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1647 deltas[0] = -edgeSlop;
1648 x -= edgeSlop;
1649 }
1650 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1651 direction = View.FOCUS_RIGHT;
1652 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1653 direction = View.FOCUS_LEFT;
1654 }
1655
1656 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1657 View nearest = FocusFinder.getInstance().findNearestTouchable(
1658 ((ViewGroup) mView), x, y, direction, deltas);
1659 if (nearest != null) {
1660 event.offsetLocation(deltas[0], deltas[1]);
1661 event.setEdgeFlags(0);
1662 mView.dispatchTouchEvent(event);
1663 }
1664 }
1665 }
1666 }
1667 } finally {
1668 if (!didFinish) {
1669 try {
1670 sWindowSession.finishKey(mWindow);
1671 } catch (RemoteException e) {
1672 }
1673 }
1674 if (event != null) {
1675 event.recycle();
1676 }
1677 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1678 // Let the exception fall through -- the looper will catch
1679 // it and take care of the bad app for us.
1680 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001681 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 case DISPATCH_TRACKBALL:
1683 deliverTrackballEvent((MotionEvent)msg.obj);
1684 break;
1685 case DISPATCH_APP_VISIBILITY:
1686 handleAppVisibility(msg.arg1 != 0);
1687 break;
1688 case DISPATCH_GET_NEW_SURFACE:
1689 handleGetNewSurface();
1690 break;
1691 case RESIZED:
1692 Rect coveredInsets = ((Rect[])msg.obj)[0];
1693 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1696 && mPendingContentInsets.equals(coveredInsets)
1697 && mPendingVisibleInsets.equals(visibleInsets)) {
1698 break;
1699 }
1700 // fall through...
1701 case RESIZED_REPORT:
1702 if (mAdded) {
1703 mWinFrame.left = 0;
1704 mWinFrame.right = msg.arg1;
1705 mWinFrame.top = 0;
1706 mWinFrame.bottom = msg.arg2;
1707 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1708 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1709 if (msg.what == RESIZED_REPORT) {
1710 mReportNextDraw = true;
1711 }
1712 requestLayout();
1713 }
1714 break;
1715 case WINDOW_FOCUS_CHANGED: {
1716 if (mAdded) {
1717 boolean hasWindowFocus = msg.arg1 != 0;
1718 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1719 if (hasWindowFocus) {
1720 boolean inTouchMode = msg.arg2 != 0;
1721 ensureTouchModeLocally(inTouchMode);
1722
1723 if (mGlWanted) {
1724 checkEglErrors();
1725 // we lost the gl context, so recreate it.
1726 if (mGlWanted && !mUseGL) {
1727 initializeGL();
1728 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001729 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001730 mGlCanvas.setViewport(
1731 (int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
1733 }
1734 }
1735 }
Romain Guy8506ab42009-06-11 17:35:47 -07001736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 mLastWasImTarget = WindowManager.LayoutParams
1738 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 InputMethodManager imm = InputMethodManager.peekInstance();
1741 if (mView != null) {
1742 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1743 imm.startGettingWindowFocus(mView);
1744 }
1745 mView.dispatchWindowFocusChanged(hasWindowFocus);
1746 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 // Note: must be done after the focus change callbacks,
1749 // so all of the view state is set up correctly.
1750 if (hasWindowFocus) {
1751 if (imm != null && mLastWasImTarget) {
1752 imm.onWindowFocus(mView, mView.findFocus(),
1753 mWindowAttributes.softInputMode,
1754 !mHasHadWindowFocus, mWindowAttributes.flags);
1755 }
1756 // Clear the forward bit. We can just do this directly, since
1757 // the window manager doesn't care about it.
1758 mWindowAttributes.softInputMode &=
1759 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1760 ((WindowManager.LayoutParams)mView.getLayoutParams())
1761 .softInputMode &=
1762 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1763 mHasHadWindowFocus = true;
1764 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001765
1766 if (hasWindowFocus && mView != null) {
1767 sendAccessibilityEvents();
1768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770 } break;
1771 case DIE:
1772 dispatchDetachedFromWindow();
1773 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001774 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 if (LOCAL_LOGV) Log.v(
1776 "ViewRoot", "Dispatching key "
1777 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001778 KeyEvent event = (KeyEvent)msg.obj;
1779 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1780 // The IME is trying to say this event is from the
1781 // system! Bad bad bad!
1782 event = KeyEvent.changeFlags(event,
1783 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001786 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 case FINISH_INPUT_CONNECTION: {
1788 InputMethodManager imm = InputMethodManager.peekInstance();
1789 if (imm != null) {
1790 imm.reportFinishInputConnection((InputConnection)msg.obj);
1791 }
1792 } break;
1793 case CHECK_FOCUS: {
1794 InputMethodManager imm = InputMethodManager.peekInstance();
1795 if (imm != null) {
1796 imm.checkFocus();
1797 }
1798 } break;
1799 }
1800 }
1801
1802 /**
1803 * Something in the current window tells us we need to change the touch mode. For
1804 * example, we are not in touch mode, and the user touches the screen.
1805 *
1806 * If the touch mode has changed, tell the window manager, and handle it locally.
1807 *
1808 * @param inTouchMode Whether we want to be in touch mode.
1809 * @return True if the touch mode changed and focus changed was changed as a result
1810 */
1811 boolean ensureTouchMode(boolean inTouchMode) {
1812 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1813 + "touch mode is " + mAttachInfo.mInTouchMode);
1814 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1815
1816 // tell the window manager
1817 try {
1818 sWindowSession.setInTouchMode(inTouchMode);
1819 } catch (RemoteException e) {
1820 throw new RuntimeException(e);
1821 }
1822
1823 // handle the change
1824 return ensureTouchModeLocally(inTouchMode);
1825 }
1826
1827 /**
1828 * Ensure that the touch mode for this window is set, and if it is changing,
1829 * take the appropriate action.
1830 * @param inTouchMode Whether we want to be in touch mode.
1831 * @return True if the touch mode changed and focus changed was changed as a result
1832 */
1833 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1834 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1835 + "touch mode is " + mAttachInfo.mInTouchMode);
1836
1837 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1838
1839 mAttachInfo.mInTouchMode = inTouchMode;
1840 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1841
1842 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1843 }
1844
1845 private boolean enterTouchMode() {
1846 if (mView != null) {
1847 if (mView.hasFocus()) {
1848 // note: not relying on mFocusedView here because this could
1849 // be when the window is first being added, and mFocused isn't
1850 // set yet.
1851 final View focused = mView.findFocus();
1852 if (focused != null && !focused.isFocusableInTouchMode()) {
1853
1854 final ViewGroup ancestorToTakeFocus =
1855 findAncestorToTakeFocusInTouchMode(focused);
1856 if (ancestorToTakeFocus != null) {
1857 // there is an ancestor that wants focus after its descendants that
1858 // is focusable in touch mode.. give it focus
1859 return ancestorToTakeFocus.requestFocus();
1860 } else {
1861 // nothing appropriate to have focus in touch mode, clear it out
1862 mView.unFocus();
1863 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1864 mFocusedView = null;
1865 return true;
1866 }
1867 }
1868 }
1869 }
1870 return false;
1871 }
1872
1873
1874 /**
1875 * Find an ancestor of focused that wants focus after its descendants and is
1876 * focusable in touch mode.
1877 * @param focused The currently focused view.
1878 * @return An appropriate view, or null if no such view exists.
1879 */
1880 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1881 ViewParent parent = focused.getParent();
1882 while (parent instanceof ViewGroup) {
1883 final ViewGroup vgParent = (ViewGroup) parent;
1884 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1885 && vgParent.isFocusableInTouchMode()) {
1886 return vgParent;
1887 }
1888 if (vgParent.isRootNamespace()) {
1889 return null;
1890 } else {
1891 parent = vgParent.getParent();
1892 }
1893 }
1894 return null;
1895 }
1896
1897 private boolean leaveTouchMode() {
1898 if (mView != null) {
1899 if (mView.hasFocus()) {
1900 // i learned the hard way to not trust mFocusedView :)
1901 mFocusedView = mView.findFocus();
1902 if (!(mFocusedView instanceof ViewGroup)) {
1903 // some view has focus, let it keep it
1904 return false;
1905 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1906 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1907 // some view group has focus, and doesn't prefer its children
1908 // over itself for focus, so let them keep it.
1909 return false;
1910 }
1911 }
1912
1913 // find the best view to give focus to in this brave new non-touch-mode
1914 // world
1915 final View focused = focusSearch(null, View.FOCUS_DOWN);
1916 if (focused != null) {
1917 return focused.requestFocus(View.FOCUS_DOWN);
1918 }
1919 }
1920 return false;
1921 }
1922
1923
1924 private void deliverTrackballEvent(MotionEvent event) {
1925 boolean didFinish;
1926 if (event == null) {
1927 try {
1928 event = sWindowSession.getPendingTrackballMove(mWindow);
1929 } catch (RemoteException e) {
1930 }
1931 didFinish = true;
1932 } else {
1933 didFinish = false;
1934 }
1935
1936 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
1937
1938 boolean handled = false;
1939 try {
1940 if (event == null) {
1941 handled = true;
1942 } else if (mView != null && mAdded) {
1943 handled = mView.dispatchTrackballEvent(event);
1944 if (!handled) {
1945 // we could do something here, like changing the focus
1946 // or something?
1947 }
1948 }
1949 } finally {
1950 if (handled) {
1951 if (!didFinish) {
1952 try {
1953 sWindowSession.finishKey(mWindow);
1954 } catch (RemoteException e) {
1955 }
1956 }
1957 if (event != null) {
1958 event.recycle();
1959 }
1960 // If we reach this, we delivered a trackball event to mView and
1961 // mView consumed it. Because we will not translate the trackball
1962 // event into a key event, touch mode will not exit, so we exit
1963 // touch mode here.
1964 ensureTouchMode(false);
1965 //noinspection ReturnInsideFinallyBlock
1966 return;
1967 }
1968 // Let the exception fall through -- the looper will catch
1969 // it and take care of the bad app for us.
1970 }
1971
1972 final TrackballAxis x = mTrackballAxisX;
1973 final TrackballAxis y = mTrackballAxisY;
1974
1975 long curTime = SystemClock.uptimeMillis();
1976 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
1977 // It has been too long since the last movement,
1978 // so restart at the beginning.
1979 x.reset(0);
1980 y.reset(0);
1981 mLastTrackballTime = curTime;
1982 }
1983
1984 try {
1985 final int action = event.getAction();
1986 final int metastate = event.getMetaState();
1987 switch (action) {
1988 case MotionEvent.ACTION_DOWN:
1989 x.reset(2);
1990 y.reset(2);
1991 deliverKeyEvent(new KeyEvent(curTime, curTime,
1992 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
1993 0, metastate), false);
1994 break;
1995 case MotionEvent.ACTION_UP:
1996 x.reset(2);
1997 y.reset(2);
1998 deliverKeyEvent(new KeyEvent(curTime, curTime,
1999 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2000 0, metastate), false);
2001 break;
2002 }
2003
2004 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2005 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2006 + " move=" + event.getX()
2007 + " / Y=" + y.position + " step="
2008 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2009 + " move=" + event.getY());
2010 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2011 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2012
2013 // Generate DPAD events based on the trackball movement.
2014 // We pick the axis that has moved the most as the direction of
2015 // the DPAD. When we generate DPAD events for one axis, then the
2016 // other axis is reset -- we don't want to perform DPAD jumps due
2017 // to slight movements in the trackball when making major movements
2018 // along the other axis.
2019 int keycode = 0;
2020 int movement = 0;
2021 float accel = 1;
2022 if (xOff > yOff) {
2023 movement = x.generate((2/event.getXPrecision()));
2024 if (movement != 0) {
2025 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2026 : KeyEvent.KEYCODE_DPAD_LEFT;
2027 accel = x.acceleration;
2028 y.reset(2);
2029 }
2030 } else if (yOff > 0) {
2031 movement = y.generate((2/event.getYPrecision()));
2032 if (movement != 0) {
2033 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2034 : KeyEvent.KEYCODE_DPAD_UP;
2035 accel = y.acceleration;
2036 x.reset(2);
2037 }
2038 }
2039
2040 if (keycode != 0) {
2041 if (movement < 0) movement = -movement;
2042 int accelMovement = (int)(movement * accel);
2043 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2044 + " accelMovement=" + accelMovement
2045 + " accel=" + accel);
2046 if (accelMovement > movement) {
2047 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2048 + keycode);
2049 movement--;
2050 deliverKeyEvent(new KeyEvent(curTime, curTime,
2051 KeyEvent.ACTION_MULTIPLE, keycode,
2052 accelMovement-movement, metastate), false);
2053 }
2054 while (movement > 0) {
2055 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2056 + keycode);
2057 movement--;
2058 curTime = SystemClock.uptimeMillis();
2059 deliverKeyEvent(new KeyEvent(curTime, curTime,
2060 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2061 deliverKeyEvent(new KeyEvent(curTime, curTime,
2062 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2063 }
2064 mLastTrackballTime = curTime;
2065 }
2066 } finally {
2067 if (!didFinish) {
2068 try {
2069 sWindowSession.finishKey(mWindow);
2070 } catch (RemoteException e) {
2071 }
2072 if (event != null) {
2073 event.recycle();
2074 }
2075 }
2076 // Let the exception fall through -- the looper will catch
2077 // it and take care of the bad app for us.
2078 }
2079 }
2080
2081 /**
2082 * @param keyCode The key code
2083 * @return True if the key is directional.
2084 */
2085 static boolean isDirectional(int keyCode) {
2086 switch (keyCode) {
2087 case KeyEvent.KEYCODE_DPAD_LEFT:
2088 case KeyEvent.KEYCODE_DPAD_RIGHT:
2089 case KeyEvent.KEYCODE_DPAD_UP:
2090 case KeyEvent.KEYCODE_DPAD_DOWN:
2091 return true;
2092 }
2093 return false;
2094 }
2095
2096 /**
2097 * Returns true if this key is a keyboard key.
2098 * @param keyEvent The key event.
2099 * @return whether this key is a keyboard key.
2100 */
2101 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2102 final int convertedKey = keyEvent.getUnicodeChar();
2103 return convertedKey > 0;
2104 }
2105
2106
2107
2108 /**
2109 * See if the key event means we should leave touch mode (and leave touch
2110 * mode if so).
2111 * @param event The key event.
2112 * @return Whether this key event should be consumed (meaning the act of
2113 * leaving touch mode alone is considered the event).
2114 */
2115 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2116 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2117 return false;
2118 }
2119 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2120 return false;
2121 }
2122
2123 // only relevant if we are in touch mode
2124 if (!mAttachInfo.mInTouchMode) {
2125 return false;
2126 }
2127
2128 // if something like an edit text has focus and the user is typing,
2129 // leave touch mode
2130 //
2131 // note: the condition of not being a keyboard key is kind of a hacky
2132 // approximation of whether we think the focused view will want the
2133 // key; if we knew for sure whether the focused view would consume
2134 // the event, that would be better.
2135 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2136 mFocusedView = mView.findFocus();
2137 if ((mFocusedView instanceof ViewGroup)
2138 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2139 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2140 // something has focus, but is holding it weakly as a container
2141 return false;
2142 }
2143 if (ensureTouchMode(false)) {
2144 throw new IllegalStateException("should not have changed focus "
2145 + "when leaving touch mode while a view has focus.");
2146 }
2147 return false;
2148 }
2149
2150 if (isDirectional(event.getKeyCode())) {
2151 // no view has focus, so we leave touch mode (and find something
2152 // to give focus to). the event is consumed if we were able to
2153 // find something to give focus to.
2154 return ensureTouchMode(false);
2155 }
2156 return false;
2157 }
2158
2159 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002160 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 */
2162 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002163 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 if (ev == null ||
2165 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2166 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
Romain Guy8506ab42009-06-11 17:35:47 -07002168
2169 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 sb.append(ev.getDownTime()).append(',');
2171 sb.append(ev.getEventTime()).append(',');
2172 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002173 sb.append(ev.getX()).append(',');
2174 sb.append(ev.getY()).append(',');
2175 sb.append(ev.getPressure()).append(',');
2176 sb.append(ev.getSize()).append(',');
2177 sb.append(ev.getMetaState()).append(',');
2178 sb.append(ev.getXPrecision()).append(',');
2179 sb.append(ev.getYPrecision()).append(',');
2180 sb.append(ev.getDeviceId()).append(',');
2181 sb.append(ev.getEdgeFlags());
2182 Log.d(TAG, sb.toString());
2183 }
2184 /**
2185 * log motion events
2186 */
2187 private static void captureKeyLog(String subTag, KeyEvent ev) {
2188 //check dynamic switch
2189 if (ev == null ||
2190 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2191 return;
2192 }
2193 StringBuilder sb = new StringBuilder(subTag + ": ");
2194 sb.append(ev.getDownTime()).append(',');
2195 sb.append(ev.getEventTime()).append(',');
2196 sb.append(ev.getAction()).append(',');
2197 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 sb.append(ev.getRepeatCount()).append(',');
2199 sb.append(ev.getMetaState()).append(',');
2200 sb.append(ev.getDeviceId()).append(',');
2201 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002202 Log.d(TAG, sb.toString());
2203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204
2205 int enqueuePendingEvent(Object event, boolean sendDone) {
2206 int seq = mPendingEventSeq+1;
2207 if (seq < 0) seq = 0;
2208 mPendingEventSeq = seq;
2209 mPendingEvents.put(seq, event);
2210 return sendDone ? seq : -seq;
2211 }
2212
2213 Object retrievePendingEvent(int seq) {
2214 if (seq < 0) seq = -seq;
2215 Object event = mPendingEvents.get(seq);
2216 if (event != null) {
2217 mPendingEvents.remove(seq);
2218 }
2219 return event;
2220 }
Romain Guy8506ab42009-06-11 17:35:47 -07002221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2223 // If mView is null, we just consume the key event because it doesn't
2224 // make sense to do anything else with it.
2225 boolean handled = mView != null
2226 ? mView.dispatchKeyEventPreIme(event) : true;
2227 if (handled) {
2228 if (sendDone) {
2229 if (LOCAL_LOGV) Log.v(
2230 "ViewRoot", "Telling window manager key is finished");
2231 try {
2232 sWindowSession.finishKey(mWindow);
2233 } catch (RemoteException e) {
2234 }
2235 }
2236 return;
2237 }
2238 // If it is possible for this window to interact with the input
2239 // method window, then we want to first dispatch our key events
2240 // to the input method.
2241 if (mLastWasImTarget) {
2242 InputMethodManager imm = InputMethodManager.peekInstance();
2243 if (imm != null && mView != null) {
2244 int seq = enqueuePendingEvent(event, sendDone);
2245 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2246 + seq + " event=" + event);
2247 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2248 mInputMethodCallback);
2249 return;
2250 }
2251 }
2252 deliverKeyEventToViewHierarchy(event, sendDone);
2253 }
2254
2255 void handleFinishedEvent(int seq, boolean handled) {
2256 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2257 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2258 + " handled=" + handled + " event=" + event);
2259 if (event != null) {
2260 final boolean sendDone = seq >= 0;
2261 if (!handled) {
2262 deliverKeyEventToViewHierarchy(event, sendDone);
2263 return;
2264 } else if (sendDone) {
2265 if (LOCAL_LOGV) Log.v(
2266 "ViewRoot", "Telling window manager key is finished");
2267 try {
2268 sWindowSession.finishKey(mWindow);
2269 } catch (RemoteException e) {
2270 }
2271 } else {
2272 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2273 + " handled=" + handled + " ev=" + event
2274 + ") neither delivering nor finishing key");
2275 }
2276 }
2277 }
Romain Guy8506ab42009-06-11 17:35:47 -07002278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2280 try {
2281 if (mView != null && mAdded) {
2282 final int action = event.getAction();
2283 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2284
2285 if (checkForLeavingTouchModeAndConsume(event)) {
2286 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002287 }
2288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 if (Config.LOGV) {
2290 captureKeyLog("captureDispatchKeyEvent", event);
2291 }
2292 boolean keyHandled = mView.dispatchKeyEvent(event);
2293
2294 if (!keyHandled && isDown) {
2295 int direction = 0;
2296 switch (event.getKeyCode()) {
2297 case KeyEvent.KEYCODE_DPAD_LEFT:
2298 direction = View.FOCUS_LEFT;
2299 break;
2300 case KeyEvent.KEYCODE_DPAD_RIGHT:
2301 direction = View.FOCUS_RIGHT;
2302 break;
2303 case KeyEvent.KEYCODE_DPAD_UP:
2304 direction = View.FOCUS_UP;
2305 break;
2306 case KeyEvent.KEYCODE_DPAD_DOWN:
2307 direction = View.FOCUS_DOWN;
2308 break;
2309 }
2310
2311 if (direction != 0) {
2312
2313 View focused = mView != null ? mView.findFocus() : null;
2314 if (focused != null) {
2315 View v = focused.focusSearch(direction);
2316 boolean focusPassed = false;
2317 if (v != null && v != focused) {
2318 // do the math the get the interesting rect
2319 // of previous focused into the coord system of
2320 // newly focused view
2321 focused.getFocusedRect(mTempRect);
2322 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2323 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2324 focusPassed = v.requestFocus(direction, mTempRect);
2325 }
2326
2327 if (!focusPassed) {
2328 mView.dispatchUnhandledMove(focused, direction);
2329 } else {
2330 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2331 }
2332 }
2333 }
2334 }
2335 }
2336
2337 } finally {
2338 if (sendDone) {
2339 if (LOCAL_LOGV) Log.v(
2340 "ViewRoot", "Telling window manager key is finished");
2341 try {
2342 sWindowSession.finishKey(mWindow);
2343 } catch (RemoteException e) {
2344 }
2345 }
2346 // Let the exception fall through -- the looper will catch
2347 // it and take care of the bad app for us.
2348 }
2349 }
2350
2351 private AudioManager getAudioManager() {
2352 if (mView == null) {
2353 throw new IllegalStateException("getAudioManager called when there is no mView");
2354 }
2355 if (mAudioManager == null) {
2356 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2357 }
2358 return mAudioManager;
2359 }
2360
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002361 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2362 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002363
2364 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002365 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002366 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002367 restore = true;
2368 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002369 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002370 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002371 if (params != null) {
2372 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002373 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002374 int relayoutResult = sWindowSession.relayout(
2375 mWindow, params,
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002376 (int) (mView.mMeasuredWidth * appScale),
2377 (int) (mView.mMeasuredHeight * appScale),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002378 viewVisibility, insetsPending, mWinFrame,
2379 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002380 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002381 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002382 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002383
2384 if (mTranslator != null) {
2385 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2386 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2387 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002388 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002389 return relayoutResult;
2390 }
Romain Guy8506ab42009-06-11 17:35:47 -07002391
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002392 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 * {@inheritDoc}
2394 */
2395 public void playSoundEffect(int effectId) {
2396 checkThread();
2397
2398 final AudioManager audioManager = getAudioManager();
2399
2400 switch (effectId) {
2401 case SoundEffectConstants.CLICK:
2402 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2403 return;
2404 case SoundEffectConstants.NAVIGATION_DOWN:
2405 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2406 return;
2407 case SoundEffectConstants.NAVIGATION_LEFT:
2408 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2409 return;
2410 case SoundEffectConstants.NAVIGATION_RIGHT:
2411 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2412 return;
2413 case SoundEffectConstants.NAVIGATION_UP:
2414 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2415 return;
2416 default:
2417 throw new IllegalArgumentException("unknown effect id " + effectId +
2418 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2419 }
2420 }
2421
2422 /**
2423 * {@inheritDoc}
2424 */
2425 public boolean performHapticFeedback(int effectId, boolean always) {
2426 try {
2427 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2428 } catch (RemoteException e) {
2429 return false;
2430 }
2431 }
2432
2433 /**
2434 * {@inheritDoc}
2435 */
2436 public View focusSearch(View focused, int direction) {
2437 checkThread();
2438 if (!(mView instanceof ViewGroup)) {
2439 return null;
2440 }
2441 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2442 }
2443
2444 public void debug() {
2445 mView.debug();
2446 }
2447
2448 public void die(boolean immediate) {
2449 checkThread();
2450 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2451 synchronized (this) {
2452 if (mAdded && !mFirst) {
2453 int viewVisibility = mView.getVisibility();
2454 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2455 if (mWindowAttributesChanged || viewVisibilityChanged) {
2456 // If layout params have been changed, first give them
2457 // to the window manager to make sure it has the correct
2458 // animation info.
2459 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002460 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2461 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 sWindowSession.finishDrawing(mWindow);
2463 }
2464 } catch (RemoteException e) {
2465 }
2466 }
2467
2468 mSurface = null;
2469 }
2470 if (mAdded) {
2471 mAdded = false;
2472 if (immediate) {
2473 dispatchDetachedFromWindow();
2474 } else if (mView != null) {
2475 sendEmptyMessage(DIE);
2476 }
2477 }
2478 }
2479 }
2480
2481 public void dispatchFinishedEvent(int seq, boolean handled) {
2482 Message msg = obtainMessage(FINISHED_EVENT);
2483 msg.arg1 = seq;
2484 msg.arg2 = handled ? 1 : 0;
2485 sendMessage(msg);
2486 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 public void dispatchResized(int w, int h, Rect coveredInsets,
2489 Rect visibleInsets, boolean reportDraw) {
2490 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2491 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2492 + " visibleInsets=" + visibleInsets.toShortString()
2493 + " reportDraw=" + reportDraw);
2494 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002495 if (mTranslator != null) {
2496 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2497 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2498 w *= mTranslator.applicationInvertedScale;
2499 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002500 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002501 msg.arg1 = w;
2502 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2504 sendMessage(msg);
2505 }
2506
2507 public void dispatchKey(KeyEvent event) {
2508 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2509 //noinspection ConstantConditions
2510 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2511 if (Config.LOGD) Log.d("keydisp",
2512 "===================================================");
2513 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2514 debug();
2515
2516 if (Config.LOGD) Log.d("keydisp",
2517 "===================================================");
2518 }
2519 }
2520
2521 Message msg = obtainMessage(DISPATCH_KEY);
2522 msg.obj = event;
2523
2524 if (LOCAL_LOGV) Log.v(
2525 "ViewRoot", "sending key " + event + " to " + mView);
2526
2527 sendMessageAtTime(msg, event.getEventTime());
2528 }
2529
2530 public void dispatchPointer(MotionEvent event, long eventTime) {
2531 Message msg = obtainMessage(DISPATCH_POINTER);
2532 msg.obj = event;
2533 sendMessageAtTime(msg, eventTime);
2534 }
2535
2536 public void dispatchTrackball(MotionEvent event, long eventTime) {
2537 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2538 msg.obj = event;
2539 sendMessageAtTime(msg, eventTime);
2540 }
2541
2542 public void dispatchAppVisibility(boolean visible) {
2543 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2544 msg.arg1 = visible ? 1 : 0;
2545 sendMessage(msg);
2546 }
2547
2548 public void dispatchGetNewSurface() {
2549 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2550 sendMessage(msg);
2551 }
2552
2553 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2554 Message msg = Message.obtain();
2555 msg.what = WINDOW_FOCUS_CHANGED;
2556 msg.arg1 = hasFocus ? 1 : 0;
2557 msg.arg2 = inTouchMode ? 1 : 0;
2558 sendMessage(msg);
2559 }
2560
svetoslavganov75986cf2009-05-14 22:28:01 -07002561 /**
2562 * The window is getting focus so if there is anything focused/selected
2563 * send an {@link AccessibilityEvent} to announce that.
2564 */
2565 private void sendAccessibilityEvents() {
2566 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2567 return;
2568 }
2569 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2570 View focusedView = mView.findFocus();
2571 if (focusedView != null && focusedView != mView) {
2572 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2573 }
2574 }
2575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 public boolean showContextMenuForChild(View originalView) {
2577 return false;
2578 }
2579
2580 public void createContextMenu(ContextMenu menu) {
2581 }
2582
2583 public void childDrawableStateChanged(View child) {
2584 }
2585
2586 protected Rect getWindowFrame() {
2587 return mWinFrame;
2588 }
2589
2590 void checkThread() {
2591 if (mThread != Thread.currentThread()) {
2592 throw new CalledFromWrongThreadException(
2593 "Only the original thread that created a view hierarchy can touch its views.");
2594 }
2595 }
2596
2597 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2598 // ViewRoot never intercepts touch event, so this can be a no-op
2599 }
2600
2601 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2602 boolean immediate) {
2603 return scrollToRectOrFocus(rectangle, immediate);
2604 }
Romain Guy8506ab42009-06-11 17:35:47 -07002605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 static class InputMethodCallback extends IInputMethodCallback.Stub {
2607 private WeakReference<ViewRoot> mViewRoot;
2608
2609 public InputMethodCallback(ViewRoot viewRoot) {
2610 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2611 }
Romain Guy8506ab42009-06-11 17:35:47 -07002612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 public void finishedEvent(int seq, boolean handled) {
2614 final ViewRoot viewRoot = mViewRoot.get();
2615 if (viewRoot != null) {
2616 viewRoot.dispatchFinishedEvent(seq, handled);
2617 }
2618 }
2619
2620 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2621 // Stub -- not for use in the client.
2622 }
2623 }
Romain Guy8506ab42009-06-11 17:35:47 -07002624
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002625 static class EventCompletion extends Handler {
2626 final IWindow mWindow;
2627 final KeyEvent mKeyEvent;
2628 final boolean mIsPointer;
2629 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002630
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002631 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2632 boolean isPointer, MotionEvent motion) {
2633 super(looper);
2634 mWindow = window;
2635 mKeyEvent = key;
2636 mIsPointer = isPointer;
2637 mMotionEvent = motion;
2638 sendEmptyMessage(0);
2639 }
Romain Guy8506ab42009-06-11 17:35:47 -07002640
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002641 @Override
2642 public void handleMessage(Message msg) {
2643 if (mKeyEvent != null) {
2644 try {
2645 sWindowSession.finishKey(mWindow);
2646 } catch (RemoteException e) {
2647 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002648 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002649 boolean didFinish;
2650 MotionEvent event = mMotionEvent;
2651 if (event == null) {
2652 try {
2653 event = sWindowSession.getPendingPointerMove(mWindow);
2654 } catch (RemoteException e) {
2655 }
2656 didFinish = true;
2657 } else {
2658 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2659 }
2660 if (!didFinish) {
2661 try {
2662 sWindowSession.finishKey(mWindow);
2663 } catch (RemoteException e) {
2664 }
2665 }
2666 } else {
2667 MotionEvent event = mMotionEvent;
2668 if (event == null) {
2669 try {
2670 event = sWindowSession.getPendingTrackballMove(mWindow);
2671 } catch (RemoteException e) {
2672 }
2673 } else {
2674 try {
2675 sWindowSession.finishKey(mWindow);
2676 } catch (RemoteException e) {
2677 }
2678 }
2679 }
2680 }
2681 }
Romain Guy8506ab42009-06-11 17:35:47 -07002682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002684 private final WeakReference<ViewRoot> mViewRoot;
2685 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002687 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002689 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691
2692 public void resized(int w, int h, Rect coveredInsets,
2693 Rect visibleInsets, boolean reportDraw) {
2694 final ViewRoot viewRoot = mViewRoot.get();
2695 if (viewRoot != null) {
2696 viewRoot.dispatchResized(w, h, coveredInsets,
2697 visibleInsets, reportDraw);
2698 }
2699 }
2700
2701 public void dispatchKey(KeyEvent event) {
2702 final ViewRoot viewRoot = mViewRoot.get();
2703 if (viewRoot != null) {
2704 viewRoot.dispatchKey(event);
2705 } else {
2706 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002707 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 }
2709 }
2710
2711 public void dispatchPointer(MotionEvent event, long eventTime) {
2712 final ViewRoot viewRoot = mViewRoot.get();
2713 if (viewRoot != null) {
2714 viewRoot.dispatchPointer(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002715 } else {
2716 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 }
2718 }
2719
2720 public void dispatchTrackball(MotionEvent event, long eventTime) {
2721 final ViewRoot viewRoot = mViewRoot.get();
2722 if (viewRoot != null) {
2723 viewRoot.dispatchTrackball(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002724 } else {
2725 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 }
2727 }
2728
2729 public void dispatchAppVisibility(boolean visible) {
2730 final ViewRoot viewRoot = mViewRoot.get();
2731 if (viewRoot != null) {
2732 viewRoot.dispatchAppVisibility(visible);
2733 }
2734 }
2735
2736 public void dispatchGetNewSurface() {
2737 final ViewRoot viewRoot = mViewRoot.get();
2738 if (viewRoot != null) {
2739 viewRoot.dispatchGetNewSurface();
2740 }
2741 }
2742
2743 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2744 final ViewRoot viewRoot = mViewRoot.get();
2745 if (viewRoot != null) {
2746 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2747 }
2748 }
2749
2750 private static int checkCallingPermission(String permission) {
2751 if (!Process.supportsProcesses()) {
2752 return PackageManager.PERMISSION_GRANTED;
2753 }
2754
2755 try {
2756 return ActivityManagerNative.getDefault().checkPermission(
2757 permission, Binder.getCallingPid(), Binder.getCallingUid());
2758 } catch (RemoteException e) {
2759 return PackageManager.PERMISSION_DENIED;
2760 }
2761 }
2762
2763 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2764 final ViewRoot viewRoot = mViewRoot.get();
2765 if (viewRoot != null) {
2766 final View view = viewRoot.mView;
2767 if (view != null) {
2768 if (checkCallingPermission(Manifest.permission.DUMP) !=
2769 PackageManager.PERMISSION_GRANTED) {
2770 throw new SecurityException("Insufficient permissions to invoke"
2771 + " executeCommand() from pid=" + Binder.getCallingPid()
2772 + ", uid=" + Binder.getCallingUid());
2773 }
2774
2775 OutputStream clientStream = null;
2776 try {
2777 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2778 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2779 } catch (IOException e) {
2780 e.printStackTrace();
2781 } finally {
2782 if (clientStream != null) {
2783 try {
2784 clientStream.close();
2785 } catch (IOException e) {
2786 e.printStackTrace();
2787 }
2788 }
2789 }
2790 }
2791 }
2792 }
2793 }
2794
2795 /**
2796 * Maintains state information for a single trackball axis, generating
2797 * discrete (DPAD) movements based on raw trackball motion.
2798 */
2799 static final class TrackballAxis {
2800 /**
2801 * The maximum amount of acceleration we will apply.
2802 */
2803 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 /**
2806 * The maximum amount of time (in milliseconds) between events in order
2807 * for us to consider the user to be doing fast trackball movements,
2808 * and thus apply an acceleration.
2809 */
2810 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 /**
2813 * Scaling factor to the time (in milliseconds) between events to how
2814 * much to multiple/divide the current acceleration. When movement
2815 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2816 * FAST_MOVE_TIME it divides it.
2817 */
2818 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 float position;
2821 float absPosition;
2822 float acceleration = 1;
2823 long lastMoveTime = 0;
2824 int step;
2825 int dir;
2826 int nonAccelMovement;
2827
2828 void reset(int _step) {
2829 position = 0;
2830 acceleration = 1;
2831 lastMoveTime = 0;
2832 step = _step;
2833 dir = 0;
2834 }
2835
2836 /**
2837 * Add trackball movement into the state. If the direction of movement
2838 * has been reversed, the state is reset before adding the
2839 * movement (so that you don't have to compensate for any previously
2840 * collected movement before see the result of the movement in the
2841 * new direction).
2842 *
2843 * @return Returns the absolute value of the amount of movement
2844 * collected so far.
2845 */
2846 float collect(float off, long time, String axis) {
2847 long normTime;
2848 if (off > 0) {
2849 normTime = (long)(off * FAST_MOVE_TIME);
2850 if (dir < 0) {
2851 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2852 position = 0;
2853 step = 0;
2854 acceleration = 1;
2855 lastMoveTime = 0;
2856 }
2857 dir = 1;
2858 } else if (off < 0) {
2859 normTime = (long)((-off) * FAST_MOVE_TIME);
2860 if (dir > 0) {
2861 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2862 position = 0;
2863 step = 0;
2864 acceleration = 1;
2865 lastMoveTime = 0;
2866 }
2867 dir = -1;
2868 } else {
2869 normTime = 0;
2870 }
Romain Guy8506ab42009-06-11 17:35:47 -07002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 // The number of milliseconds between each movement that is
2873 // considered "normal" and will not result in any acceleration
2874 // or deceleration, scaled by the offset we have here.
2875 if (normTime > 0) {
2876 long delta = time - lastMoveTime;
2877 lastMoveTime = time;
2878 float acc = acceleration;
2879 if (delta < normTime) {
2880 // The user is scrolling rapidly, so increase acceleration.
2881 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2882 if (scale > 1) acc *= scale;
2883 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2884 + off + " normTime=" + normTime + " delta=" + delta
2885 + " scale=" + scale + " acc=" + acc);
2886 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2887 } else {
2888 // The user is scrolling slowly, so decrease acceleration.
2889 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
2890 if (scale > 1) acc /= scale;
2891 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
2892 + off + " normTime=" + normTime + " delta=" + delta
2893 + " scale=" + scale + " acc=" + acc);
2894 acceleration = acc > 1 ? acc : 1;
2895 }
2896 }
2897 position += off;
2898 return (absPosition = Math.abs(position));
2899 }
2900
2901 /**
2902 * Generate the number of discrete movement events appropriate for
2903 * the currently collected trackball movement.
2904 *
2905 * @param precision The minimum movement required to generate the
2906 * first discrete movement.
2907 *
2908 * @return Returns the number of discrete movements, either positive
2909 * or negative, or 0 if there is not enough trackball movement yet
2910 * for a discrete movement.
2911 */
2912 int generate(float precision) {
2913 int movement = 0;
2914 nonAccelMovement = 0;
2915 do {
2916 final int dir = position >= 0 ? 1 : -1;
2917 switch (step) {
2918 // If we are going to execute the first step, then we want
2919 // to do this as soon as possible instead of waiting for
2920 // a full movement, in order to make things look responsive.
2921 case 0:
2922 if (absPosition < precision) {
2923 return movement;
2924 }
2925 movement += dir;
2926 nonAccelMovement += dir;
2927 step = 1;
2928 break;
2929 // If we have generated the first movement, then we need
2930 // to wait for the second complete trackball motion before
2931 // generating the second discrete movement.
2932 case 1:
2933 if (absPosition < 2) {
2934 return movement;
2935 }
2936 movement += dir;
2937 nonAccelMovement += dir;
2938 position += dir > 0 ? -2 : 2;
2939 absPosition = Math.abs(position);
2940 step = 2;
2941 break;
2942 // After the first two, we generate discrete movements
2943 // consistently with the trackball, applying an acceleration
2944 // if the trackball is moving quickly. This is a simple
2945 // acceleration on top of what we already compute based
2946 // on how quickly the wheel is being turned, to apply
2947 // a longer increasing acceleration to continuous movement
2948 // in one direction.
2949 default:
2950 if (absPosition < 1) {
2951 return movement;
2952 }
2953 movement += dir;
2954 position += dir >= 0 ? -1 : 1;
2955 absPosition = Math.abs(position);
2956 float acc = acceleration;
2957 acc *= 1.1f;
2958 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
2959 break;
2960 }
2961 } while (true);
2962 }
2963 }
2964
2965 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
2966 public CalledFromWrongThreadException(String msg) {
2967 super(msg);
2968 }
2969 }
2970
2971 private SurfaceHolder mHolder = new SurfaceHolder() {
2972 // we only need a SurfaceHolder for opengl. it would be nice
2973 // to implement everything else though, especially the callback
2974 // support (opengl doesn't make use of it right now, but eventually
2975 // will).
2976 public Surface getSurface() {
2977 return mSurface;
2978 }
2979
2980 public boolean isCreating() {
2981 return false;
2982 }
2983
2984 public void addCallback(Callback callback) {
2985 }
2986
2987 public void removeCallback(Callback callback) {
2988 }
2989
2990 public void setFixedSize(int width, int height) {
2991 }
2992
2993 public void setSizeFromLayout() {
2994 }
2995
2996 public void setFormat(int format) {
2997 }
2998
2999 public void setType(int type) {
3000 }
3001
3002 public void setKeepScreenOn(boolean screenOn) {
3003 }
3004
3005 public Canvas lockCanvas() {
3006 return null;
3007 }
3008
3009 public Canvas lockCanvas(Rect dirty) {
3010 return null;
3011 }
3012
3013 public void unlockCanvasAndPost(Canvas canvas) {
3014 }
3015 public Rect getSurfaceFrame() {
3016 return null;
3017 }
3018 };
3019
3020 static RunQueue getRunQueue() {
3021 RunQueue rq = sRunQueues.get();
3022 if (rq != null) {
3023 return rq;
3024 }
3025 rq = new RunQueue();
3026 sRunQueues.set(rq);
3027 return rq;
3028 }
Romain Guy8506ab42009-06-11 17:35:47 -07003029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 /**
3031 * @hide
3032 */
3033 static final class RunQueue {
3034 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3035
3036 void post(Runnable action) {
3037 postDelayed(action, 0);
3038 }
3039
3040 void postDelayed(Runnable action, long delayMillis) {
3041 HandlerAction handlerAction = new HandlerAction();
3042 handlerAction.action = action;
3043 handlerAction.delay = delayMillis;
3044
3045 synchronized (mActions) {
3046 mActions.add(handlerAction);
3047 }
3048 }
3049
3050 void removeCallbacks(Runnable action) {
3051 final HandlerAction handlerAction = new HandlerAction();
3052 handlerAction.action = action;
3053
3054 synchronized (mActions) {
3055 final ArrayList<HandlerAction> actions = mActions;
3056
3057 while (actions.remove(handlerAction)) {
3058 // Keep going
3059 }
3060 }
3061 }
3062
3063 void executeActions(Handler handler) {
3064 synchronized (mActions) {
3065 final ArrayList<HandlerAction> actions = mActions;
3066 final int count = actions.size();
3067
3068 for (int i = 0; i < count; i++) {
3069 final HandlerAction handlerAction = actions.get(i);
3070 handler.postDelayed(handlerAction.action, handlerAction.delay);
3071 }
3072
3073 mActions.clear();
3074 }
3075 }
3076
3077 private static class HandlerAction {
3078 Runnable action;
3079 long delay;
3080
3081 @Override
3082 public boolean equals(Object o) {
3083 if (this == o) return true;
3084 if (o == null || getClass() != o.getClass()) return false;
3085
3086 HandlerAction that = (HandlerAction) o;
3087
3088 return !(action != null ? !action.equals(that.action) : that.action != null);
3089
3090 }
3091
3092 @Override
3093 public int hashCode() {
3094 int result = action != null ? action.hashCode() : 0;
3095 result = 31 * result + (int) (delay ^ (delay >>> 32));
3096 return result;
3097 }
3098 }
3099 }
3100
3101 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3102
3103 // inform skia to just abandon its texture cache IDs
3104 // doesn't call glDeleteTextures
3105 private static native void nativeAbandonGlCaches();
3106}