blob: 6f6e22477d2575020c0746e53a7b5c82f6824b98 [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);
Romain Guy1e095972009-07-07 11:22:45 -0700549 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700550 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700551 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700552 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700553 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700554 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700555 }
Romain Guy1e095972009-07-07 11:22:45 -0700556 if (mAttachInfo.mScalingRequired) {
557 dirty.inset(-1, -1);
558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
560 mDirty.union(dirty);
561 if (!mWillDrawSoon) {
562 scheduleTraversals();
563 }
564 }
565
566 public ViewParent getParent() {
567 return null;
568 }
569
570 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
571 invalidateChild(null, dirty);
572 return null;
573 }
574
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700575 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 if (child != mView) {
577 throw new RuntimeException("child is not mine, honest!");
578 }
579 // Note: don't apply scroll offset, because we want to know its
580 // visibility in the virtual canvas being given to the view hierarchy.
581 return r.intersect(0, 0, mWidth, mHeight);
582 }
583
584 public void bringChildToFront(View child) {
585 }
586
587 public void scheduleTraversals() {
588 if (!mTraversalScheduled) {
589 mTraversalScheduled = true;
590 sendEmptyMessage(DO_TRAVERSAL);
591 }
592 }
593
594 public void unscheduleTraversals() {
595 if (mTraversalScheduled) {
596 mTraversalScheduled = false;
597 removeMessages(DO_TRAVERSAL);
598 }
599 }
600
601 int getHostVisibility() {
602 return mAppVisible ? mView.getVisibility() : View.GONE;
603 }
Romain Guy8506ab42009-06-11 17:35:47 -0700604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 private void performTraversals() {
606 // cache mView since it is used so much below...
607 final View host = mView;
608
609 if (DBG) {
610 System.out.println("======================================");
611 System.out.println("performTraversals");
612 host.debug();
613 }
614
615 if (host == null || !mAdded)
616 return;
617
618 mTraversalScheduled = false;
619 mWillDrawSoon = true;
620 boolean windowResizesToFitContent = false;
621 boolean fullRedrawNeeded = mFullRedrawNeeded;
622 boolean newSurface = false;
623 WindowManager.LayoutParams lp = mWindowAttributes;
624
625 int desiredWindowWidth;
626 int desiredWindowHeight;
627 int childWidthMeasureSpec;
628 int childHeightMeasureSpec;
629
630 final View.AttachInfo attachInfo = mAttachInfo;
631
632 final int viewVisibility = getHostVisibility();
633 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
634 || mNewSurfaceNeeded;
635
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700636 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 WindowManager.LayoutParams params = null;
639 if (mWindowAttributesChanged) {
640 mWindowAttributesChanged = false;
641 params = lp;
642 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700643 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 if (mFirst) {
645 fullRedrawNeeded = true;
646 mLayoutRequested = true;
647
Romain Guy8506ab42009-06-11 17:35:47 -0700648 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700649 mView.getContext().getResources().getDisplayMetrics();
650 desiredWindowWidth = packageMetrics.widthPixels;
651 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652
653 // For the very first time, tell the view hierarchy that it
654 // is attached to the window. Note that at this point the surface
655 // object is not initialized to its backing store, but soon it
656 // will be (assuming the window is visible).
657 attachInfo.mSurface = mSurface;
658 attachInfo.mHasWindowFocus = false;
659 attachInfo.mWindowVisibility = viewVisibility;
660 attachInfo.mRecomputeGlobalAttributes = false;
661 attachInfo.mKeepScreenOn = false;
662 viewVisibilityChanged = false;
663 host.dispatchAttachedToWindow(attachInfo, 0);
664 getRunQueue().executeActions(attachInfo.mHandler);
665 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700668 desiredWindowWidth = frame.width();
669 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
671 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700672 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 fullRedrawNeeded = true;
674 mLayoutRequested = true;
675 windowResizesToFitContent = true;
676 }
677 }
678
679 if (viewVisibilityChanged) {
680 attachInfo.mWindowVisibility = viewVisibility;
681 host.dispatchWindowVisibilityChanged(viewVisibility);
682 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
683 if (mUseGL) {
684 destroyGL();
685 }
686 }
687 if (viewVisibility == View.GONE) {
688 // After making a window gone, we will count it as being
689 // shown for the first time the next time it gets focus.
690 mHasHadWindowFocus = false;
691 }
692 }
693
694 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (mLayoutRequested) {
697 if (mFirst) {
698 host.fitSystemWindows(mAttachInfo.mContentInsets);
699 // make sure touch mode code executes by setting cached value
700 // to opposite of the added touch mode.
701 mAttachInfo.mInTouchMode = !mAddedTouchMode;
702 ensureTouchModeLocally(mAddedTouchMode);
703 } else {
704 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
705 mAttachInfo.mContentInsets.set(mPendingContentInsets);
706 host.fitSystemWindows(mAttachInfo.mContentInsets);
707 insetsChanged = true;
708 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
709 + mAttachInfo.mContentInsets);
710 }
711 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
712 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
713 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
714 + mAttachInfo.mVisibleInsets);
715 }
716 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
717 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
718 windowResizesToFitContent = true;
719
Romain Guy8506ab42009-06-11 17:35:47 -0700720 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700721 mView.getContext().getResources().getDisplayMetrics();
722 desiredWindowWidth = packageMetrics.widthPixels;
723 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
725 }
726
727 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
728 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
729
730 // Ask host how big it wants to be
731 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
732 "Measuring " + host + " in display " + desiredWindowWidth
733 + "x" + desiredWindowHeight + "...");
734 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
735
736 if (DBG) {
737 System.out.println("======================================");
738 System.out.println("performTraversals -- after measure");
739 host.debug();
740 }
741 }
742
743 if (attachInfo.mRecomputeGlobalAttributes) {
744 //Log.i(TAG, "Computing screen on!");
745 attachInfo.mRecomputeGlobalAttributes = false;
746 boolean oldVal = attachInfo.mKeepScreenOn;
747 attachInfo.mKeepScreenOn = false;
748 host.dispatchCollectViewAttributes(0);
749 if (attachInfo.mKeepScreenOn != oldVal) {
750 params = lp;
751 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
752 }
753 }
754
755 if (mFirst || attachInfo.mViewVisibilityChanged) {
756 attachInfo.mViewVisibilityChanged = false;
757 int resizeMode = mSoftInputMode &
758 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
759 // If we are in auto resize mode, then we need to determine
760 // what mode to use now.
761 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
762 final int N = attachInfo.mScrollContainers.size();
763 for (int i=0; i<N; i++) {
764 if (attachInfo.mScrollContainers.get(i).isShown()) {
765 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
766 }
767 }
768 if (resizeMode == 0) {
769 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
770 }
771 if ((lp.softInputMode &
772 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
773 lp.softInputMode = (lp.softInputMode &
774 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
775 resizeMode;
776 params = lp;
777 }
778 }
779 }
Romain Guy8506ab42009-06-11 17:35:47 -0700780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
782 if (!PixelFormat.formatHasAlpha(params.format)) {
783 params.format = PixelFormat.TRANSLUCENT;
784 }
785 }
786
787 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
788 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
789
790 final boolean computesInternalInsets =
791 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
792 boolean insetsPending = false;
793 int relayoutResult = 0;
794 if (mFirst || windowShouldResize || insetsChanged
795 || viewVisibilityChanged || params != null) {
796
797 if (viewVisibility == View.VISIBLE) {
798 // If this window is giving internal insets to the window
799 // manager, and it is being added or changing its visibility,
800 // then we want to first give the window manager "fake"
801 // insets to cause it to effectively ignore the content of
802 // the window during layout. This avoids it briefly causing
803 // other windows to resize/move based on the raw frame of the
804 // window, waiting until we can finish laying out this window
805 // and get back to the window manager with the ultimately
806 // computed insets.
807 insetsPending = computesInternalInsets
808 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
811 if (params == null) {
812 params = mWindowAttributes;
813 }
814 mGlWanted = true;
815 }
816 }
817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 boolean initialized = false;
819 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700820 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 try {
822 boolean hadSurface = mSurface.isValid();
823 int fl = 0;
824 if (params != null) {
825 fl = params.flags;
826 if (attachInfo.mKeepScreenOn) {
827 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
828 }
829 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700830 if (DEBUG_LAYOUT) {
831 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
832 host.mMeasuredHeight + ", params=" + params);
833 }
834 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 if (params != null) {
837 params.flags = fl;
838 }
839
840 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
841 + " content=" + mPendingContentInsets.toShortString()
842 + " visible=" + mPendingVisibleInsets.toShortString()
843 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 contentInsetsChanged = !mPendingContentInsets.equals(
846 mAttachInfo.mContentInsets);
847 visibleInsetsChanged = !mPendingVisibleInsets.equals(
848 mAttachInfo.mVisibleInsets);
849 if (contentInsetsChanged) {
850 mAttachInfo.mContentInsets.set(mPendingContentInsets);
851 host.fitSystemWindows(mAttachInfo.mContentInsets);
852 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
853 + mAttachInfo.mContentInsets);
854 }
855 if (visibleInsetsChanged) {
856 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
857 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
858 + mAttachInfo.mVisibleInsets);
859 }
860
861 if (!hadSurface) {
862 if (mSurface.isValid()) {
863 // If we are creating a new surface, then we need to
864 // completely redraw it. Also, when we get to the
865 // point of drawing it we will hold off and schedule
866 // a new traversal instead. This is so we can tell the
867 // window manager about all of the windows being displayed
868 // before actually drawing them, so it can display then
869 // all at once.
870 newSurface = true;
871 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 if (mGlWanted && !mUseGL) {
874 initializeGL();
875 initialized = mGlCanvas != null;
876 }
877 }
878 } else if (!mSurface.isValid()) {
879 // If the surface has been removed, then reset the scroll
880 // positions.
881 mLastScrolledFocus = null;
882 mScrollY = mCurScrollY = 0;
883 if (mScroller != null) {
884 mScroller.abortAnimation();
885 }
886 }
887 } catch (RemoteException e) {
888 }
889 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700890 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891
892 attachInfo.mWindowLeft = frame.left;
893 attachInfo.mWindowTop = frame.top;
894
895 // !!FIXME!! This next section handles the case where we did not get the
896 // window size we asked for. We should avoid this by getting a maximum size from
897 // the window session beforehand.
898 mWidth = frame.width();
899 mHeight = frame.height();
900
901 if (initialized) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700902 mGlCanvas.setViewport((int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904
905 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
906 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
907 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
908 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
909 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
910 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
911
912 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
913 + mWidth + " measuredWidth=" + host.mMeasuredWidth
914 + " mHeight=" + mHeight
915 + " measuredHeight" + host.mMeasuredHeight
916 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 // Ask host how big it wants to be
919 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
920
921 // Implementation of weights from WindowManager.LayoutParams
922 // We just grow the dimensions as needed and re-measure if
923 // needs be
924 int width = host.mMeasuredWidth;
925 int height = host.mMeasuredHeight;
926 boolean measureAgain = false;
927
928 if (lp.horizontalWeight > 0.0f) {
929 width += (int) ((mWidth - width) * lp.horizontalWeight);
930 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
931 MeasureSpec.EXACTLY);
932 measureAgain = true;
933 }
934 if (lp.verticalWeight > 0.0f) {
935 height += (int) ((mHeight - height) * lp.verticalWeight);
936 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
937 MeasureSpec.EXACTLY);
938 measureAgain = true;
939 }
940
941 if (measureAgain) {
942 if (DEBUG_LAYOUT) Log.v(TAG,
943 "And hey let's measure once more: width=" + width
944 + " height=" + height);
945 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
946 }
947
948 mLayoutRequested = true;
949 }
950 }
951
952 final boolean didLayout = mLayoutRequested;
953 boolean triggerGlobalLayoutListener = didLayout
954 || attachInfo.mRecomputeGlobalAttributes;
955 if (didLayout) {
956 mLayoutRequested = false;
957 mScrollMayChange = true;
958 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
959 "ViewRoot", "Laying out " + host + " to (" +
960 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700961 long startTime = 0L;
962 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 startTime = SystemClock.elapsedRealtime();
964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
966
Romain Guy13922e02009-05-12 17:56:14 -0700967 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
968 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
969 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
970 + "please refer to the logs with the tag "
971 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
972 }
973 }
974
975 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
977 }
978
979 // By this point all views have been sized and positionned
980 // We can compute the transparent area
981
982 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
983 // start out transparent
984 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
985 host.getLocationInWindow(mTmpLocation);
986 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
987 mTmpLocation[0] + host.mRight - host.mLeft,
988 mTmpLocation[1] + host.mBottom - host.mTop);
989
990 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700991 if (mTranslator != null) {
992 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
993 }
994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
996 mPreviousTransparentRegion.set(mTransparentRegion);
997 // reconfigure window manager
998 try {
999 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1000 } catch (RemoteException e) {
1001 }
1002 }
1003 }
1004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 if (DBG) {
1006 System.out.println("======================================");
1007 System.out.println("performTraversals -- after setFrame");
1008 host.debug();
1009 }
1010 }
1011
1012 if (triggerGlobalLayoutListener) {
1013 attachInfo.mRecomputeGlobalAttributes = false;
1014 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1015 }
1016
1017 if (computesInternalInsets) {
1018 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1019 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1020 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1021 givenContent.left = givenContent.top = givenContent.right
1022 = givenContent.bottom = givenVisible.left = givenVisible.top
1023 = givenVisible.right = givenVisible.bottom = 0;
1024 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001025 Rect contentInsets = insets.contentInsets;
1026 Rect visibleInsets = insets.visibleInsets;
1027 if (mTranslator != null) {
1028 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1029 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1032 mLastGivenInsets.set(insets);
1033 try {
1034 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001035 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 } catch (RemoteException e) {
1037 }
1038 }
1039 }
Romain Guy8506ab42009-06-11 17:35:47 -07001040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 if (mFirst) {
1042 // handle first focus request
1043 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1044 + mView.hasFocus());
1045 if (mView != null) {
1046 if (!mView.hasFocus()) {
1047 mView.requestFocus(View.FOCUS_FORWARD);
1048 mFocusedView = mRealFocusedView = mView.findFocus();
1049 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1050 + mFocusedView);
1051 } else {
1052 mRealFocusedView = mView.findFocus();
1053 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1054 + mRealFocusedView);
1055 }
1056 }
1057 }
1058
1059 mFirst = false;
1060 mWillDrawSoon = false;
1061 mNewSurfaceNeeded = false;
1062 mViewVisibility = viewVisibility;
1063
1064 if (mAttachInfo.mHasWindowFocus) {
1065 final boolean imTarget = WindowManager.LayoutParams
1066 .mayUseInputMethod(mWindowAttributes.flags);
1067 if (imTarget != mLastWasImTarget) {
1068 mLastWasImTarget = imTarget;
1069 InputMethodManager imm = InputMethodManager.peekInstance();
1070 if (imm != null && imTarget) {
1071 imm.startGettingWindowFocus(mView);
1072 imm.onWindowFocus(mView, mView.findFocus(),
1073 mWindowAttributes.softInputMode,
1074 !mHasHadWindowFocus, mWindowAttributes.flags);
1075 }
1076 }
1077 }
Romain Guy8506ab42009-06-11 17:35:47 -07001078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1080
1081 if (!cancelDraw && !newSurface) {
1082 mFullRedrawNeeded = false;
1083 draw(fullRedrawNeeded);
1084
1085 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1086 || mReportNextDraw) {
1087 if (LOCAL_LOGV) {
1088 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1089 }
1090 mReportNextDraw = false;
1091 try {
1092 sWindowSession.finishDrawing(mWindow);
1093 } catch (RemoteException e) {
1094 }
1095 }
1096 } else {
1097 // We were supposed to report when we are done drawing. Since we canceled the
1098 // draw, remember it here.
1099 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1100 mReportNextDraw = true;
1101 }
1102 if (fullRedrawNeeded) {
1103 mFullRedrawNeeded = true;
1104 }
1105 // Try again
1106 scheduleTraversals();
1107 }
1108 }
1109
1110 public void requestTransparentRegion(View child) {
1111 // the test below should not fail unless someone is messing with us
1112 checkThread();
1113 if (mView == child) {
1114 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1115 // Need to make sure we re-evaluate the window attributes next
1116 // time around, to ensure the window has the correct format.
1117 mWindowAttributesChanged = true;
1118 }
1119 }
1120
1121 /**
1122 * Figures out the measure spec for the root view in a window based on it's
1123 * layout params.
1124 *
1125 * @param windowSize
1126 * The available width or height of the window
1127 *
1128 * @param rootDimension
1129 * The layout params for one dimension (width or height) of the
1130 * window.
1131 *
1132 * @return The measure spec to use to measure the root view.
1133 */
1134 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1135 int measureSpec;
1136 switch (rootDimension) {
1137
1138 case ViewGroup.LayoutParams.FILL_PARENT:
1139 // Window can't resize. Force root view to be windowSize.
1140 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1141 break;
1142 case ViewGroup.LayoutParams.WRAP_CONTENT:
1143 // Window can resize. Set max size for root view.
1144 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1145 break;
1146 default:
1147 // Window wants to be an exact size. Force root view to be that size.
1148 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1149 break;
1150 }
1151 return measureSpec;
1152 }
1153
1154 private void draw(boolean fullRedrawNeeded) {
1155 Surface surface = mSurface;
1156 if (surface == null || !surface.isValid()) {
1157 return;
1158 }
1159
1160 scrollToRectOrFocus(null, false);
1161
1162 if (mAttachInfo.mViewScrollChanged) {
1163 mAttachInfo.mViewScrollChanged = false;
1164 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1165 }
Romain Guy8506ab42009-06-11 17:35:47 -07001166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001168 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 if (scrolling) {
1170 yoff = mScroller.getCurrY();
1171 } else {
1172 yoff = mScrollY;
1173 }
1174 if (mCurScrollY != yoff) {
1175 mCurScrollY = yoff;
1176 fullRedrawNeeded = true;
1177 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001178 float appScale = mAttachInfo.mApplicationScale;
1179 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180
1181 Rect dirty = mDirty;
1182 if (mUseGL) {
1183 if (!dirty.isEmpty()) {
1184 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001185 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 mGL.glDisable(GL_SCISSOR_TEST);
1187 mGL.glClearColor(0, 0, 0, 0);
1188 mGL.glClear(GL_COLOR_BUFFER_BIT);
1189 mGL.glEnable(GL_SCISSOR_TEST);
1190
1191 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001192 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001194
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001195 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1196 try {
1197 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001198 if (mTranslator != null) {
1199 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001200 }
1201 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001202 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1203 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1204 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001205 } finally {
1206 canvas.restoreToCount(saveCount);
1207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208
Romain Guy5bcdff42009-05-14 21:27:18 -07001209 mAttachInfo.mIgnoreDirtyState = false;
1210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1212 checkEglErrors();
1213
Romain Guy13922e02009-05-12 17:56:14 -07001214 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 int now = (int)SystemClock.elapsedRealtime();
1216 if (sDrawTime != 0) {
1217 nativeShowFPS(canvas, now - sDrawTime);
1218 }
1219 sDrawTime = now;
1220 }
1221 }
1222 }
1223 if (scrolling) {
1224 mFullRedrawNeeded = true;
1225 scheduleTraversals();
1226 }
1227 return;
1228 }
1229
Romain Guy5bcdff42009-05-14 21:27:18 -07001230 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001231 mAttachInfo.mIgnoreDirtyState = true;
1232 dirty.union(0, 0, (int) (mWidth * appScale), (int) (mHeight * appScale));
Romain Guy5bcdff42009-05-14 21:27:18 -07001233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234
1235 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1236 Log.v("ViewRoot", "Draw " + mView + "/"
1237 + mWindowAttributes.getTitle()
1238 + ": dirty={" + dirty.left + "," + dirty.top
1239 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001240 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1241 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
1243
1244 Canvas canvas;
1245 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001246 int left = dirty.left;
1247 int top = dirty.top;
1248 int right = dirty.right;
1249 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001251
1252 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1253 bottom != dirty.bottom) {
1254 mAttachInfo.mIgnoreDirtyState = true;
1255 }
1256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 // TODO: Do this in native
1258 canvas.setDensityScale(mDensity);
1259 } catch (Surface.OutOfResourcesException e) {
1260 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1261 // TODO: we should ask the window manager to do something!
1262 // for now we just do nothing
1263 return;
1264 }
1265
1266 try {
Romain Guybb93d552009-03-24 21:04:15 -07001267 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001268 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269
1270 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1271 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1272 + canvas.getWidth() + ", h=" + canvas.getHeight());
1273 //canvas.drawARGB(255, 255, 0, 0);
1274 }
1275
Romain Guy13922e02009-05-12 17:56:14 -07001276 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 startTime = SystemClock.elapsedRealtime();
1278 }
1279
1280 // If this bitmap's format includes an alpha channel, we
1281 // need to clear it before drawing so that the child will
1282 // properly re-composite its drawing on a transparent
1283 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001284 // or
1285 // If we are applying an offset, we need to clear the area
1286 // where the offset doesn't appear to avoid having garbage
1287 // left in the blank areas.
1288 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1290 }
1291
1292 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001293 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001295 mView.mPrivateFlags |= View.DRAWN;
1296
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001297 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001298 Context cxt = mView.getContext();
1299 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001300 ", metrics=" + mView.getContext().getResources().getDisplayMetrics());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001301 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001302 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001303 try {
1304 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001305 if (mTranslator != null) {
1306 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001307 }
1308 mView.draw(canvas);
1309 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001310 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001311 canvas.restoreToCount(saveCount);
1312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313
Romain Guy5bcdff42009-05-14 21:27:18 -07001314 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1315 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1316 }
1317
Romain Guy13922e02009-05-12 17:56:14 -07001318 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 int now = (int)SystemClock.elapsedRealtime();
1320 if (sDrawTime != 0) {
1321 nativeShowFPS(canvas, now - sDrawTime);
1322 }
1323 sDrawTime = now;
1324 }
1325
Romain Guy13922e02009-05-12 17:56:14 -07001326 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1328 }
1329 }
Romain Guy8506ab42009-06-11 17:35:47 -07001330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 } finally {
1332 surface.unlockCanvasAndPost(canvas);
1333 }
1334
1335 if (LOCAL_LOGV) {
1336 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1337 }
Romain Guy8506ab42009-06-11 17:35:47 -07001338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 if (scrolling) {
1340 mFullRedrawNeeded = true;
1341 scheduleTraversals();
1342 }
1343 }
1344
1345 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1346 final View.AttachInfo attachInfo = mAttachInfo;
1347 final Rect ci = attachInfo.mContentInsets;
1348 final Rect vi = attachInfo.mVisibleInsets;
1349 int scrollY = 0;
1350 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 if (vi.left > ci.left || vi.top > ci.top
1353 || vi.right > ci.right || vi.bottom > ci.bottom) {
1354 // We'll assume that we aren't going to change the scroll
1355 // offset, since we want to avoid that unless it is actually
1356 // going to make the focus visible... otherwise we scroll
1357 // all over the place.
1358 scrollY = mScrollY;
1359 // We can be called for two different situations: during a draw,
1360 // to update the scroll position if the focus has changed (in which
1361 // case 'rectangle' is null), or in response to a
1362 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1363 // is non-null and we just want to scroll to whatever that
1364 // rectangle is).
1365 View focus = mRealFocusedView;
1366 if (focus != mLastScrolledFocus) {
1367 // If the focus has changed, then ignore any requests to scroll
1368 // to a rectangle; first we want to make sure the entire focus
1369 // view is visible.
1370 rectangle = null;
1371 }
1372 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1373 + " rectangle=" + rectangle + " ci=" + ci
1374 + " vi=" + vi);
1375 if (focus == mLastScrolledFocus && !mScrollMayChange
1376 && rectangle == null) {
1377 // Optimization: if the focus hasn't changed since last
1378 // time, and no layout has happened, then just leave things
1379 // as they are.
1380 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1381 + mScrollY + " vi=" + vi.toShortString());
1382 } else if (focus != null) {
1383 // We need to determine if the currently focused view is
1384 // within the visible part of the window and, if not, apply
1385 // a pan so it can be seen.
1386 mLastScrolledFocus = focus;
1387 mScrollMayChange = false;
1388 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1389 // Try to find the rectangle from the focus view.
1390 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1391 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1392 + mView.getWidth() + " h=" + mView.getHeight()
1393 + " ci=" + ci.toShortString()
1394 + " vi=" + vi.toShortString());
1395 if (rectangle == null) {
1396 focus.getFocusedRect(mTempRect);
1397 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1398 + ": focusRect=" + mTempRect.toShortString());
1399 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1400 focus, mTempRect);
1401 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1402 "Focus in window: focusRect="
1403 + mTempRect.toShortString()
1404 + " visRect=" + mVisRect.toShortString());
1405 } else {
1406 mTempRect.set(rectangle);
1407 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1408 "Request scroll to rect: "
1409 + mTempRect.toShortString()
1410 + " visRect=" + mVisRect.toShortString());
1411 }
1412 if (mTempRect.intersect(mVisRect)) {
1413 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1414 "Focus window visible rect: "
1415 + mTempRect.toShortString());
1416 if (mTempRect.height() >
1417 (mView.getHeight()-vi.top-vi.bottom)) {
1418 // If the focus simply is not going to fit, then
1419 // best is probably just to leave things as-is.
1420 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1421 "Too tall; leaving scrollY=" + scrollY);
1422 } else if ((mTempRect.top-scrollY) < vi.top) {
1423 scrollY -= vi.top - (mTempRect.top-scrollY);
1424 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1425 "Top covered; scrollY=" + scrollY);
1426 } else if ((mTempRect.bottom-scrollY)
1427 > (mView.getHeight()-vi.bottom)) {
1428 scrollY += (mTempRect.bottom-scrollY)
1429 - (mView.getHeight()-vi.bottom);
1430 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1431 "Bottom covered; scrollY=" + scrollY);
1432 }
1433 handled = true;
1434 }
1435 }
1436 }
1437 }
Romain Guy8506ab42009-06-11 17:35:47 -07001438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 if (scrollY != mScrollY) {
1440 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1441 + mScrollY + " , new=" + scrollY);
1442 if (!immediate) {
1443 if (mScroller == null) {
1444 mScroller = new Scroller(mView.getContext());
1445 }
1446 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1447 } else if (mScroller != null) {
1448 mScroller.abortAnimation();
1449 }
1450 mScrollY = scrollY;
1451 }
Romain Guy8506ab42009-06-11 17:35:47 -07001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 return handled;
1454 }
Romain Guy8506ab42009-06-11 17:35:47 -07001455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 public void requestChildFocus(View child, View focused) {
1457 checkThread();
1458 if (mFocusedView != focused) {
1459 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1460 scheduleTraversals();
1461 }
1462 mFocusedView = mRealFocusedView = focused;
1463 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1464 + mFocusedView);
1465 }
1466
1467 public void clearChildFocus(View child) {
1468 checkThread();
1469
1470 View oldFocus = mFocusedView;
1471
1472 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1473 mFocusedView = mRealFocusedView = null;
1474 if (mView != null && !mView.hasFocus()) {
1475 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1476 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1477 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1478 }
1479 } else if (oldFocus != null) {
1480 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1481 }
1482 }
1483
1484
1485 public void focusableViewAvailable(View v) {
1486 checkThread();
1487
1488 if (mView != null && !mView.hasFocus()) {
1489 v.requestFocus();
1490 } else {
1491 // the one case where will transfer focus away from the current one
1492 // is if the current view is a view group that prefers to give focus
1493 // to its children first AND the view is a descendant of it.
1494 mFocusedView = mView.findFocus();
1495 boolean descendantsHaveDibsOnFocus =
1496 (mFocusedView instanceof ViewGroup) &&
1497 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1498 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1499 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1500 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1501 v.requestFocus();
1502 }
1503 }
1504 }
1505
1506 public void recomputeViewAttributes(View child) {
1507 checkThread();
1508 if (mView == child) {
1509 mAttachInfo.mRecomputeGlobalAttributes = true;
1510 if (!mWillDrawSoon) {
1511 scheduleTraversals();
1512 }
1513 }
1514 }
1515
1516 void dispatchDetachedFromWindow() {
1517 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1518
1519 if (mView != null) {
1520 mView.dispatchDetachedFromWindow();
1521 }
1522
1523 mView = null;
1524 mAttachInfo.mRootView = null;
1525
1526 if (mUseGL) {
1527 destroyGL();
1528 }
1529
1530 try {
1531 sWindowSession.remove(mWindow);
1532 } catch (RemoteException e) {
1533 }
1534 }
Romain Guy8506ab42009-06-11 17:35:47 -07001535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 /**
1537 * Return true if child is an ancestor of parent, (or equal to the parent).
1538 */
1539 private static boolean isViewDescendantOf(View child, View parent) {
1540 if (child == parent) {
1541 return true;
1542 }
1543
1544 final ViewParent theParent = child.getParent();
1545 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1546 }
1547
1548
1549 public final static int DO_TRAVERSAL = 1000;
1550 public final static int DIE = 1001;
1551 public final static int RESIZED = 1002;
1552 public final static int RESIZED_REPORT = 1003;
1553 public final static int WINDOW_FOCUS_CHANGED = 1004;
1554 public final static int DISPATCH_KEY = 1005;
1555 public final static int DISPATCH_POINTER = 1006;
1556 public final static int DISPATCH_TRACKBALL = 1007;
1557 public final static int DISPATCH_APP_VISIBILITY = 1008;
1558 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1559 public final static int FINISHED_EVENT = 1010;
1560 public final static int DISPATCH_KEY_FROM_IME = 1011;
1561 public final static int FINISH_INPUT_CONNECTION = 1012;
1562 public final static int CHECK_FOCUS = 1013;
1563
1564 @Override
1565 public void handleMessage(Message msg) {
1566 switch (msg.what) {
1567 case View.AttachInfo.INVALIDATE_MSG:
1568 ((View) msg.obj).invalidate();
1569 break;
1570 case View.AttachInfo.INVALIDATE_RECT_MSG:
1571 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1572 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1573 info.release();
1574 break;
1575 case DO_TRAVERSAL:
1576 if (mProfile) {
1577 Debug.startMethodTracing("ViewRoot");
1578 }
1579
1580 performTraversals();
1581
1582 if (mProfile) {
1583 Debug.stopMethodTracing();
1584 mProfile = false;
1585 }
1586 break;
1587 case FINISHED_EVENT:
1588 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1589 break;
1590 case DISPATCH_KEY:
1591 if (LOCAL_LOGV) Log.v(
1592 "ViewRoot", "Dispatching key "
1593 + msg.obj + " to " + mView);
1594 deliverKeyEvent((KeyEvent)msg.obj, true);
1595 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001596 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 MotionEvent event = (MotionEvent)msg.obj;
1598
1599 boolean didFinish;
1600 if (event == null) {
1601 try {
1602 event = sWindowSession.getPendingPointerMove(mWindow);
1603 } catch (RemoteException e) {
1604 }
1605 didFinish = true;
1606 } else {
1607 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
1608 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001609 if (event != null && mTranslator != null) {
1610 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 try {
1613 boolean handled;
1614 if (mView != null && mAdded && event != null) {
1615
1616 // enter touch mode on the down
1617 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1618 if (isDown) {
1619 ensureTouchMode(true);
1620 }
1621 if(Config.LOGV) {
1622 captureMotionLog("captureDispatchPointer", event);
1623 }
1624 event.offsetLocation(0, mCurScrollY);
1625 handled = mView.dispatchTouchEvent(event);
1626 if (!handled && isDown) {
1627 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1628
1629 final int edgeFlags = event.getEdgeFlags();
1630 int direction = View.FOCUS_UP;
1631 int x = (int)event.getX();
1632 int y = (int)event.getY();
1633 final int[] deltas = new int[2];
1634
1635 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1636 direction = View.FOCUS_DOWN;
1637 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1638 deltas[0] = edgeSlop;
1639 x += edgeSlop;
1640 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1641 deltas[0] = -edgeSlop;
1642 x -= edgeSlop;
1643 }
1644 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1645 direction = View.FOCUS_UP;
1646 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1647 deltas[0] = edgeSlop;
1648 x += edgeSlop;
1649 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1650 deltas[0] = -edgeSlop;
1651 x -= edgeSlop;
1652 }
1653 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1654 direction = View.FOCUS_RIGHT;
1655 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1656 direction = View.FOCUS_LEFT;
1657 }
1658
1659 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1660 View nearest = FocusFinder.getInstance().findNearestTouchable(
1661 ((ViewGroup) mView), x, y, direction, deltas);
1662 if (nearest != null) {
1663 event.offsetLocation(deltas[0], deltas[1]);
1664 event.setEdgeFlags(0);
1665 mView.dispatchTouchEvent(event);
1666 }
1667 }
1668 }
1669 }
1670 } finally {
1671 if (!didFinish) {
1672 try {
1673 sWindowSession.finishKey(mWindow);
1674 } catch (RemoteException e) {
1675 }
1676 }
1677 if (event != null) {
1678 event.recycle();
1679 }
1680 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1681 // Let the exception fall through -- the looper will catch
1682 // it and take care of the bad app for us.
1683 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001684 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 case DISPATCH_TRACKBALL:
1686 deliverTrackballEvent((MotionEvent)msg.obj);
1687 break;
1688 case DISPATCH_APP_VISIBILITY:
1689 handleAppVisibility(msg.arg1 != 0);
1690 break;
1691 case DISPATCH_GET_NEW_SURFACE:
1692 handleGetNewSurface();
1693 break;
1694 case RESIZED:
1695 Rect coveredInsets = ((Rect[])msg.obj)[0];
1696 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1699 && mPendingContentInsets.equals(coveredInsets)
1700 && mPendingVisibleInsets.equals(visibleInsets)) {
1701 break;
1702 }
1703 // fall through...
1704 case RESIZED_REPORT:
1705 if (mAdded) {
1706 mWinFrame.left = 0;
1707 mWinFrame.right = msg.arg1;
1708 mWinFrame.top = 0;
1709 mWinFrame.bottom = msg.arg2;
1710 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1711 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1712 if (msg.what == RESIZED_REPORT) {
1713 mReportNextDraw = true;
1714 }
1715 requestLayout();
1716 }
1717 break;
1718 case WINDOW_FOCUS_CHANGED: {
1719 if (mAdded) {
1720 boolean hasWindowFocus = msg.arg1 != 0;
1721 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1722 if (hasWindowFocus) {
1723 boolean inTouchMode = msg.arg2 != 0;
1724 ensureTouchModeLocally(inTouchMode);
1725
1726 if (mGlWanted) {
1727 checkEglErrors();
1728 // we lost the gl context, so recreate it.
1729 if (mGlWanted && !mUseGL) {
1730 initializeGL();
1731 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001732 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001733 mGlCanvas.setViewport(
1734 (int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
1736 }
1737 }
1738 }
Romain Guy8506ab42009-06-11 17:35:47 -07001739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 mLastWasImTarget = WindowManager.LayoutParams
1741 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 InputMethodManager imm = InputMethodManager.peekInstance();
1744 if (mView != null) {
1745 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1746 imm.startGettingWindowFocus(mView);
1747 }
1748 mView.dispatchWindowFocusChanged(hasWindowFocus);
1749 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 // Note: must be done after the focus change callbacks,
1752 // so all of the view state is set up correctly.
1753 if (hasWindowFocus) {
1754 if (imm != null && mLastWasImTarget) {
1755 imm.onWindowFocus(mView, mView.findFocus(),
1756 mWindowAttributes.softInputMode,
1757 !mHasHadWindowFocus, mWindowAttributes.flags);
1758 }
1759 // Clear the forward bit. We can just do this directly, since
1760 // the window manager doesn't care about it.
1761 mWindowAttributes.softInputMode &=
1762 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1763 ((WindowManager.LayoutParams)mView.getLayoutParams())
1764 .softInputMode &=
1765 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1766 mHasHadWindowFocus = true;
1767 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001768
1769 if (hasWindowFocus && mView != null) {
1770 sendAccessibilityEvents();
1771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773 } break;
1774 case DIE:
1775 dispatchDetachedFromWindow();
1776 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001777 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 if (LOCAL_LOGV) Log.v(
1779 "ViewRoot", "Dispatching key "
1780 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001781 KeyEvent event = (KeyEvent)msg.obj;
1782 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1783 // The IME is trying to say this event is from the
1784 // system! Bad bad bad!
1785 event = KeyEvent.changeFlags(event,
1786 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001789 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 case FINISH_INPUT_CONNECTION: {
1791 InputMethodManager imm = InputMethodManager.peekInstance();
1792 if (imm != null) {
1793 imm.reportFinishInputConnection((InputConnection)msg.obj);
1794 }
1795 } break;
1796 case CHECK_FOCUS: {
1797 InputMethodManager imm = InputMethodManager.peekInstance();
1798 if (imm != null) {
1799 imm.checkFocus();
1800 }
1801 } break;
1802 }
1803 }
1804
1805 /**
1806 * Something in the current window tells us we need to change the touch mode. For
1807 * example, we are not in touch mode, and the user touches the screen.
1808 *
1809 * If the touch mode has changed, tell the window manager, and handle it locally.
1810 *
1811 * @param inTouchMode Whether we want to be in touch mode.
1812 * @return True if the touch mode changed and focus changed was changed as a result
1813 */
1814 boolean ensureTouchMode(boolean inTouchMode) {
1815 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1816 + "touch mode is " + mAttachInfo.mInTouchMode);
1817 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1818
1819 // tell the window manager
1820 try {
1821 sWindowSession.setInTouchMode(inTouchMode);
1822 } catch (RemoteException e) {
1823 throw new RuntimeException(e);
1824 }
1825
1826 // handle the change
1827 return ensureTouchModeLocally(inTouchMode);
1828 }
1829
1830 /**
1831 * Ensure that the touch mode for this window is set, and if it is changing,
1832 * take the appropriate action.
1833 * @param inTouchMode Whether we want to be in touch mode.
1834 * @return True if the touch mode changed and focus changed was changed as a result
1835 */
1836 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1837 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1838 + "touch mode is " + mAttachInfo.mInTouchMode);
1839
1840 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1841
1842 mAttachInfo.mInTouchMode = inTouchMode;
1843 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1844
1845 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1846 }
1847
1848 private boolean enterTouchMode() {
1849 if (mView != null) {
1850 if (mView.hasFocus()) {
1851 // note: not relying on mFocusedView here because this could
1852 // be when the window is first being added, and mFocused isn't
1853 // set yet.
1854 final View focused = mView.findFocus();
1855 if (focused != null && !focused.isFocusableInTouchMode()) {
1856
1857 final ViewGroup ancestorToTakeFocus =
1858 findAncestorToTakeFocusInTouchMode(focused);
1859 if (ancestorToTakeFocus != null) {
1860 // there is an ancestor that wants focus after its descendants that
1861 // is focusable in touch mode.. give it focus
1862 return ancestorToTakeFocus.requestFocus();
1863 } else {
1864 // nothing appropriate to have focus in touch mode, clear it out
1865 mView.unFocus();
1866 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1867 mFocusedView = null;
1868 return true;
1869 }
1870 }
1871 }
1872 }
1873 return false;
1874 }
1875
1876
1877 /**
1878 * Find an ancestor of focused that wants focus after its descendants and is
1879 * focusable in touch mode.
1880 * @param focused The currently focused view.
1881 * @return An appropriate view, or null if no such view exists.
1882 */
1883 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1884 ViewParent parent = focused.getParent();
1885 while (parent instanceof ViewGroup) {
1886 final ViewGroup vgParent = (ViewGroup) parent;
1887 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1888 && vgParent.isFocusableInTouchMode()) {
1889 return vgParent;
1890 }
1891 if (vgParent.isRootNamespace()) {
1892 return null;
1893 } else {
1894 parent = vgParent.getParent();
1895 }
1896 }
1897 return null;
1898 }
1899
1900 private boolean leaveTouchMode() {
1901 if (mView != null) {
1902 if (mView.hasFocus()) {
1903 // i learned the hard way to not trust mFocusedView :)
1904 mFocusedView = mView.findFocus();
1905 if (!(mFocusedView instanceof ViewGroup)) {
1906 // some view has focus, let it keep it
1907 return false;
1908 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1909 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1910 // some view group has focus, and doesn't prefer its children
1911 // over itself for focus, so let them keep it.
1912 return false;
1913 }
1914 }
1915
1916 // find the best view to give focus to in this brave new non-touch-mode
1917 // world
1918 final View focused = focusSearch(null, View.FOCUS_DOWN);
1919 if (focused != null) {
1920 return focused.requestFocus(View.FOCUS_DOWN);
1921 }
1922 }
1923 return false;
1924 }
1925
1926
1927 private void deliverTrackballEvent(MotionEvent event) {
1928 boolean didFinish;
1929 if (event == null) {
1930 try {
1931 event = sWindowSession.getPendingTrackballMove(mWindow);
1932 } catch (RemoteException e) {
1933 }
1934 didFinish = true;
1935 } else {
1936 didFinish = false;
1937 }
1938
1939 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
1940
1941 boolean handled = false;
1942 try {
1943 if (event == null) {
1944 handled = true;
1945 } else if (mView != null && mAdded) {
1946 handled = mView.dispatchTrackballEvent(event);
1947 if (!handled) {
1948 // we could do something here, like changing the focus
1949 // or something?
1950 }
1951 }
1952 } finally {
1953 if (handled) {
1954 if (!didFinish) {
1955 try {
1956 sWindowSession.finishKey(mWindow);
1957 } catch (RemoteException e) {
1958 }
1959 }
1960 if (event != null) {
1961 event.recycle();
1962 }
1963 // If we reach this, we delivered a trackball event to mView and
1964 // mView consumed it. Because we will not translate the trackball
1965 // event into a key event, touch mode will not exit, so we exit
1966 // touch mode here.
1967 ensureTouchMode(false);
1968 //noinspection ReturnInsideFinallyBlock
1969 return;
1970 }
1971 // Let the exception fall through -- the looper will catch
1972 // it and take care of the bad app for us.
1973 }
1974
1975 final TrackballAxis x = mTrackballAxisX;
1976 final TrackballAxis y = mTrackballAxisY;
1977
1978 long curTime = SystemClock.uptimeMillis();
1979 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
1980 // It has been too long since the last movement,
1981 // so restart at the beginning.
1982 x.reset(0);
1983 y.reset(0);
1984 mLastTrackballTime = curTime;
1985 }
1986
1987 try {
1988 final int action = event.getAction();
1989 final int metastate = event.getMetaState();
1990 switch (action) {
1991 case MotionEvent.ACTION_DOWN:
1992 x.reset(2);
1993 y.reset(2);
1994 deliverKeyEvent(new KeyEvent(curTime, curTime,
1995 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
1996 0, metastate), false);
1997 break;
1998 case MotionEvent.ACTION_UP:
1999 x.reset(2);
2000 y.reset(2);
2001 deliverKeyEvent(new KeyEvent(curTime, curTime,
2002 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2003 0, metastate), false);
2004 break;
2005 }
2006
2007 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2008 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2009 + " move=" + event.getX()
2010 + " / Y=" + y.position + " step="
2011 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2012 + " move=" + event.getY());
2013 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2014 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2015
2016 // Generate DPAD events based on the trackball movement.
2017 // We pick the axis that has moved the most as the direction of
2018 // the DPAD. When we generate DPAD events for one axis, then the
2019 // other axis is reset -- we don't want to perform DPAD jumps due
2020 // to slight movements in the trackball when making major movements
2021 // along the other axis.
2022 int keycode = 0;
2023 int movement = 0;
2024 float accel = 1;
2025 if (xOff > yOff) {
2026 movement = x.generate((2/event.getXPrecision()));
2027 if (movement != 0) {
2028 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2029 : KeyEvent.KEYCODE_DPAD_LEFT;
2030 accel = x.acceleration;
2031 y.reset(2);
2032 }
2033 } else if (yOff > 0) {
2034 movement = y.generate((2/event.getYPrecision()));
2035 if (movement != 0) {
2036 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2037 : KeyEvent.KEYCODE_DPAD_UP;
2038 accel = y.acceleration;
2039 x.reset(2);
2040 }
2041 }
2042
2043 if (keycode != 0) {
2044 if (movement < 0) movement = -movement;
2045 int accelMovement = (int)(movement * accel);
2046 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2047 + " accelMovement=" + accelMovement
2048 + " accel=" + accel);
2049 if (accelMovement > movement) {
2050 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2051 + keycode);
2052 movement--;
2053 deliverKeyEvent(new KeyEvent(curTime, curTime,
2054 KeyEvent.ACTION_MULTIPLE, keycode,
2055 accelMovement-movement, metastate), false);
2056 }
2057 while (movement > 0) {
2058 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2059 + keycode);
2060 movement--;
2061 curTime = SystemClock.uptimeMillis();
2062 deliverKeyEvent(new KeyEvent(curTime, curTime,
2063 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2064 deliverKeyEvent(new KeyEvent(curTime, curTime,
2065 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2066 }
2067 mLastTrackballTime = curTime;
2068 }
2069 } finally {
2070 if (!didFinish) {
2071 try {
2072 sWindowSession.finishKey(mWindow);
2073 } catch (RemoteException e) {
2074 }
2075 if (event != null) {
2076 event.recycle();
2077 }
2078 }
2079 // Let the exception fall through -- the looper will catch
2080 // it and take care of the bad app for us.
2081 }
2082 }
2083
2084 /**
2085 * @param keyCode The key code
2086 * @return True if the key is directional.
2087 */
2088 static boolean isDirectional(int keyCode) {
2089 switch (keyCode) {
2090 case KeyEvent.KEYCODE_DPAD_LEFT:
2091 case KeyEvent.KEYCODE_DPAD_RIGHT:
2092 case KeyEvent.KEYCODE_DPAD_UP:
2093 case KeyEvent.KEYCODE_DPAD_DOWN:
2094 return true;
2095 }
2096 return false;
2097 }
2098
2099 /**
2100 * Returns true if this key is a keyboard key.
2101 * @param keyEvent The key event.
2102 * @return whether this key is a keyboard key.
2103 */
2104 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2105 final int convertedKey = keyEvent.getUnicodeChar();
2106 return convertedKey > 0;
2107 }
2108
2109
2110
2111 /**
2112 * See if the key event means we should leave touch mode (and leave touch
2113 * mode if so).
2114 * @param event The key event.
2115 * @return Whether this key event should be consumed (meaning the act of
2116 * leaving touch mode alone is considered the event).
2117 */
2118 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2119 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2120 return false;
2121 }
2122 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2123 return false;
2124 }
2125
2126 // only relevant if we are in touch mode
2127 if (!mAttachInfo.mInTouchMode) {
2128 return false;
2129 }
2130
2131 // if something like an edit text has focus and the user is typing,
2132 // leave touch mode
2133 //
2134 // note: the condition of not being a keyboard key is kind of a hacky
2135 // approximation of whether we think the focused view will want the
2136 // key; if we knew for sure whether the focused view would consume
2137 // the event, that would be better.
2138 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2139 mFocusedView = mView.findFocus();
2140 if ((mFocusedView instanceof ViewGroup)
2141 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2142 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2143 // something has focus, but is holding it weakly as a container
2144 return false;
2145 }
2146 if (ensureTouchMode(false)) {
2147 throw new IllegalStateException("should not have changed focus "
2148 + "when leaving touch mode while a view has focus.");
2149 }
2150 return false;
2151 }
2152
2153 if (isDirectional(event.getKeyCode())) {
2154 // no view has focus, so we leave touch mode (and find something
2155 // to give focus to). the event is consumed if we were able to
2156 // find something to give focus to.
2157 return ensureTouchMode(false);
2158 }
2159 return false;
2160 }
2161
2162 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002163 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 */
2165 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002166 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 if (ev == null ||
2168 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2169 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 }
Romain Guy8506ab42009-06-11 17:35:47 -07002171
2172 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 sb.append(ev.getDownTime()).append(',');
2174 sb.append(ev.getEventTime()).append(',');
2175 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002176 sb.append(ev.getX()).append(',');
2177 sb.append(ev.getY()).append(',');
2178 sb.append(ev.getPressure()).append(',');
2179 sb.append(ev.getSize()).append(',');
2180 sb.append(ev.getMetaState()).append(',');
2181 sb.append(ev.getXPrecision()).append(',');
2182 sb.append(ev.getYPrecision()).append(',');
2183 sb.append(ev.getDeviceId()).append(',');
2184 sb.append(ev.getEdgeFlags());
2185 Log.d(TAG, sb.toString());
2186 }
2187 /**
2188 * log motion events
2189 */
2190 private static void captureKeyLog(String subTag, KeyEvent ev) {
2191 //check dynamic switch
2192 if (ev == null ||
2193 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2194 return;
2195 }
2196 StringBuilder sb = new StringBuilder(subTag + ": ");
2197 sb.append(ev.getDownTime()).append(',');
2198 sb.append(ev.getEventTime()).append(',');
2199 sb.append(ev.getAction()).append(',');
2200 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 sb.append(ev.getRepeatCount()).append(',');
2202 sb.append(ev.getMetaState()).append(',');
2203 sb.append(ev.getDeviceId()).append(',');
2204 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002205 Log.d(TAG, sb.toString());
2206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207
2208 int enqueuePendingEvent(Object event, boolean sendDone) {
2209 int seq = mPendingEventSeq+1;
2210 if (seq < 0) seq = 0;
2211 mPendingEventSeq = seq;
2212 mPendingEvents.put(seq, event);
2213 return sendDone ? seq : -seq;
2214 }
2215
2216 Object retrievePendingEvent(int seq) {
2217 if (seq < 0) seq = -seq;
2218 Object event = mPendingEvents.get(seq);
2219 if (event != null) {
2220 mPendingEvents.remove(seq);
2221 }
2222 return event;
2223 }
Romain Guy8506ab42009-06-11 17:35:47 -07002224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2226 // If mView is null, we just consume the key event because it doesn't
2227 // make sense to do anything else with it.
2228 boolean handled = mView != null
2229 ? mView.dispatchKeyEventPreIme(event) : true;
2230 if (handled) {
2231 if (sendDone) {
2232 if (LOCAL_LOGV) Log.v(
2233 "ViewRoot", "Telling window manager key is finished");
2234 try {
2235 sWindowSession.finishKey(mWindow);
2236 } catch (RemoteException e) {
2237 }
2238 }
2239 return;
2240 }
2241 // If it is possible for this window to interact with the input
2242 // method window, then we want to first dispatch our key events
2243 // to the input method.
2244 if (mLastWasImTarget) {
2245 InputMethodManager imm = InputMethodManager.peekInstance();
2246 if (imm != null && mView != null) {
2247 int seq = enqueuePendingEvent(event, sendDone);
2248 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2249 + seq + " event=" + event);
2250 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2251 mInputMethodCallback);
2252 return;
2253 }
2254 }
2255 deliverKeyEventToViewHierarchy(event, sendDone);
2256 }
2257
2258 void handleFinishedEvent(int seq, boolean handled) {
2259 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2260 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2261 + " handled=" + handled + " event=" + event);
2262 if (event != null) {
2263 final boolean sendDone = seq >= 0;
2264 if (!handled) {
2265 deliverKeyEventToViewHierarchy(event, sendDone);
2266 return;
2267 } else if (sendDone) {
2268 if (LOCAL_LOGV) Log.v(
2269 "ViewRoot", "Telling window manager key is finished");
2270 try {
2271 sWindowSession.finishKey(mWindow);
2272 } catch (RemoteException e) {
2273 }
2274 } else {
2275 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2276 + " handled=" + handled + " ev=" + event
2277 + ") neither delivering nor finishing key");
2278 }
2279 }
2280 }
Romain Guy8506ab42009-06-11 17:35:47 -07002281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2283 try {
2284 if (mView != null && mAdded) {
2285 final int action = event.getAction();
2286 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2287
2288 if (checkForLeavingTouchModeAndConsume(event)) {
2289 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002290 }
2291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 if (Config.LOGV) {
2293 captureKeyLog("captureDispatchKeyEvent", event);
2294 }
2295 boolean keyHandled = mView.dispatchKeyEvent(event);
2296
2297 if (!keyHandled && isDown) {
2298 int direction = 0;
2299 switch (event.getKeyCode()) {
2300 case KeyEvent.KEYCODE_DPAD_LEFT:
2301 direction = View.FOCUS_LEFT;
2302 break;
2303 case KeyEvent.KEYCODE_DPAD_RIGHT:
2304 direction = View.FOCUS_RIGHT;
2305 break;
2306 case KeyEvent.KEYCODE_DPAD_UP:
2307 direction = View.FOCUS_UP;
2308 break;
2309 case KeyEvent.KEYCODE_DPAD_DOWN:
2310 direction = View.FOCUS_DOWN;
2311 break;
2312 }
2313
2314 if (direction != 0) {
2315
2316 View focused = mView != null ? mView.findFocus() : null;
2317 if (focused != null) {
2318 View v = focused.focusSearch(direction);
2319 boolean focusPassed = false;
2320 if (v != null && v != focused) {
2321 // do the math the get the interesting rect
2322 // of previous focused into the coord system of
2323 // newly focused view
2324 focused.getFocusedRect(mTempRect);
2325 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2326 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2327 focusPassed = v.requestFocus(direction, mTempRect);
2328 }
2329
2330 if (!focusPassed) {
2331 mView.dispatchUnhandledMove(focused, direction);
2332 } else {
2333 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2334 }
2335 }
2336 }
2337 }
2338 }
2339
2340 } finally {
2341 if (sendDone) {
2342 if (LOCAL_LOGV) Log.v(
2343 "ViewRoot", "Telling window manager key is finished");
2344 try {
2345 sWindowSession.finishKey(mWindow);
2346 } catch (RemoteException e) {
2347 }
2348 }
2349 // Let the exception fall through -- the looper will catch
2350 // it and take care of the bad app for us.
2351 }
2352 }
2353
2354 private AudioManager getAudioManager() {
2355 if (mView == null) {
2356 throw new IllegalStateException("getAudioManager called when there is no mView");
2357 }
2358 if (mAudioManager == null) {
2359 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2360 }
2361 return mAudioManager;
2362 }
2363
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002364 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2365 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002366
2367 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002368 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002369 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002370 restore = true;
2371 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002372 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002373 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002374 if (params != null) {
2375 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002376 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002377 int relayoutResult = sWindowSession.relayout(
2378 mWindow, params,
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002379 (int) (mView.mMeasuredWidth * appScale),
2380 (int) (mView.mMeasuredHeight * appScale),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002381 viewVisibility, insetsPending, mWinFrame,
2382 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002383 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002384 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002385 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002386
2387 if (mTranslator != null) {
2388 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2389 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2390 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002391 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002392 return relayoutResult;
2393 }
Romain Guy8506ab42009-06-11 17:35:47 -07002394
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002395 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 * {@inheritDoc}
2397 */
2398 public void playSoundEffect(int effectId) {
2399 checkThread();
2400
2401 final AudioManager audioManager = getAudioManager();
2402
2403 switch (effectId) {
2404 case SoundEffectConstants.CLICK:
2405 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2406 return;
2407 case SoundEffectConstants.NAVIGATION_DOWN:
2408 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2409 return;
2410 case SoundEffectConstants.NAVIGATION_LEFT:
2411 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2412 return;
2413 case SoundEffectConstants.NAVIGATION_RIGHT:
2414 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2415 return;
2416 case SoundEffectConstants.NAVIGATION_UP:
2417 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2418 return;
2419 default:
2420 throw new IllegalArgumentException("unknown effect id " + effectId +
2421 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2422 }
2423 }
2424
2425 /**
2426 * {@inheritDoc}
2427 */
2428 public boolean performHapticFeedback(int effectId, boolean always) {
2429 try {
2430 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2431 } catch (RemoteException e) {
2432 return false;
2433 }
2434 }
2435
2436 /**
2437 * {@inheritDoc}
2438 */
2439 public View focusSearch(View focused, int direction) {
2440 checkThread();
2441 if (!(mView instanceof ViewGroup)) {
2442 return null;
2443 }
2444 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2445 }
2446
2447 public void debug() {
2448 mView.debug();
2449 }
2450
2451 public void die(boolean immediate) {
2452 checkThread();
2453 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2454 synchronized (this) {
2455 if (mAdded && !mFirst) {
2456 int viewVisibility = mView.getVisibility();
2457 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2458 if (mWindowAttributesChanged || viewVisibilityChanged) {
2459 // If layout params have been changed, first give them
2460 // to the window manager to make sure it has the correct
2461 // animation info.
2462 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002463 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2464 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 sWindowSession.finishDrawing(mWindow);
2466 }
2467 } catch (RemoteException e) {
2468 }
2469 }
2470
2471 mSurface = null;
2472 }
2473 if (mAdded) {
2474 mAdded = false;
2475 if (immediate) {
2476 dispatchDetachedFromWindow();
2477 } else if (mView != null) {
2478 sendEmptyMessage(DIE);
2479 }
2480 }
2481 }
2482 }
2483
2484 public void dispatchFinishedEvent(int seq, boolean handled) {
2485 Message msg = obtainMessage(FINISHED_EVENT);
2486 msg.arg1 = seq;
2487 msg.arg2 = handled ? 1 : 0;
2488 sendMessage(msg);
2489 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 public void dispatchResized(int w, int h, Rect coveredInsets,
2492 Rect visibleInsets, boolean reportDraw) {
2493 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2494 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2495 + " visibleInsets=" + visibleInsets.toShortString()
2496 + " reportDraw=" + reportDraw);
2497 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002498 if (mTranslator != null) {
2499 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2500 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2501 w *= mTranslator.applicationInvertedScale;
2502 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002503 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002504 msg.arg1 = w;
2505 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2507 sendMessage(msg);
2508 }
2509
2510 public void dispatchKey(KeyEvent event) {
2511 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2512 //noinspection ConstantConditions
2513 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2514 if (Config.LOGD) Log.d("keydisp",
2515 "===================================================");
2516 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2517 debug();
2518
2519 if (Config.LOGD) Log.d("keydisp",
2520 "===================================================");
2521 }
2522 }
2523
2524 Message msg = obtainMessage(DISPATCH_KEY);
2525 msg.obj = event;
2526
2527 if (LOCAL_LOGV) Log.v(
2528 "ViewRoot", "sending key " + event + " to " + mView);
2529
2530 sendMessageAtTime(msg, event.getEventTime());
2531 }
2532
2533 public void dispatchPointer(MotionEvent event, long eventTime) {
2534 Message msg = obtainMessage(DISPATCH_POINTER);
2535 msg.obj = event;
2536 sendMessageAtTime(msg, eventTime);
2537 }
2538
2539 public void dispatchTrackball(MotionEvent event, long eventTime) {
2540 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2541 msg.obj = event;
2542 sendMessageAtTime(msg, eventTime);
2543 }
2544
2545 public void dispatchAppVisibility(boolean visible) {
2546 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2547 msg.arg1 = visible ? 1 : 0;
2548 sendMessage(msg);
2549 }
2550
2551 public void dispatchGetNewSurface() {
2552 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2553 sendMessage(msg);
2554 }
2555
2556 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2557 Message msg = Message.obtain();
2558 msg.what = WINDOW_FOCUS_CHANGED;
2559 msg.arg1 = hasFocus ? 1 : 0;
2560 msg.arg2 = inTouchMode ? 1 : 0;
2561 sendMessage(msg);
2562 }
2563
svetoslavganov75986cf2009-05-14 22:28:01 -07002564 /**
2565 * The window is getting focus so if there is anything focused/selected
2566 * send an {@link AccessibilityEvent} to announce that.
2567 */
2568 private void sendAccessibilityEvents() {
2569 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2570 return;
2571 }
2572 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2573 View focusedView = mView.findFocus();
2574 if (focusedView != null && focusedView != mView) {
2575 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2576 }
2577 }
2578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 public boolean showContextMenuForChild(View originalView) {
2580 return false;
2581 }
2582
2583 public void createContextMenu(ContextMenu menu) {
2584 }
2585
2586 public void childDrawableStateChanged(View child) {
2587 }
2588
2589 protected Rect getWindowFrame() {
2590 return mWinFrame;
2591 }
2592
2593 void checkThread() {
2594 if (mThread != Thread.currentThread()) {
2595 throw new CalledFromWrongThreadException(
2596 "Only the original thread that created a view hierarchy can touch its views.");
2597 }
2598 }
2599
2600 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2601 // ViewRoot never intercepts touch event, so this can be a no-op
2602 }
2603
2604 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2605 boolean immediate) {
2606 return scrollToRectOrFocus(rectangle, immediate);
2607 }
Romain Guy8506ab42009-06-11 17:35:47 -07002608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 static class InputMethodCallback extends IInputMethodCallback.Stub {
2610 private WeakReference<ViewRoot> mViewRoot;
2611
2612 public InputMethodCallback(ViewRoot viewRoot) {
2613 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2614 }
Romain Guy8506ab42009-06-11 17:35:47 -07002615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 public void finishedEvent(int seq, boolean handled) {
2617 final ViewRoot viewRoot = mViewRoot.get();
2618 if (viewRoot != null) {
2619 viewRoot.dispatchFinishedEvent(seq, handled);
2620 }
2621 }
2622
2623 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2624 // Stub -- not for use in the client.
2625 }
2626 }
Romain Guy8506ab42009-06-11 17:35:47 -07002627
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002628 static class EventCompletion extends Handler {
2629 final IWindow mWindow;
2630 final KeyEvent mKeyEvent;
2631 final boolean mIsPointer;
2632 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002633
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002634 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2635 boolean isPointer, MotionEvent motion) {
2636 super(looper);
2637 mWindow = window;
2638 mKeyEvent = key;
2639 mIsPointer = isPointer;
2640 mMotionEvent = motion;
2641 sendEmptyMessage(0);
2642 }
Romain Guy8506ab42009-06-11 17:35:47 -07002643
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002644 @Override
2645 public void handleMessage(Message msg) {
2646 if (mKeyEvent != null) {
2647 try {
2648 sWindowSession.finishKey(mWindow);
2649 } catch (RemoteException e) {
2650 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002651 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002652 boolean didFinish;
2653 MotionEvent event = mMotionEvent;
2654 if (event == null) {
2655 try {
2656 event = sWindowSession.getPendingPointerMove(mWindow);
2657 } catch (RemoteException e) {
2658 }
2659 didFinish = true;
2660 } else {
2661 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2662 }
2663 if (!didFinish) {
2664 try {
2665 sWindowSession.finishKey(mWindow);
2666 } catch (RemoteException e) {
2667 }
2668 }
2669 } else {
2670 MotionEvent event = mMotionEvent;
2671 if (event == null) {
2672 try {
2673 event = sWindowSession.getPendingTrackballMove(mWindow);
2674 } catch (RemoteException e) {
2675 }
2676 } else {
2677 try {
2678 sWindowSession.finishKey(mWindow);
2679 } catch (RemoteException e) {
2680 }
2681 }
2682 }
2683 }
2684 }
Romain Guy8506ab42009-06-11 17:35:47 -07002685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002687 private final WeakReference<ViewRoot> mViewRoot;
2688 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002690 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002692 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 }
2694
2695 public void resized(int w, int h, Rect coveredInsets,
2696 Rect visibleInsets, boolean reportDraw) {
2697 final ViewRoot viewRoot = mViewRoot.get();
2698 if (viewRoot != null) {
2699 viewRoot.dispatchResized(w, h, coveredInsets,
2700 visibleInsets, reportDraw);
2701 }
2702 }
2703
2704 public void dispatchKey(KeyEvent event) {
2705 final ViewRoot viewRoot = mViewRoot.get();
2706 if (viewRoot != null) {
2707 viewRoot.dispatchKey(event);
2708 } else {
2709 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002710 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712 }
2713
2714 public void dispatchPointer(MotionEvent event, long eventTime) {
2715 final ViewRoot viewRoot = mViewRoot.get();
2716 if (viewRoot != null) {
2717 viewRoot.dispatchPointer(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002718 } else {
2719 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
2721 }
2722
2723 public void dispatchTrackball(MotionEvent event, long eventTime) {
2724 final ViewRoot viewRoot = mViewRoot.get();
2725 if (viewRoot != null) {
2726 viewRoot.dispatchTrackball(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002727 } else {
2728 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
2730 }
2731
2732 public void dispatchAppVisibility(boolean visible) {
2733 final ViewRoot viewRoot = mViewRoot.get();
2734 if (viewRoot != null) {
2735 viewRoot.dispatchAppVisibility(visible);
2736 }
2737 }
2738
2739 public void dispatchGetNewSurface() {
2740 final ViewRoot viewRoot = mViewRoot.get();
2741 if (viewRoot != null) {
2742 viewRoot.dispatchGetNewSurface();
2743 }
2744 }
2745
2746 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2747 final ViewRoot viewRoot = mViewRoot.get();
2748 if (viewRoot != null) {
2749 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2750 }
2751 }
2752
2753 private static int checkCallingPermission(String permission) {
2754 if (!Process.supportsProcesses()) {
2755 return PackageManager.PERMISSION_GRANTED;
2756 }
2757
2758 try {
2759 return ActivityManagerNative.getDefault().checkPermission(
2760 permission, Binder.getCallingPid(), Binder.getCallingUid());
2761 } catch (RemoteException e) {
2762 return PackageManager.PERMISSION_DENIED;
2763 }
2764 }
2765
2766 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2767 final ViewRoot viewRoot = mViewRoot.get();
2768 if (viewRoot != null) {
2769 final View view = viewRoot.mView;
2770 if (view != null) {
2771 if (checkCallingPermission(Manifest.permission.DUMP) !=
2772 PackageManager.PERMISSION_GRANTED) {
2773 throw new SecurityException("Insufficient permissions to invoke"
2774 + " executeCommand() from pid=" + Binder.getCallingPid()
2775 + ", uid=" + Binder.getCallingUid());
2776 }
2777
2778 OutputStream clientStream = null;
2779 try {
2780 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2781 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2782 } catch (IOException e) {
2783 e.printStackTrace();
2784 } finally {
2785 if (clientStream != null) {
2786 try {
2787 clientStream.close();
2788 } catch (IOException e) {
2789 e.printStackTrace();
2790 }
2791 }
2792 }
2793 }
2794 }
2795 }
2796 }
2797
2798 /**
2799 * Maintains state information for a single trackball axis, generating
2800 * discrete (DPAD) movements based on raw trackball motion.
2801 */
2802 static final class TrackballAxis {
2803 /**
2804 * The maximum amount of acceleration we will apply.
2805 */
2806 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 /**
2809 * The maximum amount of time (in milliseconds) between events in order
2810 * for us to consider the user to be doing fast trackball movements,
2811 * and thus apply an acceleration.
2812 */
2813 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 /**
2816 * Scaling factor to the time (in milliseconds) between events to how
2817 * much to multiple/divide the current acceleration. When movement
2818 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2819 * FAST_MOVE_TIME it divides it.
2820 */
2821 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 float position;
2824 float absPosition;
2825 float acceleration = 1;
2826 long lastMoveTime = 0;
2827 int step;
2828 int dir;
2829 int nonAccelMovement;
2830
2831 void reset(int _step) {
2832 position = 0;
2833 acceleration = 1;
2834 lastMoveTime = 0;
2835 step = _step;
2836 dir = 0;
2837 }
2838
2839 /**
2840 * Add trackball movement into the state. If the direction of movement
2841 * has been reversed, the state is reset before adding the
2842 * movement (so that you don't have to compensate for any previously
2843 * collected movement before see the result of the movement in the
2844 * new direction).
2845 *
2846 * @return Returns the absolute value of the amount of movement
2847 * collected so far.
2848 */
2849 float collect(float off, long time, String axis) {
2850 long normTime;
2851 if (off > 0) {
2852 normTime = (long)(off * FAST_MOVE_TIME);
2853 if (dir < 0) {
2854 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2855 position = 0;
2856 step = 0;
2857 acceleration = 1;
2858 lastMoveTime = 0;
2859 }
2860 dir = 1;
2861 } else if (off < 0) {
2862 normTime = (long)((-off) * FAST_MOVE_TIME);
2863 if (dir > 0) {
2864 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2865 position = 0;
2866 step = 0;
2867 acceleration = 1;
2868 lastMoveTime = 0;
2869 }
2870 dir = -1;
2871 } else {
2872 normTime = 0;
2873 }
Romain Guy8506ab42009-06-11 17:35:47 -07002874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 // The number of milliseconds between each movement that is
2876 // considered "normal" and will not result in any acceleration
2877 // or deceleration, scaled by the offset we have here.
2878 if (normTime > 0) {
2879 long delta = time - lastMoveTime;
2880 lastMoveTime = time;
2881 float acc = acceleration;
2882 if (delta < normTime) {
2883 // The user is scrolling rapidly, so increase acceleration.
2884 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2885 if (scale > 1) acc *= scale;
2886 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2887 + off + " normTime=" + normTime + " delta=" + delta
2888 + " scale=" + scale + " acc=" + acc);
2889 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2890 } else {
2891 // The user is scrolling slowly, so decrease acceleration.
2892 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
2893 if (scale > 1) acc /= scale;
2894 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
2895 + off + " normTime=" + normTime + " delta=" + delta
2896 + " scale=" + scale + " acc=" + acc);
2897 acceleration = acc > 1 ? acc : 1;
2898 }
2899 }
2900 position += off;
2901 return (absPosition = Math.abs(position));
2902 }
2903
2904 /**
2905 * Generate the number of discrete movement events appropriate for
2906 * the currently collected trackball movement.
2907 *
2908 * @param precision The minimum movement required to generate the
2909 * first discrete movement.
2910 *
2911 * @return Returns the number of discrete movements, either positive
2912 * or negative, or 0 if there is not enough trackball movement yet
2913 * for a discrete movement.
2914 */
2915 int generate(float precision) {
2916 int movement = 0;
2917 nonAccelMovement = 0;
2918 do {
2919 final int dir = position >= 0 ? 1 : -1;
2920 switch (step) {
2921 // If we are going to execute the first step, then we want
2922 // to do this as soon as possible instead of waiting for
2923 // a full movement, in order to make things look responsive.
2924 case 0:
2925 if (absPosition < precision) {
2926 return movement;
2927 }
2928 movement += dir;
2929 nonAccelMovement += dir;
2930 step = 1;
2931 break;
2932 // If we have generated the first movement, then we need
2933 // to wait for the second complete trackball motion before
2934 // generating the second discrete movement.
2935 case 1:
2936 if (absPosition < 2) {
2937 return movement;
2938 }
2939 movement += dir;
2940 nonAccelMovement += dir;
2941 position += dir > 0 ? -2 : 2;
2942 absPosition = Math.abs(position);
2943 step = 2;
2944 break;
2945 // After the first two, we generate discrete movements
2946 // consistently with the trackball, applying an acceleration
2947 // if the trackball is moving quickly. This is a simple
2948 // acceleration on top of what we already compute based
2949 // on how quickly the wheel is being turned, to apply
2950 // a longer increasing acceleration to continuous movement
2951 // in one direction.
2952 default:
2953 if (absPosition < 1) {
2954 return movement;
2955 }
2956 movement += dir;
2957 position += dir >= 0 ? -1 : 1;
2958 absPosition = Math.abs(position);
2959 float acc = acceleration;
2960 acc *= 1.1f;
2961 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
2962 break;
2963 }
2964 } while (true);
2965 }
2966 }
2967
2968 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
2969 public CalledFromWrongThreadException(String msg) {
2970 super(msg);
2971 }
2972 }
2973
2974 private SurfaceHolder mHolder = new SurfaceHolder() {
2975 // we only need a SurfaceHolder for opengl. it would be nice
2976 // to implement everything else though, especially the callback
2977 // support (opengl doesn't make use of it right now, but eventually
2978 // will).
2979 public Surface getSurface() {
2980 return mSurface;
2981 }
2982
2983 public boolean isCreating() {
2984 return false;
2985 }
2986
2987 public void addCallback(Callback callback) {
2988 }
2989
2990 public void removeCallback(Callback callback) {
2991 }
2992
2993 public void setFixedSize(int width, int height) {
2994 }
2995
2996 public void setSizeFromLayout() {
2997 }
2998
2999 public void setFormat(int format) {
3000 }
3001
3002 public void setType(int type) {
3003 }
3004
3005 public void setKeepScreenOn(boolean screenOn) {
3006 }
3007
3008 public Canvas lockCanvas() {
3009 return null;
3010 }
3011
3012 public Canvas lockCanvas(Rect dirty) {
3013 return null;
3014 }
3015
3016 public void unlockCanvasAndPost(Canvas canvas) {
3017 }
3018 public Rect getSurfaceFrame() {
3019 return null;
3020 }
3021 };
3022
3023 static RunQueue getRunQueue() {
3024 RunQueue rq = sRunQueues.get();
3025 if (rq != null) {
3026 return rq;
3027 }
3028 rq = new RunQueue();
3029 sRunQueues.set(rq);
3030 return rq;
3031 }
Romain Guy8506ab42009-06-11 17:35:47 -07003032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 /**
3034 * @hide
3035 */
3036 static final class RunQueue {
3037 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3038
3039 void post(Runnable action) {
3040 postDelayed(action, 0);
3041 }
3042
3043 void postDelayed(Runnable action, long delayMillis) {
3044 HandlerAction handlerAction = new HandlerAction();
3045 handlerAction.action = action;
3046 handlerAction.delay = delayMillis;
3047
3048 synchronized (mActions) {
3049 mActions.add(handlerAction);
3050 }
3051 }
3052
3053 void removeCallbacks(Runnable action) {
3054 final HandlerAction handlerAction = new HandlerAction();
3055 handlerAction.action = action;
3056
3057 synchronized (mActions) {
3058 final ArrayList<HandlerAction> actions = mActions;
3059
3060 while (actions.remove(handlerAction)) {
3061 // Keep going
3062 }
3063 }
3064 }
3065
3066 void executeActions(Handler handler) {
3067 synchronized (mActions) {
3068 final ArrayList<HandlerAction> actions = mActions;
3069 final int count = actions.size();
3070
3071 for (int i = 0; i < count; i++) {
3072 final HandlerAction handlerAction = actions.get(i);
3073 handler.postDelayed(handlerAction.action, handlerAction.delay);
3074 }
3075
3076 mActions.clear();
3077 }
3078 }
3079
3080 private static class HandlerAction {
3081 Runnable action;
3082 long delay;
3083
3084 @Override
3085 public boolean equals(Object o) {
3086 if (this == o) return true;
3087 if (o == null || getClass() != o.getClass()) return false;
3088
3089 HandlerAction that = (HandlerAction) o;
3090
3091 return !(action != null ? !action.equals(that.action) : that.action != null);
3092
3093 }
3094
3095 @Override
3096 public int hashCode() {
3097 int result = action != null ? action.hashCode() : 0;
3098 result = 31 * result + (int) (delay ^ (delay >>> 32));
3099 return result;
3100 }
3101 }
3102 }
3103
3104 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3105
3106 // inform skia to just abandon its texture cache IDs
3107 // doesn't call glDeleteTextures
3108 private static native void nativeAbandonGlCaches();
3109}