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