blob: 216fc5e76e40cd2ee873bccdc5388038cf807604 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.graphics.PorterDuff;
25import android.graphics.Rect;
26import android.graphics.Region;
27import android.os.*;
28import android.os.Process;
29import android.os.SystemProperties;
30import android.util.AndroidRuntimeException;
31import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070032import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.util.Log;
34import android.util.EventLog;
35import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070037import android.view.accessibility.AccessibilityEvent;
38import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.view.inputmethod.InputConnection;
40import android.view.inputmethod.InputMethodManager;
41import android.widget.Scroller;
42import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070043import android.content.res.CompatibilityInfo;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070044import android.content.res.Resources;
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
Michael Chan53071d62009-05-13 17:29:48 -070082 private static final boolean MEASURE_LATENCY = false;
83 private static LatencyTimer lt;
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 /**
86 * Maximum time we allow the user to roll the trackball enough to generate
87 * a key event, before resetting the counters.
88 */
89 static final int MAX_TRACKBALL_DELAY = 250;
90
91 static long sInstanceCount = 0;
92
93 static IWindowSession sWindowSession;
94
95 static final Object mStaticInit = new Object();
96 static boolean mInitialized = false;
97
98 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
99
Romain Guy8506ab42009-06-11 17:35:47 -0700100 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 long mLastTrackballTime = 0;
103 final TrackballAxis mTrackballAxisX = new TrackballAxis();
104 final TrackballAxis mTrackballAxisY = new TrackballAxis();
105
106 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 final InputMethodCallback mInputMethodCallback;
109 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
110 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 final Thread mThread;
113
114 final WindowLeaked mLocation;
115
116 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
117
118 final W mWindow;
119
120 View mView;
121 View mFocusedView;
122 View mRealFocusedView; // this is not set to null in touch mode
123 int mViewVisibility;
124 boolean mAppVisible = true;
125
126 final Region mTransparentRegion;
127 final Region mPreviousTransparentRegion;
128
129 int mWidth;
130 int mHeight;
131 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700132 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700133
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700134 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
136 final View.AttachInfo mAttachInfo;
137
138 final Rect mTempRect; // used in the transaction to not thrash the heap.
139 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 boolean mTraversalScheduled;
142 boolean mWillDrawSoon;
143 boolean mLayoutRequested;
144 boolean mFirst;
145 boolean mReportNextDraw;
146 boolean mFullRedrawNeeded;
147 boolean mNewSurfaceNeeded;
148 boolean mHasHadWindowFocus;
149 boolean mLastWasImTarget;
150
151 boolean mWindowAttributesChanged = false;
152
153 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700154 // Surface can never be reassigned or cleared (use Surface.clear()).
155 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157 boolean mAdded;
158 boolean mAddedTouchMode;
159
160 /*package*/ int mAddNesting;
161
162 // These are accessed by multiple threads.
163 final Rect mWinFrame; // frame given by window manager.
164
165 final Rect mPendingVisibleInsets = new Rect();
166 final Rect mPendingContentInsets = new Rect();
167 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
168 = new ViewTreeObserver.InternalInsetsInfo();
169
170 boolean mScrollMayChange;
171 int mSoftInputMode;
172 View mLastScrolledFocus;
173 int mScrollY;
174 int mCurScrollY;
175 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 EGL10 mEgl;
178 EGLDisplay mEglDisplay;
179 EGLContext mEglContext;
180 EGLSurface mEglSurface;
181 GL11 mGL;
182 Canvas mGlCanvas;
183 boolean mUseGL;
184 boolean mGlWanted;
185
Romain Guy8506ab42009-06-11 17:35:47 -0700186 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 /**
189 * see {@link #playSoundEffect(int)}
190 */
191 AudioManager mAudioManager;
192
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700193 private final int mDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700195 public static IWindowSession getWindowSession(Looper mainLooper) {
196 synchronized (mStaticInit) {
197 if (!mInitialized) {
198 try {
199 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
200 sWindowSession = IWindowManager.Stub.asInterface(
201 ServiceManager.getService("window"))
202 .openSession(imm.getClient(), imm.getInputContext());
203 mInitialized = true;
204 } catch (RemoteException e) {
205 }
206 }
207 return sWindowSession;
208 }
209 }
210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 public ViewRoot(Context context) {
212 super();
213
Michael Chan53071d62009-05-13 17:29:48 -0700214 if (MEASURE_LATENCY && lt == null) {
215 lt = new LatencyTimer(100, 1000);
216 }
217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 ++sInstanceCount;
219
220 // Initialize the statics when this class is first instantiated. This is
221 // done here instead of in the static block because Zygote does not
222 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700223 getWindowSession(context.getMainLooper());
224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 mThread = Thread.currentThread();
226 mLocation = new WindowLeaked(null);
227 mLocation.fillInStackTrace();
228 mWidth = -1;
229 mHeight = -1;
230 mDirty = new Rect();
231 mTempRect = new Rect();
232 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700234 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 mInputMethodCallback = new InputMethodCallback(this);
236 mViewVisibility = View.GONE;
237 mTransparentRegion = new Region();
238 mPreviousTransparentRegion = new Region();
239 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 mAdded = false;
241 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
242 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700243 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
245
246 @Override
247 protected void finalize() throws Throwable {
248 super.finalize();
249 --sInstanceCount;
250 }
251
252 public static long getInstanceCount() {
253 return sInstanceCount;
254 }
255
256 // FIXME for perf testing only
257 private boolean mProfile = false;
258
259 /**
260 * Call this to profile the next traversal call.
261 * FIXME for perf testing only. Remove eventually
262 */
263 public void profile() {
264 mProfile = true;
265 }
266
267 /**
268 * Indicates whether we are in touch mode. Calling this method triggers an IPC
269 * call and should be avoided whenever possible.
270 *
271 * @return True, if the device is in touch mode, false otherwise.
272 *
273 * @hide
274 */
275 static boolean isInTouchMode() {
276 if (mInitialized) {
277 try {
278 return sWindowSession.getInTouchMode();
279 } catch (RemoteException e) {
280 }
281 }
282 return false;
283 }
284
285 private void initializeGL() {
286 initializeGLInner();
287 int err = mEgl.eglGetError();
288 if (err != EGL10.EGL_SUCCESS) {
289 // give-up on using GL
290 destroyGL();
291 mGlWanted = false;
292 }
293 }
294
295 private void initializeGLInner() {
296 final EGL10 egl = (EGL10) EGLContext.getEGL();
297 mEgl = egl;
298
299 /*
300 * Get to the default display.
301 */
302 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
303 mEglDisplay = eglDisplay;
304
305 /*
306 * We can now initialize EGL for that display
307 */
308 int[] version = new int[2];
309 egl.eglInitialize(eglDisplay, version);
310
311 /*
312 * Specify a configuration for our opengl session
313 * and grab the first configuration that matches is
314 */
315 final int[] configSpec = {
316 EGL10.EGL_RED_SIZE, 5,
317 EGL10.EGL_GREEN_SIZE, 6,
318 EGL10.EGL_BLUE_SIZE, 5,
319 EGL10.EGL_DEPTH_SIZE, 0,
320 EGL10.EGL_NONE
321 };
322 final EGLConfig[] configs = new EGLConfig[1];
323 final int[] num_config = new int[1];
324 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
325 final EGLConfig config = configs[0];
326
327 /*
328 * Create an OpenGL ES context. This must be done only once, an
329 * OpenGL context is a somewhat heavy object.
330 */
331 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
332 EGL10.EGL_NO_CONTEXT, null);
333 mEglContext = context;
334
335 /*
336 * Create an EGL surface we can render into.
337 */
338 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
339 mEglSurface = surface;
340
341 /*
342 * Before we can issue GL commands, we need to make sure
343 * the context is current and bound to a surface.
344 */
345 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
346
347 /*
348 * Get to the appropriate GL interface.
349 * This is simply done by casting the GL context to either
350 * GL10 or GL11.
351 */
352 final GL11 gl = (GL11) context.getGL();
353 mGL = gl;
354 mGlCanvas = new Canvas(gl);
355 mUseGL = true;
356 }
357
358 private void destroyGL() {
359 // inform skia that the context is gone
360 nativeAbandonGlCaches();
361
362 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
363 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
364 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
365 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
366 mEgl.eglTerminate(mEglDisplay);
367 mEglContext = null;
368 mEglSurface = null;
369 mEglDisplay = null;
370 mEgl = null;
371 mGlCanvas = null;
372 mGL = null;
373 mUseGL = false;
374 }
375
376 private void checkEglErrors() {
377 if (mUseGL) {
378 int err = mEgl.eglGetError();
379 if (err != EGL10.EGL_SUCCESS) {
380 // something bad has happened revert to
381 // normal rendering.
382 destroyGL();
383 if (err != EGL11.EGL_CONTEXT_LOST) {
384 // we'll try again if it was context lost
385 mGlWanted = false;
386 }
387 }
388 }
389 }
390
391 /**
392 * We have one child
393 */
394 public void setView(View view, WindowManager.LayoutParams attrs,
395 View panelParentView) {
396 synchronized (this) {
397 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700398 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700399 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700400 attrs = mWindowAttributes;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700401 Resources resources = mView.getContext().getResources();
402 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700403 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700404
405 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700406 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
407 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700408 }
409
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700410 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700411 if (attrs != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700412 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700413 attrs.backup();
414 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700415 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700416 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
417
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700418 if (!compatibilityInfo.supportsScreen()) {
419 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
420 }
421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 mSoftInputMode = attrs.softInputMode;
423 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 mAttachInfo.mRootView = view;
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700425 mAttachInfo.mScalingRequired = mTranslator == null ? false : true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700426 mAttachInfo.mApplicationScale =
427 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 if (panelParentView != null) {
429 mAttachInfo.mPanelParentWindowToken
430 = panelParentView.getApplicationWindowToken();
431 }
432 mAdded = true;
433 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 // Schedule the first layout -before- adding to the window
436 // manager, to make sure we do the relayout before receiving
437 // any other events from the system.
438 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700440 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 getHostVisibility(), mAttachInfo.mContentInsets);
442 } catch (RemoteException e) {
443 mAdded = false;
444 mView = null;
445 mAttachInfo.mRootView = null;
446 unscheduleTraversals();
447 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700448 } finally {
449 if (restore) {
450 attrs.restore();
451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700453
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700454 if (mTranslator != null) {
455 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 mPendingContentInsets.set(mAttachInfo.mContentInsets);
458 mPendingVisibleInsets.set(0, 0, 0, 0);
459 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
460 if (res < WindowManagerImpl.ADD_OKAY) {
461 mView = null;
462 mAttachInfo.mRootView = null;
463 mAdded = false;
464 unscheduleTraversals();
465 switch (res) {
466 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
467 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
468 throw new WindowManagerImpl.BadTokenException(
469 "Unable to add window -- token " + attrs.token
470 + " is not valid; is your activity running?");
471 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
472 throw new WindowManagerImpl.BadTokenException(
473 "Unable to add window -- token " + attrs.token
474 + " is not for an application");
475 case WindowManagerImpl.ADD_APP_EXITING:
476 throw new WindowManagerImpl.BadTokenException(
477 "Unable to add window -- app for token " + attrs.token
478 + " is exiting");
479 case WindowManagerImpl.ADD_DUPLICATE_ADD:
480 throw new WindowManagerImpl.BadTokenException(
481 "Unable to add window -- window " + mWindow
482 + " has already been added");
483 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
484 // Silently ignore -- we would have just removed it
485 // right away, anyway.
486 return;
487 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
488 throw new WindowManagerImpl.BadTokenException(
489 "Unable to add window " + mWindow +
490 " -- another window of this type already exists");
491 case WindowManagerImpl.ADD_PERMISSION_DENIED:
492 throw new WindowManagerImpl.BadTokenException(
493 "Unable to add window " + mWindow +
494 " -- permission denied for this window type");
495 }
496 throw new RuntimeException(
497 "Unable to add window -- unknown error code " + res);
498 }
499 view.assignParent(this);
500 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
501 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
502 }
503 }
504 }
505
506 public View getView() {
507 return mView;
508 }
509
510 final WindowLeaked getLocation() {
511 return mLocation;
512 }
513
514 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
515 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700516 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700517 // preserve compatible window flag if exists.
518 int compatibleWindowFlag =
519 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700521 mWindowAttributes.flags |= compatibleWindowFlag;
522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 if (newView) {
524 mSoftInputMode = attrs.softInputMode;
525 requestLayout();
526 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700527 // Don't lose the mode we last auto-computed.
528 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
529 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
530 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
531 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
532 | (oldSoftInputMode
533 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 mWindowAttributesChanged = true;
536 scheduleTraversals();
537 }
538 }
539
540 void handleAppVisibility(boolean visible) {
541 if (mAppVisible != visible) {
542 mAppVisible = visible;
543 scheduleTraversals();
544 }
545 }
546
547 void handleGetNewSurface() {
548 mNewSurfaceNeeded = true;
549 mFullRedrawNeeded = true;
550 scheduleTraversals();
551 }
552
553 /**
554 * {@inheritDoc}
555 */
556 public void requestLayout() {
557 checkThread();
558 mLayoutRequested = true;
559 scheduleTraversals();
560 }
561
562 /**
563 * {@inheritDoc}
564 */
565 public boolean isLayoutRequested() {
566 return mLayoutRequested;
567 }
568
569 public void invalidateChild(View child, Rect dirty) {
570 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700571 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
572 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700574 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700575 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700576 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700577 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700578 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700579 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700580 }
Romain Guy1e095972009-07-07 11:22:45 -0700581 if (mAttachInfo.mScalingRequired) {
582 dirty.inset(-1, -1);
583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 }
585 mDirty.union(dirty);
586 if (!mWillDrawSoon) {
587 scheduleTraversals();
588 }
589 }
590
591 public ViewParent getParent() {
592 return null;
593 }
594
595 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
596 invalidateChild(null, dirty);
597 return null;
598 }
599
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700600 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 if (child != mView) {
602 throw new RuntimeException("child is not mine, honest!");
603 }
604 // Note: don't apply scroll offset, because we want to know its
605 // visibility in the virtual canvas being given to the view hierarchy.
606 return r.intersect(0, 0, mWidth, mHeight);
607 }
608
609 public void bringChildToFront(View child) {
610 }
611
612 public void scheduleTraversals() {
613 if (!mTraversalScheduled) {
614 mTraversalScheduled = true;
615 sendEmptyMessage(DO_TRAVERSAL);
616 }
617 }
618
619 public void unscheduleTraversals() {
620 if (mTraversalScheduled) {
621 mTraversalScheduled = false;
622 removeMessages(DO_TRAVERSAL);
623 }
624 }
625
626 int getHostVisibility() {
627 return mAppVisible ? mView.getVisibility() : View.GONE;
628 }
Romain Guy8506ab42009-06-11 17:35:47 -0700629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 private void performTraversals() {
631 // cache mView since it is used so much below...
632 final View host = mView;
633
634 if (DBG) {
635 System.out.println("======================================");
636 System.out.println("performTraversals");
637 host.debug();
638 }
639
640 if (host == null || !mAdded)
641 return;
642
643 mTraversalScheduled = false;
644 mWillDrawSoon = true;
645 boolean windowResizesToFitContent = false;
646 boolean fullRedrawNeeded = mFullRedrawNeeded;
647 boolean newSurface = false;
648 WindowManager.LayoutParams lp = mWindowAttributes;
649
650 int desiredWindowWidth;
651 int desiredWindowHeight;
652 int childWidthMeasureSpec;
653 int childHeightMeasureSpec;
654
655 final View.AttachInfo attachInfo = mAttachInfo;
656
657 final int viewVisibility = getHostVisibility();
658 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
659 || mNewSurfaceNeeded;
660
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700661 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 WindowManager.LayoutParams params = null;
664 if (mWindowAttributesChanged) {
665 mWindowAttributesChanged = false;
666 params = lp;
667 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700668 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 if (mFirst) {
670 fullRedrawNeeded = true;
671 mLayoutRequested = true;
672
Romain Guy8506ab42009-06-11 17:35:47 -0700673 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700674 mView.getContext().getResources().getDisplayMetrics();
675 desiredWindowWidth = packageMetrics.widthPixels;
676 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677
678 // For the very first time, tell the view hierarchy that it
679 // is attached to the window. Note that at this point the surface
680 // object is not initialized to its backing store, but soon it
681 // will be (assuming the window is visible).
682 attachInfo.mSurface = mSurface;
683 attachInfo.mHasWindowFocus = false;
684 attachInfo.mWindowVisibility = viewVisibility;
685 attachInfo.mRecomputeGlobalAttributes = false;
686 attachInfo.mKeepScreenOn = false;
687 viewVisibilityChanged = false;
688 host.dispatchAttachedToWindow(attachInfo, 0);
689 getRunQueue().executeActions(attachInfo.mHandler);
690 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700693 desiredWindowWidth = frame.width();
694 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
696 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700697 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 fullRedrawNeeded = true;
699 mLayoutRequested = true;
700 windowResizesToFitContent = true;
701 }
702 }
703
704 if (viewVisibilityChanged) {
705 attachInfo.mWindowVisibility = viewVisibility;
706 host.dispatchWindowVisibilityChanged(viewVisibility);
707 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
708 if (mUseGL) {
709 destroyGL();
710 }
711 }
712 if (viewVisibility == View.GONE) {
713 // After making a window gone, we will count it as being
714 // shown for the first time the next time it gets focus.
715 mHasHadWindowFocus = false;
716 }
717 }
718
719 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (mLayoutRequested) {
722 if (mFirst) {
723 host.fitSystemWindows(mAttachInfo.mContentInsets);
724 // make sure touch mode code executes by setting cached value
725 // to opposite of the added touch mode.
726 mAttachInfo.mInTouchMode = !mAddedTouchMode;
727 ensureTouchModeLocally(mAddedTouchMode);
728 } else {
729 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
730 mAttachInfo.mContentInsets.set(mPendingContentInsets);
731 host.fitSystemWindows(mAttachInfo.mContentInsets);
732 insetsChanged = true;
733 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
734 + mAttachInfo.mContentInsets);
735 }
736 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
737 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
738 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
739 + mAttachInfo.mVisibleInsets);
740 }
741 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
742 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
743 windowResizesToFitContent = true;
744
Romain Guy8506ab42009-06-11 17:35:47 -0700745 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700746 mView.getContext().getResources().getDisplayMetrics();
747 desiredWindowWidth = packageMetrics.widthPixels;
748 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 }
750 }
751
752 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
753 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
754
755 // Ask host how big it wants to be
756 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
757 "Measuring " + host + " in display " + desiredWindowWidth
758 + "x" + desiredWindowHeight + "...");
759 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
760
761 if (DBG) {
762 System.out.println("======================================");
763 System.out.println("performTraversals -- after measure");
764 host.debug();
765 }
766 }
767
768 if (attachInfo.mRecomputeGlobalAttributes) {
769 //Log.i(TAG, "Computing screen on!");
770 attachInfo.mRecomputeGlobalAttributes = false;
771 boolean oldVal = attachInfo.mKeepScreenOn;
772 attachInfo.mKeepScreenOn = false;
773 host.dispatchCollectViewAttributes(0);
774 if (attachInfo.mKeepScreenOn != oldVal) {
775 params = lp;
776 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
777 }
778 }
779
780 if (mFirst || attachInfo.mViewVisibilityChanged) {
781 attachInfo.mViewVisibilityChanged = false;
782 int resizeMode = mSoftInputMode &
783 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
784 // If we are in auto resize mode, then we need to determine
785 // what mode to use now.
786 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
787 final int N = attachInfo.mScrollContainers.size();
788 for (int i=0; i<N; i++) {
789 if (attachInfo.mScrollContainers.get(i).isShown()) {
790 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
791 }
792 }
793 if (resizeMode == 0) {
794 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
795 }
796 if ((lp.softInputMode &
797 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
798 lp.softInputMode = (lp.softInputMode &
799 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
800 resizeMode;
801 params = lp;
802 }
803 }
804 }
Romain Guy8506ab42009-06-11 17:35:47 -0700805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
807 if (!PixelFormat.formatHasAlpha(params.format)) {
808 params.format = PixelFormat.TRANSLUCENT;
809 }
810 }
811
812 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
813 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
814
815 final boolean computesInternalInsets =
816 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
817 boolean insetsPending = false;
818 int relayoutResult = 0;
819 if (mFirst || windowShouldResize || insetsChanged
820 || viewVisibilityChanged || params != null) {
821
822 if (viewVisibility == View.VISIBLE) {
823 // If this window is giving internal insets to the window
824 // manager, and it is being added or changing its visibility,
825 // then we want to first give the window manager "fake"
826 // insets to cause it to effectively ignore the content of
827 // the window during layout. This avoids it briefly causing
828 // other windows to resize/move based on the raw frame of the
829 // window, waiting until we can finish laying out this window
830 // and get back to the window manager with the ultimately
831 // computed insets.
832 insetsPending = computesInternalInsets
833 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
836 if (params == null) {
837 params = mWindowAttributes;
838 }
839 mGlWanted = true;
840 }
841 }
842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 boolean initialized = false;
844 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700845 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 try {
847 boolean hadSurface = mSurface.isValid();
848 int fl = 0;
849 if (params != null) {
850 fl = params.flags;
851 if (attachInfo.mKeepScreenOn) {
852 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
853 }
854 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700855 if (DEBUG_LAYOUT) {
856 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
857 host.mMeasuredHeight + ", params=" + params);
858 }
859 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 if (params != null) {
862 params.flags = fl;
863 }
864
865 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
866 + " content=" + mPendingContentInsets.toShortString()
867 + " visible=" + mPendingVisibleInsets.toShortString()
868 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 contentInsetsChanged = !mPendingContentInsets.equals(
871 mAttachInfo.mContentInsets);
872 visibleInsetsChanged = !mPendingVisibleInsets.equals(
873 mAttachInfo.mVisibleInsets);
874 if (contentInsetsChanged) {
875 mAttachInfo.mContentInsets.set(mPendingContentInsets);
876 host.fitSystemWindows(mAttachInfo.mContentInsets);
877 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
878 + mAttachInfo.mContentInsets);
879 }
880 if (visibleInsetsChanged) {
881 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
882 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
883 + mAttachInfo.mVisibleInsets);
884 }
885
886 if (!hadSurface) {
887 if (mSurface.isValid()) {
888 // If we are creating a new surface, then we need to
889 // completely redraw it. Also, when we get to the
890 // point of drawing it we will hold off and schedule
891 // a new traversal instead. This is so we can tell the
892 // window manager about all of the windows being displayed
893 // before actually drawing them, so it can display then
894 // all at once.
895 newSurface = true;
896 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 if (mGlWanted && !mUseGL) {
899 initializeGL();
900 initialized = mGlCanvas != null;
901 }
902 }
903 } else if (!mSurface.isValid()) {
904 // If the surface has been removed, then reset the scroll
905 // positions.
906 mLastScrolledFocus = null;
907 mScrollY = mCurScrollY = 0;
908 if (mScroller != null) {
909 mScroller.abortAnimation();
910 }
911 }
912 } catch (RemoteException e) {
913 }
914 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700915 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916
917 attachInfo.mWindowLeft = frame.left;
918 attachInfo.mWindowTop = frame.top;
919
920 // !!FIXME!! This next section handles the case where we did not get the
921 // window size we asked for. We should avoid this by getting a maximum size from
922 // the window session beforehand.
923 mWidth = frame.width();
924 mHeight = frame.height();
925
926 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -0700927 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
928 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930
931 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
932 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
933 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
934 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
935 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
936 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
937
938 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
939 + mWidth + " measuredWidth=" + host.mMeasuredWidth
940 + " mHeight=" + mHeight
941 + " measuredHeight" + host.mMeasuredHeight
942 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 // Ask host how big it wants to be
945 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
946
947 // Implementation of weights from WindowManager.LayoutParams
948 // We just grow the dimensions as needed and re-measure if
949 // needs be
950 int width = host.mMeasuredWidth;
951 int height = host.mMeasuredHeight;
952 boolean measureAgain = false;
953
954 if (lp.horizontalWeight > 0.0f) {
955 width += (int) ((mWidth - width) * lp.horizontalWeight);
956 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
957 MeasureSpec.EXACTLY);
958 measureAgain = true;
959 }
960 if (lp.verticalWeight > 0.0f) {
961 height += (int) ((mHeight - height) * lp.verticalWeight);
962 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
963 MeasureSpec.EXACTLY);
964 measureAgain = true;
965 }
966
967 if (measureAgain) {
968 if (DEBUG_LAYOUT) Log.v(TAG,
969 "And hey let's measure once more: width=" + width
970 + " height=" + height);
971 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
972 }
973
974 mLayoutRequested = true;
975 }
976 }
977
978 final boolean didLayout = mLayoutRequested;
979 boolean triggerGlobalLayoutListener = didLayout
980 || attachInfo.mRecomputeGlobalAttributes;
981 if (didLayout) {
982 mLayoutRequested = false;
983 mScrollMayChange = true;
984 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
985 "ViewRoot", "Laying out " + host + " to (" +
986 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700987 long startTime = 0L;
988 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 startTime = SystemClock.elapsedRealtime();
990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
992
Romain Guy13922e02009-05-12 17:56:14 -0700993 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
994 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
995 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
996 + "please refer to the logs with the tag "
997 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
998 }
999 }
1000
1001 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1003 }
1004
1005 // By this point all views have been sized and positionned
1006 // We can compute the transparent area
1007
1008 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1009 // start out transparent
1010 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1011 host.getLocationInWindow(mTmpLocation);
1012 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1013 mTmpLocation[0] + host.mRight - host.mLeft,
1014 mTmpLocation[1] + host.mBottom - host.mTop);
1015
1016 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001017 if (mTranslator != null) {
1018 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1019 }
1020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1022 mPreviousTransparentRegion.set(mTransparentRegion);
1023 // reconfigure window manager
1024 try {
1025 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1026 } catch (RemoteException e) {
1027 }
1028 }
1029 }
1030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (DBG) {
1032 System.out.println("======================================");
1033 System.out.println("performTraversals -- after setFrame");
1034 host.debug();
1035 }
1036 }
1037
1038 if (triggerGlobalLayoutListener) {
1039 attachInfo.mRecomputeGlobalAttributes = false;
1040 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1041 }
1042
1043 if (computesInternalInsets) {
1044 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1045 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1046 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1047 givenContent.left = givenContent.top = givenContent.right
1048 = givenContent.bottom = givenVisible.left = givenVisible.top
1049 = givenVisible.right = givenVisible.bottom = 0;
1050 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001051 Rect contentInsets = insets.contentInsets;
1052 Rect visibleInsets = insets.visibleInsets;
1053 if (mTranslator != null) {
1054 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1055 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1058 mLastGivenInsets.set(insets);
1059 try {
1060 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001061 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 } catch (RemoteException e) {
1063 }
1064 }
1065 }
Romain Guy8506ab42009-06-11 17:35:47 -07001066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 if (mFirst) {
1068 // handle first focus request
1069 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1070 + mView.hasFocus());
1071 if (mView != null) {
1072 if (!mView.hasFocus()) {
1073 mView.requestFocus(View.FOCUS_FORWARD);
1074 mFocusedView = mRealFocusedView = mView.findFocus();
1075 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1076 + mFocusedView);
1077 } else {
1078 mRealFocusedView = mView.findFocus();
1079 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1080 + mRealFocusedView);
1081 }
1082 }
1083 }
1084
1085 mFirst = false;
1086 mWillDrawSoon = false;
1087 mNewSurfaceNeeded = false;
1088 mViewVisibility = viewVisibility;
1089
1090 if (mAttachInfo.mHasWindowFocus) {
1091 final boolean imTarget = WindowManager.LayoutParams
1092 .mayUseInputMethod(mWindowAttributes.flags);
1093 if (imTarget != mLastWasImTarget) {
1094 mLastWasImTarget = imTarget;
1095 InputMethodManager imm = InputMethodManager.peekInstance();
1096 if (imm != null && imTarget) {
1097 imm.startGettingWindowFocus(mView);
1098 imm.onWindowFocus(mView, mView.findFocus(),
1099 mWindowAttributes.softInputMode,
1100 !mHasHadWindowFocus, mWindowAttributes.flags);
1101 }
1102 }
1103 }
Romain Guy8506ab42009-06-11 17:35:47 -07001104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1106
1107 if (!cancelDraw && !newSurface) {
1108 mFullRedrawNeeded = false;
1109 draw(fullRedrawNeeded);
1110
1111 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1112 || mReportNextDraw) {
1113 if (LOCAL_LOGV) {
1114 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1115 }
1116 mReportNextDraw = false;
1117 try {
1118 sWindowSession.finishDrawing(mWindow);
1119 } catch (RemoteException e) {
1120 }
1121 }
1122 } else {
1123 // We were supposed to report when we are done drawing. Since we canceled the
1124 // draw, remember it here.
1125 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1126 mReportNextDraw = true;
1127 }
1128 if (fullRedrawNeeded) {
1129 mFullRedrawNeeded = true;
1130 }
1131 // Try again
1132 scheduleTraversals();
1133 }
1134 }
1135
1136 public void requestTransparentRegion(View child) {
1137 // the test below should not fail unless someone is messing with us
1138 checkThread();
1139 if (mView == child) {
1140 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1141 // Need to make sure we re-evaluate the window attributes next
1142 // time around, to ensure the window has the correct format.
1143 mWindowAttributesChanged = true;
1144 }
1145 }
1146
1147 /**
1148 * Figures out the measure spec for the root view in a window based on it's
1149 * layout params.
1150 *
1151 * @param windowSize
1152 * The available width or height of the window
1153 *
1154 * @param rootDimension
1155 * The layout params for one dimension (width or height) of the
1156 * window.
1157 *
1158 * @return The measure spec to use to measure the root view.
1159 */
1160 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1161 int measureSpec;
1162 switch (rootDimension) {
1163
1164 case ViewGroup.LayoutParams.FILL_PARENT:
1165 // Window can't resize. Force root view to be windowSize.
1166 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1167 break;
1168 case ViewGroup.LayoutParams.WRAP_CONTENT:
1169 // Window can resize. Set max size for root view.
1170 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1171 break;
1172 default:
1173 // Window wants to be an exact size. Force root view to be that size.
1174 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1175 break;
1176 }
1177 return measureSpec;
1178 }
1179
1180 private void draw(boolean fullRedrawNeeded) {
1181 Surface surface = mSurface;
1182 if (surface == null || !surface.isValid()) {
1183 return;
1184 }
1185
1186 scrollToRectOrFocus(null, false);
1187
1188 if (mAttachInfo.mViewScrollChanged) {
1189 mAttachInfo.mViewScrollChanged = false;
1190 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1191 }
Romain Guy8506ab42009-06-11 17:35:47 -07001192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001194 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 if (scrolling) {
1196 yoff = mScroller.getCurrY();
1197 } else {
1198 yoff = mScrollY;
1199 }
1200 if (mCurScrollY != yoff) {
1201 mCurScrollY = yoff;
1202 fullRedrawNeeded = true;
1203 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001204 float appScale = mAttachInfo.mApplicationScale;
1205 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206
1207 Rect dirty = mDirty;
1208 if (mUseGL) {
1209 if (!dirty.isEmpty()) {
1210 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001211 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 mGL.glDisable(GL_SCISSOR_TEST);
1213 mGL.glClearColor(0, 0, 0, 0);
1214 mGL.glClear(GL_COLOR_BUFFER_BIT);
1215 mGL.glEnable(GL_SCISSOR_TEST);
1216
1217 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001218 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001220
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001221 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1222 try {
1223 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001224 if (mTranslator != null) {
1225 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001226 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001227 canvas.setScreenDensity(scalingRequired
1228 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001229 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001230 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1231 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1232 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001233 } finally {
1234 canvas.restoreToCount(saveCount);
1235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236
Romain Guy5bcdff42009-05-14 21:27:18 -07001237 mAttachInfo.mIgnoreDirtyState = false;
1238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1240 checkEglErrors();
1241
Romain Guy13922e02009-05-12 17:56:14 -07001242 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 int now = (int)SystemClock.elapsedRealtime();
1244 if (sDrawTime != 0) {
1245 nativeShowFPS(canvas, now - sDrawTime);
1246 }
1247 sDrawTime = now;
1248 }
1249 }
1250 }
1251 if (scrolling) {
1252 mFullRedrawNeeded = true;
1253 scheduleTraversals();
1254 }
1255 return;
1256 }
1257
Romain Guy5bcdff42009-05-14 21:27:18 -07001258 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001259 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001260 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262
1263 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1264 Log.v("ViewRoot", "Draw " + mView + "/"
1265 + mWindowAttributes.getTitle()
1266 + ": dirty={" + dirty.left + "," + dirty.top
1267 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001268 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1269 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271
1272 Canvas canvas;
1273 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001274 int left = dirty.left;
1275 int top = dirty.top;
1276 int right = dirty.right;
1277 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001279
1280 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1281 bottom != dirty.bottom) {
1282 mAttachInfo.mIgnoreDirtyState = true;
1283 }
1284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 // TODO: Do this in native
Dianne Hackborn11ea3342009-07-22 21:48:55 -07001286 canvas.setDensity(mDensity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 } catch (Surface.OutOfResourcesException e) {
1288 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1289 // TODO: we should ask the window manager to do something!
1290 // for now we just do nothing
1291 return;
1292 }
1293
1294 try {
Romain Guybb93d552009-03-24 21:04:15 -07001295 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001296 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297
1298 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1299 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1300 + canvas.getWidth() + ", h=" + canvas.getHeight());
1301 //canvas.drawARGB(255, 255, 0, 0);
1302 }
1303
Romain Guy13922e02009-05-12 17:56:14 -07001304 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 startTime = SystemClock.elapsedRealtime();
1306 }
1307
1308 // If this bitmap's format includes an alpha channel, we
1309 // need to clear it before drawing so that the child will
1310 // properly re-composite its drawing on a transparent
1311 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001312 // or
1313 // If we are applying an offset, we need to clear the area
1314 // where the offset doesn't appear to avoid having garbage
1315 // left in the blank areas.
1316 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1318 }
1319
1320 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001321 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001323 mView.mPrivateFlags |= View.DRAWN;
1324
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001325 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001326 Context cxt = mView.getContext();
1327 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -07001328 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1329 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001330 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001331 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001332 try {
1333 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001334 if (mTranslator != null) {
1335 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001336 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001337 canvas.setScreenDensity(scalingRequired
1338 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001339 mView.draw(canvas);
1340 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001341 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001342 canvas.restoreToCount(saveCount);
1343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344
Romain Guy5bcdff42009-05-14 21:27:18 -07001345 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1346 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1347 }
1348
Romain Guy13922e02009-05-12 17:56:14 -07001349 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 int now = (int)SystemClock.elapsedRealtime();
1351 if (sDrawTime != 0) {
1352 nativeShowFPS(canvas, now - sDrawTime);
1353 }
1354 sDrawTime = now;
1355 }
1356
Romain Guy13922e02009-05-12 17:56:14 -07001357 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1359 }
1360 }
Romain Guy8506ab42009-06-11 17:35:47 -07001361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 } finally {
1363 surface.unlockCanvasAndPost(canvas);
1364 }
1365
1366 if (LOCAL_LOGV) {
1367 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1368 }
Romain Guy8506ab42009-06-11 17:35:47 -07001369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 if (scrolling) {
1371 mFullRedrawNeeded = true;
1372 scheduleTraversals();
1373 }
1374 }
1375
1376 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1377 final View.AttachInfo attachInfo = mAttachInfo;
1378 final Rect ci = attachInfo.mContentInsets;
1379 final Rect vi = attachInfo.mVisibleInsets;
1380 int scrollY = 0;
1381 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 if (vi.left > ci.left || vi.top > ci.top
1384 || vi.right > ci.right || vi.bottom > ci.bottom) {
1385 // We'll assume that we aren't going to change the scroll
1386 // offset, since we want to avoid that unless it is actually
1387 // going to make the focus visible... otherwise we scroll
1388 // all over the place.
1389 scrollY = mScrollY;
1390 // We can be called for two different situations: during a draw,
1391 // to update the scroll position if the focus has changed (in which
1392 // case 'rectangle' is null), or in response to a
1393 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1394 // is non-null and we just want to scroll to whatever that
1395 // rectangle is).
1396 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001397
1398 // When in touch mode, focus points to the previously focused view,
1399 // which may have been removed from the view hierarchy. The following
1400 // line checks whether the view is still in the hierarchy
1401 if (focus == null || focus.getParent() == null) {
1402 mRealFocusedView = null;
1403 return false;
1404 }
1405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 if (focus != mLastScrolledFocus) {
1407 // If the focus has changed, then ignore any requests to scroll
1408 // to a rectangle; first we want to make sure the entire focus
1409 // view is visible.
1410 rectangle = null;
1411 }
1412 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1413 + " rectangle=" + rectangle + " ci=" + ci
1414 + " vi=" + vi);
1415 if (focus == mLastScrolledFocus && !mScrollMayChange
1416 && rectangle == null) {
1417 // Optimization: if the focus hasn't changed since last
1418 // time, and no layout has happened, then just leave things
1419 // as they are.
1420 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1421 + mScrollY + " vi=" + vi.toShortString());
1422 } else if (focus != null) {
1423 // We need to determine if the currently focused view is
1424 // within the visible part of the window and, if not, apply
1425 // a pan so it can be seen.
1426 mLastScrolledFocus = focus;
1427 mScrollMayChange = false;
1428 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1429 // Try to find the rectangle from the focus view.
1430 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1431 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1432 + mView.getWidth() + " h=" + mView.getHeight()
1433 + " ci=" + ci.toShortString()
1434 + " vi=" + vi.toShortString());
1435 if (rectangle == null) {
1436 focus.getFocusedRect(mTempRect);
1437 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1438 + ": focusRect=" + mTempRect.toShortString());
1439 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1440 focus, mTempRect);
1441 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1442 "Focus in window: focusRect="
1443 + mTempRect.toShortString()
1444 + " visRect=" + mVisRect.toShortString());
1445 } else {
1446 mTempRect.set(rectangle);
1447 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1448 "Request scroll to rect: "
1449 + mTempRect.toShortString()
1450 + " visRect=" + mVisRect.toShortString());
1451 }
1452 if (mTempRect.intersect(mVisRect)) {
1453 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1454 "Focus window visible rect: "
1455 + mTempRect.toShortString());
1456 if (mTempRect.height() >
1457 (mView.getHeight()-vi.top-vi.bottom)) {
1458 // If the focus simply is not going to fit, then
1459 // best is probably just to leave things as-is.
1460 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1461 "Too tall; leaving scrollY=" + scrollY);
1462 } else if ((mTempRect.top-scrollY) < vi.top) {
1463 scrollY -= vi.top - (mTempRect.top-scrollY);
1464 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1465 "Top covered; scrollY=" + scrollY);
1466 } else if ((mTempRect.bottom-scrollY)
1467 > (mView.getHeight()-vi.bottom)) {
1468 scrollY += (mTempRect.bottom-scrollY)
1469 - (mView.getHeight()-vi.bottom);
1470 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1471 "Bottom covered; scrollY=" + scrollY);
1472 }
1473 handled = true;
1474 }
1475 }
1476 }
1477 }
Romain Guy8506ab42009-06-11 17:35:47 -07001478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 if (scrollY != mScrollY) {
1480 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1481 + mScrollY + " , new=" + scrollY);
1482 if (!immediate) {
1483 if (mScroller == null) {
1484 mScroller = new Scroller(mView.getContext());
1485 }
1486 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1487 } else if (mScroller != null) {
1488 mScroller.abortAnimation();
1489 }
1490 mScrollY = scrollY;
1491 }
Romain Guy8506ab42009-06-11 17:35:47 -07001492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 return handled;
1494 }
Romain Guy8506ab42009-06-11 17:35:47 -07001495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 public void requestChildFocus(View child, View focused) {
1497 checkThread();
1498 if (mFocusedView != focused) {
1499 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1500 scheduleTraversals();
1501 }
1502 mFocusedView = mRealFocusedView = focused;
1503 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1504 + mFocusedView);
1505 }
1506
1507 public void clearChildFocus(View child) {
1508 checkThread();
1509
1510 View oldFocus = mFocusedView;
1511
1512 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1513 mFocusedView = mRealFocusedView = null;
1514 if (mView != null && !mView.hasFocus()) {
1515 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1516 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1517 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1518 }
1519 } else if (oldFocus != null) {
1520 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1521 }
1522 }
1523
1524
1525 public void focusableViewAvailable(View v) {
1526 checkThread();
1527
1528 if (mView != null && !mView.hasFocus()) {
1529 v.requestFocus();
1530 } else {
1531 // the one case where will transfer focus away from the current one
1532 // is if the current view is a view group that prefers to give focus
1533 // to its children first AND the view is a descendant of it.
1534 mFocusedView = mView.findFocus();
1535 boolean descendantsHaveDibsOnFocus =
1536 (mFocusedView instanceof ViewGroup) &&
1537 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1538 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1539 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1540 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1541 v.requestFocus();
1542 }
1543 }
1544 }
1545
1546 public void recomputeViewAttributes(View child) {
1547 checkThread();
1548 if (mView == child) {
1549 mAttachInfo.mRecomputeGlobalAttributes = true;
1550 if (!mWillDrawSoon) {
1551 scheduleTraversals();
1552 }
1553 }
1554 }
1555
1556 void dispatchDetachedFromWindow() {
1557 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1558
1559 if (mView != null) {
1560 mView.dispatchDetachedFromWindow();
1561 }
1562
1563 mView = null;
1564 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001565 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566
1567 if (mUseGL) {
1568 destroyGL();
1569 }
Mathias Agopian5583dc62009-07-09 16:28:11 -07001570 mSurface.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571
1572 try {
1573 sWindowSession.remove(mWindow);
1574 } catch (RemoteException e) {
1575 }
1576 }
Romain Guy8506ab42009-06-11 17:35:47 -07001577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 /**
1579 * Return true if child is an ancestor of parent, (or equal to the parent).
1580 */
1581 private static boolean isViewDescendantOf(View child, View parent) {
1582 if (child == parent) {
1583 return true;
1584 }
1585
1586 final ViewParent theParent = child.getParent();
1587 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1588 }
1589
1590
1591 public final static int DO_TRAVERSAL = 1000;
1592 public final static int DIE = 1001;
1593 public final static int RESIZED = 1002;
1594 public final static int RESIZED_REPORT = 1003;
1595 public final static int WINDOW_FOCUS_CHANGED = 1004;
1596 public final static int DISPATCH_KEY = 1005;
1597 public final static int DISPATCH_POINTER = 1006;
1598 public final static int DISPATCH_TRACKBALL = 1007;
1599 public final static int DISPATCH_APP_VISIBILITY = 1008;
1600 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1601 public final static int FINISHED_EVENT = 1010;
1602 public final static int DISPATCH_KEY_FROM_IME = 1011;
1603 public final static int FINISH_INPUT_CONNECTION = 1012;
1604 public final static int CHECK_FOCUS = 1013;
1605
1606 @Override
1607 public void handleMessage(Message msg) {
1608 switch (msg.what) {
1609 case View.AttachInfo.INVALIDATE_MSG:
1610 ((View) msg.obj).invalidate();
1611 break;
1612 case View.AttachInfo.INVALIDATE_RECT_MSG:
1613 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1614 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1615 info.release();
1616 break;
1617 case DO_TRAVERSAL:
1618 if (mProfile) {
1619 Debug.startMethodTracing("ViewRoot");
1620 }
1621
1622 performTraversals();
1623
1624 if (mProfile) {
1625 Debug.stopMethodTracing();
1626 mProfile = false;
1627 }
1628 break;
1629 case FINISHED_EVENT:
1630 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1631 break;
1632 case DISPATCH_KEY:
1633 if (LOCAL_LOGV) Log.v(
1634 "ViewRoot", "Dispatching key "
1635 + msg.obj + " to " + mView);
1636 deliverKeyEvent((KeyEvent)msg.obj, true);
1637 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001638 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 MotionEvent event = (MotionEvent)msg.obj;
1640
1641 boolean didFinish;
1642 if (event == null) {
1643 try {
Michael Chan53071d62009-05-13 17:29:48 -07001644 long timeBeforeGettingEvents;
1645 if (MEASURE_LATENCY) {
1646 timeBeforeGettingEvents = System.nanoTime();
1647 }
1648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001650
1651 if (MEASURE_LATENCY && event != null) {
1652 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1653 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 } catch (RemoteException e) {
1656 }
1657 didFinish = true;
1658 } else {
1659 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
1660 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001661 if (event != null && mTranslator != null) {
1662 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 try {
1665 boolean handled;
1666 if (mView != null && mAdded && event != null) {
1667
1668 // enter touch mode on the down
1669 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1670 if (isDown) {
1671 ensureTouchMode(true);
1672 }
1673 if(Config.LOGV) {
1674 captureMotionLog("captureDispatchPointer", event);
1675 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001676 if (mCurScrollY != 0) {
1677 event.offsetLocation(0, mCurScrollY);
1678 }
Michael Chan53071d62009-05-13 17:29:48 -07001679 if (MEASURE_LATENCY) {
1680 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001683 if (MEASURE_LATENCY) {
1684 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 if (!handled && isDown) {
1687 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1688
1689 final int edgeFlags = event.getEdgeFlags();
1690 int direction = View.FOCUS_UP;
1691 int x = (int)event.getX();
1692 int y = (int)event.getY();
1693 final int[] deltas = new int[2];
1694
1695 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1696 direction = View.FOCUS_DOWN;
1697 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1698 deltas[0] = edgeSlop;
1699 x += edgeSlop;
1700 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1701 deltas[0] = -edgeSlop;
1702 x -= edgeSlop;
1703 }
1704 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1705 direction = View.FOCUS_UP;
1706 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1707 deltas[0] = edgeSlop;
1708 x += edgeSlop;
1709 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1710 deltas[0] = -edgeSlop;
1711 x -= edgeSlop;
1712 }
1713 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1714 direction = View.FOCUS_RIGHT;
1715 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1716 direction = View.FOCUS_LEFT;
1717 }
1718
1719 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1720 View nearest = FocusFinder.getInstance().findNearestTouchable(
1721 ((ViewGroup) mView), x, y, direction, deltas);
1722 if (nearest != null) {
1723 event.offsetLocation(deltas[0], deltas[1]);
1724 event.setEdgeFlags(0);
1725 mView.dispatchTouchEvent(event);
1726 }
1727 }
1728 }
1729 }
1730 } finally {
1731 if (!didFinish) {
1732 try {
1733 sWindowSession.finishKey(mWindow);
1734 } catch (RemoteException e) {
1735 }
1736 }
1737 if (event != null) {
1738 event.recycle();
1739 }
1740 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1741 // Let the exception fall through -- the looper will catch
1742 // it and take care of the bad app for us.
1743 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001744 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 case DISPATCH_TRACKBALL:
1746 deliverTrackballEvent((MotionEvent)msg.obj);
1747 break;
1748 case DISPATCH_APP_VISIBILITY:
1749 handleAppVisibility(msg.arg1 != 0);
1750 break;
1751 case DISPATCH_GET_NEW_SURFACE:
1752 handleGetNewSurface();
1753 break;
1754 case RESIZED:
1755 Rect coveredInsets = ((Rect[])msg.obj)[0];
1756 Rect visibleInsets = ((Rect[])msg.obj)[1];
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1759 && mPendingContentInsets.equals(coveredInsets)
1760 && mPendingVisibleInsets.equals(visibleInsets)) {
1761 break;
1762 }
1763 // fall through...
1764 case RESIZED_REPORT:
1765 if (mAdded) {
1766 mWinFrame.left = 0;
1767 mWinFrame.right = msg.arg1;
1768 mWinFrame.top = 0;
1769 mWinFrame.bottom = msg.arg2;
1770 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1771 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1772 if (msg.what == RESIZED_REPORT) {
1773 mReportNextDraw = true;
1774 }
1775 requestLayout();
1776 }
1777 break;
1778 case WINDOW_FOCUS_CHANGED: {
1779 if (mAdded) {
1780 boolean hasWindowFocus = msg.arg1 != 0;
1781 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1782 if (hasWindowFocus) {
1783 boolean inTouchMode = msg.arg2 != 0;
1784 ensureTouchModeLocally(inTouchMode);
1785
1786 if (mGlWanted) {
1787 checkEglErrors();
1788 // we lost the gl context, so recreate it.
1789 if (mGlWanted && !mUseGL) {
1790 initializeGL();
1791 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001792 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001793 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001794 (int) (mWidth * appScale + 0.5f),
1795 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 }
1798 }
1799 }
Romain Guy8506ab42009-06-11 17:35:47 -07001800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 mLastWasImTarget = WindowManager.LayoutParams
1802 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 InputMethodManager imm = InputMethodManager.peekInstance();
1805 if (mView != null) {
1806 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1807 imm.startGettingWindowFocus(mView);
1808 }
1809 mView.dispatchWindowFocusChanged(hasWindowFocus);
1810 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 // Note: must be done after the focus change callbacks,
1813 // so all of the view state is set up correctly.
1814 if (hasWindowFocus) {
1815 if (imm != null && mLastWasImTarget) {
1816 imm.onWindowFocus(mView, mView.findFocus(),
1817 mWindowAttributes.softInputMode,
1818 !mHasHadWindowFocus, mWindowAttributes.flags);
1819 }
1820 // Clear the forward bit. We can just do this directly, since
1821 // the window manager doesn't care about it.
1822 mWindowAttributes.softInputMode &=
1823 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1824 ((WindowManager.LayoutParams)mView.getLayoutParams())
1825 .softInputMode &=
1826 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1827 mHasHadWindowFocus = true;
1828 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001829
1830 if (hasWindowFocus && mView != null) {
1831 sendAccessibilityEvents();
1832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834 } break;
1835 case DIE:
1836 dispatchDetachedFromWindow();
1837 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001838 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 if (LOCAL_LOGV) Log.v(
1840 "ViewRoot", "Dispatching key "
1841 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001842 KeyEvent event = (KeyEvent)msg.obj;
1843 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1844 // The IME is trying to say this event is from the
1845 // system! Bad bad bad!
1846 event = KeyEvent.changeFlags(event,
1847 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001850 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 case FINISH_INPUT_CONNECTION: {
1852 InputMethodManager imm = InputMethodManager.peekInstance();
1853 if (imm != null) {
1854 imm.reportFinishInputConnection((InputConnection)msg.obj);
1855 }
1856 } break;
1857 case CHECK_FOCUS: {
1858 InputMethodManager imm = InputMethodManager.peekInstance();
1859 if (imm != null) {
1860 imm.checkFocus();
1861 }
1862 } break;
1863 }
1864 }
1865
1866 /**
1867 * Something in the current window tells us we need to change the touch mode. For
1868 * example, we are not in touch mode, and the user touches the screen.
1869 *
1870 * If the touch mode has changed, tell the window manager, and handle it locally.
1871 *
1872 * @param inTouchMode Whether we want to be in touch mode.
1873 * @return True if the touch mode changed and focus changed was changed as a result
1874 */
1875 boolean ensureTouchMode(boolean inTouchMode) {
1876 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1877 + "touch mode is " + mAttachInfo.mInTouchMode);
1878 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1879
1880 // tell the window manager
1881 try {
1882 sWindowSession.setInTouchMode(inTouchMode);
1883 } catch (RemoteException e) {
1884 throw new RuntimeException(e);
1885 }
1886
1887 // handle the change
1888 return ensureTouchModeLocally(inTouchMode);
1889 }
1890
1891 /**
1892 * Ensure that the touch mode for this window is set, and if it is changing,
1893 * take the appropriate action.
1894 * @param inTouchMode Whether we want to be in touch mode.
1895 * @return True if the touch mode changed and focus changed was changed as a result
1896 */
1897 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1898 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1899 + "touch mode is " + mAttachInfo.mInTouchMode);
1900
1901 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1902
1903 mAttachInfo.mInTouchMode = inTouchMode;
1904 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1905
1906 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1907 }
1908
1909 private boolean enterTouchMode() {
1910 if (mView != null) {
1911 if (mView.hasFocus()) {
1912 // note: not relying on mFocusedView here because this could
1913 // be when the window is first being added, and mFocused isn't
1914 // set yet.
1915 final View focused = mView.findFocus();
1916 if (focused != null && !focused.isFocusableInTouchMode()) {
1917
1918 final ViewGroup ancestorToTakeFocus =
1919 findAncestorToTakeFocusInTouchMode(focused);
1920 if (ancestorToTakeFocus != null) {
1921 // there is an ancestor that wants focus after its descendants that
1922 // is focusable in touch mode.. give it focus
1923 return ancestorToTakeFocus.requestFocus();
1924 } else {
1925 // nothing appropriate to have focus in touch mode, clear it out
1926 mView.unFocus();
1927 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1928 mFocusedView = null;
1929 return true;
1930 }
1931 }
1932 }
1933 }
1934 return false;
1935 }
1936
1937
1938 /**
1939 * Find an ancestor of focused that wants focus after its descendants and is
1940 * focusable in touch mode.
1941 * @param focused The currently focused view.
1942 * @return An appropriate view, or null if no such view exists.
1943 */
1944 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1945 ViewParent parent = focused.getParent();
1946 while (parent instanceof ViewGroup) {
1947 final ViewGroup vgParent = (ViewGroup) parent;
1948 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1949 && vgParent.isFocusableInTouchMode()) {
1950 return vgParent;
1951 }
1952 if (vgParent.isRootNamespace()) {
1953 return null;
1954 } else {
1955 parent = vgParent.getParent();
1956 }
1957 }
1958 return null;
1959 }
1960
1961 private boolean leaveTouchMode() {
1962 if (mView != null) {
1963 if (mView.hasFocus()) {
1964 // i learned the hard way to not trust mFocusedView :)
1965 mFocusedView = mView.findFocus();
1966 if (!(mFocusedView instanceof ViewGroup)) {
1967 // some view has focus, let it keep it
1968 return false;
1969 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1970 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1971 // some view group has focus, and doesn't prefer its children
1972 // over itself for focus, so let them keep it.
1973 return false;
1974 }
1975 }
1976
1977 // find the best view to give focus to in this brave new non-touch-mode
1978 // world
1979 final View focused = focusSearch(null, View.FOCUS_DOWN);
1980 if (focused != null) {
1981 return focused.requestFocus(View.FOCUS_DOWN);
1982 }
1983 }
1984 return false;
1985 }
1986
1987
1988 private void deliverTrackballEvent(MotionEvent event) {
1989 boolean didFinish;
1990 if (event == null) {
1991 try {
1992 event = sWindowSession.getPendingTrackballMove(mWindow);
1993 } catch (RemoteException e) {
1994 }
1995 didFinish = true;
1996 } else {
1997 didFinish = false;
1998 }
1999
2000 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2001
2002 boolean handled = false;
2003 try {
2004 if (event == null) {
2005 handled = true;
2006 } else if (mView != null && mAdded) {
2007 handled = mView.dispatchTrackballEvent(event);
2008 if (!handled) {
2009 // we could do something here, like changing the focus
2010 // or something?
2011 }
2012 }
2013 } finally {
2014 if (handled) {
2015 if (!didFinish) {
2016 try {
2017 sWindowSession.finishKey(mWindow);
2018 } catch (RemoteException e) {
2019 }
2020 }
2021 if (event != null) {
2022 event.recycle();
2023 }
2024 // If we reach this, we delivered a trackball event to mView and
2025 // mView consumed it. Because we will not translate the trackball
2026 // event into a key event, touch mode will not exit, so we exit
2027 // touch mode here.
2028 ensureTouchMode(false);
2029 //noinspection ReturnInsideFinallyBlock
2030 return;
2031 }
2032 // Let the exception fall through -- the looper will catch
2033 // it and take care of the bad app for us.
2034 }
2035
2036 final TrackballAxis x = mTrackballAxisX;
2037 final TrackballAxis y = mTrackballAxisY;
2038
2039 long curTime = SystemClock.uptimeMillis();
2040 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2041 // It has been too long since the last movement,
2042 // so restart at the beginning.
2043 x.reset(0);
2044 y.reset(0);
2045 mLastTrackballTime = curTime;
2046 }
2047
2048 try {
2049 final int action = event.getAction();
2050 final int metastate = event.getMetaState();
2051 switch (action) {
2052 case MotionEvent.ACTION_DOWN:
2053 x.reset(2);
2054 y.reset(2);
2055 deliverKeyEvent(new KeyEvent(curTime, curTime,
2056 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2057 0, metastate), false);
2058 break;
2059 case MotionEvent.ACTION_UP:
2060 x.reset(2);
2061 y.reset(2);
2062 deliverKeyEvent(new KeyEvent(curTime, curTime,
2063 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2064 0, metastate), false);
2065 break;
2066 }
2067
2068 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2069 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2070 + " move=" + event.getX()
2071 + " / Y=" + y.position + " step="
2072 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2073 + " move=" + event.getY());
2074 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2075 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2076
2077 // Generate DPAD events based on the trackball movement.
2078 // We pick the axis that has moved the most as the direction of
2079 // the DPAD. When we generate DPAD events for one axis, then the
2080 // other axis is reset -- we don't want to perform DPAD jumps due
2081 // to slight movements in the trackball when making major movements
2082 // along the other axis.
2083 int keycode = 0;
2084 int movement = 0;
2085 float accel = 1;
2086 if (xOff > yOff) {
2087 movement = x.generate((2/event.getXPrecision()));
2088 if (movement != 0) {
2089 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2090 : KeyEvent.KEYCODE_DPAD_LEFT;
2091 accel = x.acceleration;
2092 y.reset(2);
2093 }
2094 } else if (yOff > 0) {
2095 movement = y.generate((2/event.getYPrecision()));
2096 if (movement != 0) {
2097 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2098 : KeyEvent.KEYCODE_DPAD_UP;
2099 accel = y.acceleration;
2100 x.reset(2);
2101 }
2102 }
2103
2104 if (keycode != 0) {
2105 if (movement < 0) movement = -movement;
2106 int accelMovement = (int)(movement * accel);
2107 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2108 + " accelMovement=" + accelMovement
2109 + " accel=" + accel);
2110 if (accelMovement > movement) {
2111 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2112 + keycode);
2113 movement--;
2114 deliverKeyEvent(new KeyEvent(curTime, curTime,
2115 KeyEvent.ACTION_MULTIPLE, keycode,
2116 accelMovement-movement, metastate), false);
2117 }
2118 while (movement > 0) {
2119 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2120 + keycode);
2121 movement--;
2122 curTime = SystemClock.uptimeMillis();
2123 deliverKeyEvent(new KeyEvent(curTime, curTime,
2124 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2125 deliverKeyEvent(new KeyEvent(curTime, curTime,
2126 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2127 }
2128 mLastTrackballTime = curTime;
2129 }
2130 } finally {
2131 if (!didFinish) {
2132 try {
2133 sWindowSession.finishKey(mWindow);
2134 } catch (RemoteException e) {
2135 }
2136 if (event != null) {
2137 event.recycle();
2138 }
2139 }
2140 // Let the exception fall through -- the looper will catch
2141 // it and take care of the bad app for us.
2142 }
2143 }
2144
2145 /**
2146 * @param keyCode The key code
2147 * @return True if the key is directional.
2148 */
2149 static boolean isDirectional(int keyCode) {
2150 switch (keyCode) {
2151 case KeyEvent.KEYCODE_DPAD_LEFT:
2152 case KeyEvent.KEYCODE_DPAD_RIGHT:
2153 case KeyEvent.KEYCODE_DPAD_UP:
2154 case KeyEvent.KEYCODE_DPAD_DOWN:
2155 return true;
2156 }
2157 return false;
2158 }
2159
2160 /**
2161 * Returns true if this key is a keyboard key.
2162 * @param keyEvent The key event.
2163 * @return whether this key is a keyboard key.
2164 */
2165 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2166 final int convertedKey = keyEvent.getUnicodeChar();
2167 return convertedKey > 0;
2168 }
2169
2170
2171
2172 /**
2173 * See if the key event means we should leave touch mode (and leave touch
2174 * mode if so).
2175 * @param event The key event.
2176 * @return Whether this key event should be consumed (meaning the act of
2177 * leaving touch mode alone is considered the event).
2178 */
2179 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2180 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2181 return false;
2182 }
2183 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2184 return false;
2185 }
2186
2187 // only relevant if we are in touch mode
2188 if (!mAttachInfo.mInTouchMode) {
2189 return false;
2190 }
2191
2192 // if something like an edit text has focus and the user is typing,
2193 // leave touch mode
2194 //
2195 // note: the condition of not being a keyboard key is kind of a hacky
2196 // approximation of whether we think the focused view will want the
2197 // key; if we knew for sure whether the focused view would consume
2198 // the event, that would be better.
2199 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2200 mFocusedView = mView.findFocus();
2201 if ((mFocusedView instanceof ViewGroup)
2202 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2203 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2204 // something has focus, but is holding it weakly as a container
2205 return false;
2206 }
2207 if (ensureTouchMode(false)) {
2208 throw new IllegalStateException("should not have changed focus "
2209 + "when leaving touch mode while a view has focus.");
2210 }
2211 return false;
2212 }
2213
2214 if (isDirectional(event.getKeyCode())) {
2215 // no view has focus, so we leave touch mode (and find something
2216 // to give focus to). the event is consumed if we were able to
2217 // find something to give focus to.
2218 return ensureTouchMode(false);
2219 }
2220 return false;
2221 }
2222
2223 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002224 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 */
2226 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002227 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 if (ev == null ||
2229 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2230 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 }
Romain Guy8506ab42009-06-11 17:35:47 -07002232
2233 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 sb.append(ev.getDownTime()).append(',');
2235 sb.append(ev.getEventTime()).append(',');
2236 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002237 sb.append(ev.getX()).append(',');
2238 sb.append(ev.getY()).append(',');
2239 sb.append(ev.getPressure()).append(',');
2240 sb.append(ev.getSize()).append(',');
2241 sb.append(ev.getMetaState()).append(',');
2242 sb.append(ev.getXPrecision()).append(',');
2243 sb.append(ev.getYPrecision()).append(',');
2244 sb.append(ev.getDeviceId()).append(',');
2245 sb.append(ev.getEdgeFlags());
2246 Log.d(TAG, sb.toString());
2247 }
2248 /**
2249 * log motion events
2250 */
2251 private static void captureKeyLog(String subTag, KeyEvent ev) {
2252 //check dynamic switch
2253 if (ev == null ||
2254 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2255 return;
2256 }
2257 StringBuilder sb = new StringBuilder(subTag + ": ");
2258 sb.append(ev.getDownTime()).append(',');
2259 sb.append(ev.getEventTime()).append(',');
2260 sb.append(ev.getAction()).append(',');
2261 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 sb.append(ev.getRepeatCount()).append(',');
2263 sb.append(ev.getMetaState()).append(',');
2264 sb.append(ev.getDeviceId()).append(',');
2265 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002266 Log.d(TAG, sb.toString());
2267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268
2269 int enqueuePendingEvent(Object event, boolean sendDone) {
2270 int seq = mPendingEventSeq+1;
2271 if (seq < 0) seq = 0;
2272 mPendingEventSeq = seq;
2273 mPendingEvents.put(seq, event);
2274 return sendDone ? seq : -seq;
2275 }
2276
2277 Object retrievePendingEvent(int seq) {
2278 if (seq < 0) seq = -seq;
2279 Object event = mPendingEvents.get(seq);
2280 if (event != null) {
2281 mPendingEvents.remove(seq);
2282 }
2283 return event;
2284 }
Romain Guy8506ab42009-06-11 17:35:47 -07002285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2287 // If mView is null, we just consume the key event because it doesn't
2288 // make sense to do anything else with it.
2289 boolean handled = mView != null
2290 ? mView.dispatchKeyEventPreIme(event) : true;
2291 if (handled) {
2292 if (sendDone) {
2293 if (LOCAL_LOGV) Log.v(
2294 "ViewRoot", "Telling window manager key is finished");
2295 try {
2296 sWindowSession.finishKey(mWindow);
2297 } catch (RemoteException e) {
2298 }
2299 }
2300 return;
2301 }
2302 // If it is possible for this window to interact with the input
2303 // method window, then we want to first dispatch our key events
2304 // to the input method.
2305 if (mLastWasImTarget) {
2306 InputMethodManager imm = InputMethodManager.peekInstance();
2307 if (imm != null && mView != null) {
2308 int seq = enqueuePendingEvent(event, sendDone);
2309 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2310 + seq + " event=" + event);
2311 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2312 mInputMethodCallback);
2313 return;
2314 }
2315 }
2316 deliverKeyEventToViewHierarchy(event, sendDone);
2317 }
2318
2319 void handleFinishedEvent(int seq, boolean handled) {
2320 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2321 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2322 + " handled=" + handled + " event=" + event);
2323 if (event != null) {
2324 final boolean sendDone = seq >= 0;
2325 if (!handled) {
2326 deliverKeyEventToViewHierarchy(event, sendDone);
2327 return;
2328 } else if (sendDone) {
2329 if (LOCAL_LOGV) Log.v(
2330 "ViewRoot", "Telling window manager key is finished");
2331 try {
2332 sWindowSession.finishKey(mWindow);
2333 } catch (RemoteException e) {
2334 }
2335 } else {
2336 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2337 + " handled=" + handled + " ev=" + event
2338 + ") neither delivering nor finishing key");
2339 }
2340 }
2341 }
Romain Guy8506ab42009-06-11 17:35:47 -07002342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2344 try {
2345 if (mView != null && mAdded) {
2346 final int action = event.getAction();
2347 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2348
2349 if (checkForLeavingTouchModeAndConsume(event)) {
2350 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002351 }
2352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 if (Config.LOGV) {
2354 captureKeyLog("captureDispatchKeyEvent", event);
2355 }
2356 boolean keyHandled = mView.dispatchKeyEvent(event);
2357
2358 if (!keyHandled && isDown) {
2359 int direction = 0;
2360 switch (event.getKeyCode()) {
2361 case KeyEvent.KEYCODE_DPAD_LEFT:
2362 direction = View.FOCUS_LEFT;
2363 break;
2364 case KeyEvent.KEYCODE_DPAD_RIGHT:
2365 direction = View.FOCUS_RIGHT;
2366 break;
2367 case KeyEvent.KEYCODE_DPAD_UP:
2368 direction = View.FOCUS_UP;
2369 break;
2370 case KeyEvent.KEYCODE_DPAD_DOWN:
2371 direction = View.FOCUS_DOWN;
2372 break;
2373 }
2374
2375 if (direction != 0) {
2376
2377 View focused = mView != null ? mView.findFocus() : null;
2378 if (focused != null) {
2379 View v = focused.focusSearch(direction);
2380 boolean focusPassed = false;
2381 if (v != null && v != focused) {
2382 // do the math the get the interesting rect
2383 // of previous focused into the coord system of
2384 // newly focused view
2385 focused.getFocusedRect(mTempRect);
2386 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2387 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2388 focusPassed = v.requestFocus(direction, mTempRect);
2389 }
2390
2391 if (!focusPassed) {
2392 mView.dispatchUnhandledMove(focused, direction);
2393 } else {
2394 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2395 }
2396 }
2397 }
2398 }
2399 }
2400
2401 } finally {
2402 if (sendDone) {
2403 if (LOCAL_LOGV) Log.v(
2404 "ViewRoot", "Telling window manager key is finished");
2405 try {
2406 sWindowSession.finishKey(mWindow);
2407 } catch (RemoteException e) {
2408 }
2409 }
2410 // Let the exception fall through -- the looper will catch
2411 // it and take care of the bad app for us.
2412 }
2413 }
2414
2415 private AudioManager getAudioManager() {
2416 if (mView == null) {
2417 throw new IllegalStateException("getAudioManager called when there is no mView");
2418 }
2419 if (mAudioManager == null) {
2420 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2421 }
2422 return mAudioManager;
2423 }
2424
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002425 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2426 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002427
2428 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002429 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002430 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002431 restore = true;
2432 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002433 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002434 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002435 if (params != null) {
2436 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002437 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002438 int relayoutResult = sWindowSession.relayout(
2439 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002440 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2441 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002442 viewVisibility, insetsPending, mWinFrame,
2443 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002444 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002445 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002446 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002447
2448 if (mTranslator != null) {
2449 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2450 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2451 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002452 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002453 return relayoutResult;
2454 }
Romain Guy8506ab42009-06-11 17:35:47 -07002455
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002456 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 * {@inheritDoc}
2458 */
2459 public void playSoundEffect(int effectId) {
2460 checkThread();
2461
2462 final AudioManager audioManager = getAudioManager();
2463
2464 switch (effectId) {
2465 case SoundEffectConstants.CLICK:
2466 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2467 return;
2468 case SoundEffectConstants.NAVIGATION_DOWN:
2469 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2470 return;
2471 case SoundEffectConstants.NAVIGATION_LEFT:
2472 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2473 return;
2474 case SoundEffectConstants.NAVIGATION_RIGHT:
2475 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2476 return;
2477 case SoundEffectConstants.NAVIGATION_UP:
2478 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2479 return;
2480 default:
2481 throw new IllegalArgumentException("unknown effect id " + effectId +
2482 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2483 }
2484 }
2485
2486 /**
2487 * {@inheritDoc}
2488 */
2489 public boolean performHapticFeedback(int effectId, boolean always) {
2490 try {
2491 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2492 } catch (RemoteException e) {
2493 return false;
2494 }
2495 }
2496
2497 /**
2498 * {@inheritDoc}
2499 */
2500 public View focusSearch(View focused, int direction) {
2501 checkThread();
2502 if (!(mView instanceof ViewGroup)) {
2503 return null;
2504 }
2505 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2506 }
2507
2508 public void debug() {
2509 mView.debug();
2510 }
2511
2512 public void die(boolean immediate) {
2513 checkThread();
2514 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2515 synchronized (this) {
2516 if (mAdded && !mFirst) {
2517 int viewVisibility = mView.getVisibility();
2518 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2519 if (mWindowAttributesChanged || viewVisibilityChanged) {
2520 // If layout params have been changed, first give them
2521 // to the window manager to make sure it has the correct
2522 // animation info.
2523 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002524 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2525 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 sWindowSession.finishDrawing(mWindow);
2527 }
2528 } catch (RemoteException e) {
2529 }
2530 }
2531
Mathias Agopian5583dc62009-07-09 16:28:11 -07002532 mSurface.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 }
2534 if (mAdded) {
2535 mAdded = false;
2536 if (immediate) {
2537 dispatchDetachedFromWindow();
2538 } else if (mView != null) {
2539 sendEmptyMessage(DIE);
2540 }
2541 }
2542 }
2543 }
2544
2545 public void dispatchFinishedEvent(int seq, boolean handled) {
2546 Message msg = obtainMessage(FINISHED_EVENT);
2547 msg.arg1 = seq;
2548 msg.arg2 = handled ? 1 : 0;
2549 sendMessage(msg);
2550 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 public void dispatchResized(int w, int h, Rect coveredInsets,
2553 Rect visibleInsets, boolean reportDraw) {
2554 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2555 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2556 + " visibleInsets=" + visibleInsets.toShortString()
2557 + " reportDraw=" + reportDraw);
2558 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002559 if (mTranslator != null) {
2560 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2561 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2562 w *= mTranslator.applicationInvertedScale;
2563 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002564 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002565 msg.arg1 = w;
2566 msg.arg2 = h;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2568 sendMessage(msg);
2569 }
2570
2571 public void dispatchKey(KeyEvent event) {
2572 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2573 //noinspection ConstantConditions
2574 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2575 if (Config.LOGD) Log.d("keydisp",
2576 "===================================================");
2577 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2578 debug();
2579
2580 if (Config.LOGD) Log.d("keydisp",
2581 "===================================================");
2582 }
2583 }
2584
2585 Message msg = obtainMessage(DISPATCH_KEY);
2586 msg.obj = event;
2587
2588 if (LOCAL_LOGV) Log.v(
2589 "ViewRoot", "sending key " + event + " to " + mView);
2590
2591 sendMessageAtTime(msg, event.getEventTime());
2592 }
2593
2594 public void dispatchPointer(MotionEvent event, long eventTime) {
2595 Message msg = obtainMessage(DISPATCH_POINTER);
2596 msg.obj = event;
2597 sendMessageAtTime(msg, eventTime);
2598 }
2599
2600 public void dispatchTrackball(MotionEvent event, long eventTime) {
2601 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2602 msg.obj = event;
2603 sendMessageAtTime(msg, eventTime);
2604 }
2605
2606 public void dispatchAppVisibility(boolean visible) {
2607 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2608 msg.arg1 = visible ? 1 : 0;
2609 sendMessage(msg);
2610 }
2611
2612 public void dispatchGetNewSurface() {
2613 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2614 sendMessage(msg);
2615 }
2616
2617 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2618 Message msg = Message.obtain();
2619 msg.what = WINDOW_FOCUS_CHANGED;
2620 msg.arg1 = hasFocus ? 1 : 0;
2621 msg.arg2 = inTouchMode ? 1 : 0;
2622 sendMessage(msg);
2623 }
2624
svetoslavganov75986cf2009-05-14 22:28:01 -07002625 /**
2626 * The window is getting focus so if there is anything focused/selected
2627 * send an {@link AccessibilityEvent} to announce that.
2628 */
2629 private void sendAccessibilityEvents() {
2630 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2631 return;
2632 }
2633 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2634 View focusedView = mView.findFocus();
2635 if (focusedView != null && focusedView != mView) {
2636 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2637 }
2638 }
2639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 public boolean showContextMenuForChild(View originalView) {
2641 return false;
2642 }
2643
2644 public void createContextMenu(ContextMenu menu) {
2645 }
2646
2647 public void childDrawableStateChanged(View child) {
2648 }
2649
2650 protected Rect getWindowFrame() {
2651 return mWinFrame;
2652 }
2653
2654 void checkThread() {
2655 if (mThread != Thread.currentThread()) {
2656 throw new CalledFromWrongThreadException(
2657 "Only the original thread that created a view hierarchy can touch its views.");
2658 }
2659 }
2660
2661 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2662 // ViewRoot never intercepts touch event, so this can be a no-op
2663 }
2664
2665 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2666 boolean immediate) {
2667 return scrollToRectOrFocus(rectangle, immediate);
2668 }
Romain Guy8506ab42009-06-11 17:35:47 -07002669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 static class InputMethodCallback extends IInputMethodCallback.Stub {
2671 private WeakReference<ViewRoot> mViewRoot;
2672
2673 public InputMethodCallback(ViewRoot viewRoot) {
2674 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2675 }
Romain Guy8506ab42009-06-11 17:35:47 -07002676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 public void finishedEvent(int seq, boolean handled) {
2678 final ViewRoot viewRoot = mViewRoot.get();
2679 if (viewRoot != null) {
2680 viewRoot.dispatchFinishedEvent(seq, handled);
2681 }
2682 }
2683
2684 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2685 // Stub -- not for use in the client.
2686 }
2687 }
Romain Guy8506ab42009-06-11 17:35:47 -07002688
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002689 static class EventCompletion extends Handler {
2690 final IWindow mWindow;
2691 final KeyEvent mKeyEvent;
2692 final boolean mIsPointer;
2693 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002694
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002695 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2696 boolean isPointer, MotionEvent motion) {
2697 super(looper);
2698 mWindow = window;
2699 mKeyEvent = key;
2700 mIsPointer = isPointer;
2701 mMotionEvent = motion;
2702 sendEmptyMessage(0);
2703 }
Romain Guy8506ab42009-06-11 17:35:47 -07002704
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002705 @Override
2706 public void handleMessage(Message msg) {
2707 if (mKeyEvent != null) {
2708 try {
2709 sWindowSession.finishKey(mWindow);
2710 } catch (RemoteException e) {
2711 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002712 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002713 boolean didFinish;
2714 MotionEvent event = mMotionEvent;
2715 if (event == null) {
2716 try {
2717 event = sWindowSession.getPendingPointerMove(mWindow);
2718 } catch (RemoteException e) {
2719 }
2720 didFinish = true;
2721 } else {
2722 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2723 }
2724 if (!didFinish) {
2725 try {
2726 sWindowSession.finishKey(mWindow);
2727 } catch (RemoteException e) {
2728 }
2729 }
2730 } else {
2731 MotionEvent event = mMotionEvent;
2732 if (event == null) {
2733 try {
2734 event = sWindowSession.getPendingTrackballMove(mWindow);
2735 } catch (RemoteException e) {
2736 }
2737 } else {
2738 try {
2739 sWindowSession.finishKey(mWindow);
2740 } catch (RemoteException e) {
2741 }
2742 }
2743 }
2744 }
2745 }
Romain Guy8506ab42009-06-11 17:35:47 -07002746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002748 private final WeakReference<ViewRoot> mViewRoot;
2749 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002751 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002753 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 }
2755
2756 public void resized(int w, int h, Rect coveredInsets,
2757 Rect visibleInsets, boolean reportDraw) {
2758 final ViewRoot viewRoot = mViewRoot.get();
2759 if (viewRoot != null) {
2760 viewRoot.dispatchResized(w, h, coveredInsets,
2761 visibleInsets, reportDraw);
2762 }
2763 }
2764
2765 public void dispatchKey(KeyEvent event) {
2766 final ViewRoot viewRoot = mViewRoot.get();
2767 if (viewRoot != null) {
2768 viewRoot.dispatchKey(event);
2769 } else {
2770 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002771 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 }
2773 }
2774
2775 public void dispatchPointer(MotionEvent event, long eventTime) {
2776 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002777 if (viewRoot != null) {
2778 if (MEASURE_LATENCY) {
2779 // Note: eventTime is in milliseconds
2780 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 viewRoot.dispatchPointer(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002783 } else {
2784 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 }
2786 }
2787
2788 public void dispatchTrackball(MotionEvent event, long eventTime) {
2789 final ViewRoot viewRoot = mViewRoot.get();
2790 if (viewRoot != null) {
2791 viewRoot.dispatchTrackball(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002792 } else {
2793 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 }
2795 }
2796
2797 public void dispatchAppVisibility(boolean visible) {
2798 final ViewRoot viewRoot = mViewRoot.get();
2799 if (viewRoot != null) {
2800 viewRoot.dispatchAppVisibility(visible);
2801 }
2802 }
2803
2804 public void dispatchGetNewSurface() {
2805 final ViewRoot viewRoot = mViewRoot.get();
2806 if (viewRoot != null) {
2807 viewRoot.dispatchGetNewSurface();
2808 }
2809 }
2810
2811 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2812 final ViewRoot viewRoot = mViewRoot.get();
2813 if (viewRoot != null) {
2814 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2815 }
2816 }
2817
2818 private static int checkCallingPermission(String permission) {
2819 if (!Process.supportsProcesses()) {
2820 return PackageManager.PERMISSION_GRANTED;
2821 }
2822
2823 try {
2824 return ActivityManagerNative.getDefault().checkPermission(
2825 permission, Binder.getCallingPid(), Binder.getCallingUid());
2826 } catch (RemoteException e) {
2827 return PackageManager.PERMISSION_DENIED;
2828 }
2829 }
2830
2831 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2832 final ViewRoot viewRoot = mViewRoot.get();
2833 if (viewRoot != null) {
2834 final View view = viewRoot.mView;
2835 if (view != null) {
2836 if (checkCallingPermission(Manifest.permission.DUMP) !=
2837 PackageManager.PERMISSION_GRANTED) {
2838 throw new SecurityException("Insufficient permissions to invoke"
2839 + " executeCommand() from pid=" + Binder.getCallingPid()
2840 + ", uid=" + Binder.getCallingUid());
2841 }
2842
2843 OutputStream clientStream = null;
2844 try {
2845 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2846 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2847 } catch (IOException e) {
2848 e.printStackTrace();
2849 } finally {
2850 if (clientStream != null) {
2851 try {
2852 clientStream.close();
2853 } catch (IOException e) {
2854 e.printStackTrace();
2855 }
2856 }
2857 }
2858 }
2859 }
2860 }
2861 }
2862
2863 /**
2864 * Maintains state information for a single trackball axis, generating
2865 * discrete (DPAD) movements based on raw trackball motion.
2866 */
2867 static final class TrackballAxis {
2868 /**
2869 * The maximum amount of acceleration we will apply.
2870 */
2871 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 /**
2874 * The maximum amount of time (in milliseconds) between events in order
2875 * for us to consider the user to be doing fast trackball movements,
2876 * and thus apply an acceleration.
2877 */
2878 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 /**
2881 * Scaling factor to the time (in milliseconds) between events to how
2882 * much to multiple/divide the current acceleration. When movement
2883 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2884 * FAST_MOVE_TIME it divides it.
2885 */
2886 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 float position;
2889 float absPosition;
2890 float acceleration = 1;
2891 long lastMoveTime = 0;
2892 int step;
2893 int dir;
2894 int nonAccelMovement;
2895
2896 void reset(int _step) {
2897 position = 0;
2898 acceleration = 1;
2899 lastMoveTime = 0;
2900 step = _step;
2901 dir = 0;
2902 }
2903
2904 /**
2905 * Add trackball movement into the state. If the direction of movement
2906 * has been reversed, the state is reset before adding the
2907 * movement (so that you don't have to compensate for any previously
2908 * collected movement before see the result of the movement in the
2909 * new direction).
2910 *
2911 * @return Returns the absolute value of the amount of movement
2912 * collected so far.
2913 */
2914 float collect(float off, long time, String axis) {
2915 long normTime;
2916 if (off > 0) {
2917 normTime = (long)(off * FAST_MOVE_TIME);
2918 if (dir < 0) {
2919 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2920 position = 0;
2921 step = 0;
2922 acceleration = 1;
2923 lastMoveTime = 0;
2924 }
2925 dir = 1;
2926 } else if (off < 0) {
2927 normTime = (long)((-off) * FAST_MOVE_TIME);
2928 if (dir > 0) {
2929 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2930 position = 0;
2931 step = 0;
2932 acceleration = 1;
2933 lastMoveTime = 0;
2934 }
2935 dir = -1;
2936 } else {
2937 normTime = 0;
2938 }
Romain Guy8506ab42009-06-11 17:35:47 -07002939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 // The number of milliseconds between each movement that is
2941 // considered "normal" and will not result in any acceleration
2942 // or deceleration, scaled by the offset we have here.
2943 if (normTime > 0) {
2944 long delta = time - lastMoveTime;
2945 lastMoveTime = time;
2946 float acc = acceleration;
2947 if (delta < normTime) {
2948 // The user is scrolling rapidly, so increase acceleration.
2949 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2950 if (scale > 1) acc *= scale;
2951 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2952 + off + " normTime=" + normTime + " delta=" + delta
2953 + " scale=" + scale + " acc=" + acc);
2954 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2955 } else {
2956 // The user is scrolling slowly, so decrease acceleration.
2957 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
2958 if (scale > 1) acc /= scale;
2959 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
2960 + off + " normTime=" + normTime + " delta=" + delta
2961 + " scale=" + scale + " acc=" + acc);
2962 acceleration = acc > 1 ? acc : 1;
2963 }
2964 }
2965 position += off;
2966 return (absPosition = Math.abs(position));
2967 }
2968
2969 /**
2970 * Generate the number of discrete movement events appropriate for
2971 * the currently collected trackball movement.
2972 *
2973 * @param precision The minimum movement required to generate the
2974 * first discrete movement.
2975 *
2976 * @return Returns the number of discrete movements, either positive
2977 * or negative, or 0 if there is not enough trackball movement yet
2978 * for a discrete movement.
2979 */
2980 int generate(float precision) {
2981 int movement = 0;
2982 nonAccelMovement = 0;
2983 do {
2984 final int dir = position >= 0 ? 1 : -1;
2985 switch (step) {
2986 // If we are going to execute the first step, then we want
2987 // to do this as soon as possible instead of waiting for
2988 // a full movement, in order to make things look responsive.
2989 case 0:
2990 if (absPosition < precision) {
2991 return movement;
2992 }
2993 movement += dir;
2994 nonAccelMovement += dir;
2995 step = 1;
2996 break;
2997 // If we have generated the first movement, then we need
2998 // to wait for the second complete trackball motion before
2999 // generating the second discrete movement.
3000 case 1:
3001 if (absPosition < 2) {
3002 return movement;
3003 }
3004 movement += dir;
3005 nonAccelMovement += dir;
3006 position += dir > 0 ? -2 : 2;
3007 absPosition = Math.abs(position);
3008 step = 2;
3009 break;
3010 // After the first two, we generate discrete movements
3011 // consistently with the trackball, applying an acceleration
3012 // if the trackball is moving quickly. This is a simple
3013 // acceleration on top of what we already compute based
3014 // on how quickly the wheel is being turned, to apply
3015 // a longer increasing acceleration to continuous movement
3016 // in one direction.
3017 default:
3018 if (absPosition < 1) {
3019 return movement;
3020 }
3021 movement += dir;
3022 position += dir >= 0 ? -1 : 1;
3023 absPosition = Math.abs(position);
3024 float acc = acceleration;
3025 acc *= 1.1f;
3026 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3027 break;
3028 }
3029 } while (true);
3030 }
3031 }
3032
3033 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3034 public CalledFromWrongThreadException(String msg) {
3035 super(msg);
3036 }
3037 }
3038
3039 private SurfaceHolder mHolder = new SurfaceHolder() {
3040 // we only need a SurfaceHolder for opengl. it would be nice
3041 // to implement everything else though, especially the callback
3042 // support (opengl doesn't make use of it right now, but eventually
3043 // will).
3044 public Surface getSurface() {
3045 return mSurface;
3046 }
3047
3048 public boolean isCreating() {
3049 return false;
3050 }
3051
3052 public void addCallback(Callback callback) {
3053 }
3054
3055 public void removeCallback(Callback callback) {
3056 }
3057
3058 public void setFixedSize(int width, int height) {
3059 }
3060
3061 public void setSizeFromLayout() {
3062 }
3063
3064 public void setFormat(int format) {
3065 }
3066
3067 public void setType(int type) {
3068 }
3069
3070 public void setKeepScreenOn(boolean screenOn) {
3071 }
3072
3073 public Canvas lockCanvas() {
3074 return null;
3075 }
3076
3077 public Canvas lockCanvas(Rect dirty) {
3078 return null;
3079 }
3080
3081 public void unlockCanvasAndPost(Canvas canvas) {
3082 }
3083 public Rect getSurfaceFrame() {
3084 return null;
3085 }
3086 };
3087
3088 static RunQueue getRunQueue() {
3089 RunQueue rq = sRunQueues.get();
3090 if (rq != null) {
3091 return rq;
3092 }
3093 rq = new RunQueue();
3094 sRunQueues.set(rq);
3095 return rq;
3096 }
Romain Guy8506ab42009-06-11 17:35:47 -07003097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 /**
3099 * @hide
3100 */
3101 static final class RunQueue {
3102 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3103
3104 void post(Runnable action) {
3105 postDelayed(action, 0);
3106 }
3107
3108 void postDelayed(Runnable action, long delayMillis) {
3109 HandlerAction handlerAction = new HandlerAction();
3110 handlerAction.action = action;
3111 handlerAction.delay = delayMillis;
3112
3113 synchronized (mActions) {
3114 mActions.add(handlerAction);
3115 }
3116 }
3117
3118 void removeCallbacks(Runnable action) {
3119 final HandlerAction handlerAction = new HandlerAction();
3120 handlerAction.action = action;
3121
3122 synchronized (mActions) {
3123 final ArrayList<HandlerAction> actions = mActions;
3124
3125 while (actions.remove(handlerAction)) {
3126 // Keep going
3127 }
3128 }
3129 }
3130
3131 void executeActions(Handler handler) {
3132 synchronized (mActions) {
3133 final ArrayList<HandlerAction> actions = mActions;
3134 final int count = actions.size();
3135
3136 for (int i = 0; i < count; i++) {
3137 final HandlerAction handlerAction = actions.get(i);
3138 handler.postDelayed(handlerAction.action, handlerAction.delay);
3139 }
3140
3141 mActions.clear();
3142 }
3143 }
3144
3145 private static class HandlerAction {
3146 Runnable action;
3147 long delay;
3148
3149 @Override
3150 public boolean equals(Object o) {
3151 if (this == o) return true;
3152 if (o == null || getClass() != o.getClass()) return false;
3153
3154 HandlerAction that = (HandlerAction) o;
3155
3156 return !(action != null ? !action.equals(that.action) : that.action != null);
3157
3158 }
3159
3160 @Override
3161 public int hashCode() {
3162 int result = action != null ? action.hashCode() : 0;
3163 result = 31 * result + (int) (delay ^ (delay >>> 32));
3164 return result;
3165 }
3166 }
3167 }
3168
3169 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3170
3171 // inform skia to just abandon its texture cache IDs
3172 // doesn't call glDeleteTextures
3173 private static native void nativeAbandonGlCaches();
3174}