blob: d35b04894164084d0a2d826f49caaec225264e97 [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 Oshima9189cab2009-06-03 11:19:12 -0700131 private CompatibilityInfo mCompatibilityInfo;
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.
137 final Point mVisPoint; // used to retrieve global offset of focused view.
138
139 boolean mTraversalScheduled;
140 boolean mWillDrawSoon;
141 boolean mLayoutRequested;
142 boolean mFirst;
143 boolean mReportNextDraw;
144 boolean mFullRedrawNeeded;
145 boolean mNewSurfaceNeeded;
146 boolean mHasHadWindowFocus;
147 boolean mLastWasImTarget;
148
149 boolean mWindowAttributesChanged = false;
150
151 // These can be accessed by any thread, must be protected with a lock.
152 Surface mSurface;
153
154 boolean mAdded;
155 boolean mAddedTouchMode;
156
157 /*package*/ int mAddNesting;
158
159 // These are accessed by multiple threads.
160 final Rect mWinFrame; // frame given by window manager.
161
162 final Rect mPendingVisibleInsets = new Rect();
163 final Rect mPendingContentInsets = new Rect();
164 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
165 = new ViewTreeObserver.InternalInsetsInfo();
166
167 boolean mScrollMayChange;
168 int mSoftInputMode;
169 View mLastScrolledFocus;
170 int mScrollY;
171 int mCurScrollY;
172 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 EGL10 mEgl;
175 EGLDisplay mEglDisplay;
176 EGLContext mEglContext;
177 EGLSurface mEglSurface;
178 GL11 mGL;
179 Canvas mGlCanvas;
180 boolean mUseGL;
181 boolean mGlWanted;
182
Romain Guy8506ab42009-06-11 17:35:47 -0700183 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
185 /**
186 * see {@link #playSoundEffect(int)}
187 */
188 AudioManager mAudioManager;
189
190 private final float mDensity;
191
192 public ViewRoot(Context context) {
193 super();
194
195 ++sInstanceCount;
196
197 // Initialize the statics when this class is first instantiated. This is
198 // done here instead of in the static block because Zygote does not
199 // allow the spawning of threads.
200 synchronized (mStaticInit) {
201 if (!mInitialized) {
202 try {
203 InputMethodManager imm = InputMethodManager.getInstance(context);
204 sWindowSession = IWindowManager.Stub.asInterface(
205 ServiceManager.getService("window"))
206 .openSession(imm.getClient(), imm.getInputContext());
207 mInitialized = true;
208 } catch (RemoteException e) {
209 }
210 }
211 }
212
213 mThread = Thread.currentThread();
214 mLocation = new WindowLeaked(null);
215 mLocation.fillInStackTrace();
216 mWidth = -1;
217 mHeight = -1;
218 mDirty = new Rect();
219 mTempRect = new Rect();
220 mVisRect = new Rect();
221 mVisPoint = new Point();
222 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700223 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 mInputMethodCallback = new InputMethodCallback(this);
225 mViewVisibility = View.GONE;
226 mTransparentRegion = new Region();
227 mPreviousTransparentRegion = new Region();
228 mFirst = true; // true for the first time the view is added
229 mSurface = new Surface();
230 mAdded = false;
231 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
232 mViewConfiguration = ViewConfiguration.get(context);
233 mDensity = context.getResources().getDisplayMetrics().density;
234 }
235
236 @Override
237 protected void finalize() throws Throwable {
238 super.finalize();
239 --sInstanceCount;
240 }
241
242 public static long getInstanceCount() {
243 return sInstanceCount;
244 }
245
246 // FIXME for perf testing only
247 private boolean mProfile = false;
248
249 /**
250 * Call this to profile the next traversal call.
251 * FIXME for perf testing only. Remove eventually
252 */
253 public void profile() {
254 mProfile = true;
255 }
256
257 /**
258 * Indicates whether we are in touch mode. Calling this method triggers an IPC
259 * call and should be avoided whenever possible.
260 *
261 * @return True, if the device is in touch mode, false otherwise.
262 *
263 * @hide
264 */
265 static boolean isInTouchMode() {
266 if (mInitialized) {
267 try {
268 return sWindowSession.getInTouchMode();
269 } catch (RemoteException e) {
270 }
271 }
272 return false;
273 }
274
275 private void initializeGL() {
276 initializeGLInner();
277 int err = mEgl.eglGetError();
278 if (err != EGL10.EGL_SUCCESS) {
279 // give-up on using GL
280 destroyGL();
281 mGlWanted = false;
282 }
283 }
284
285 private void initializeGLInner() {
286 final EGL10 egl = (EGL10) EGLContext.getEGL();
287 mEgl = egl;
288
289 /*
290 * Get to the default display.
291 */
292 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
293 mEglDisplay = eglDisplay;
294
295 /*
296 * We can now initialize EGL for that display
297 */
298 int[] version = new int[2];
299 egl.eglInitialize(eglDisplay, version);
300
301 /*
302 * Specify a configuration for our opengl session
303 * and grab the first configuration that matches is
304 */
305 final int[] configSpec = {
306 EGL10.EGL_RED_SIZE, 5,
307 EGL10.EGL_GREEN_SIZE, 6,
308 EGL10.EGL_BLUE_SIZE, 5,
309 EGL10.EGL_DEPTH_SIZE, 0,
310 EGL10.EGL_NONE
311 };
312 final EGLConfig[] configs = new EGLConfig[1];
313 final int[] num_config = new int[1];
314 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
315 final EGLConfig config = configs[0];
316
317 /*
318 * Create an OpenGL ES context. This must be done only once, an
319 * OpenGL context is a somewhat heavy object.
320 */
321 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
322 EGL10.EGL_NO_CONTEXT, null);
323 mEglContext = context;
324
325 /*
326 * Create an EGL surface we can render into.
327 */
328 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
329 mEglSurface = surface;
330
331 /*
332 * Before we can issue GL commands, we need to make sure
333 * the context is current and bound to a surface.
334 */
335 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
336
337 /*
338 * Get to the appropriate GL interface.
339 * This is simply done by casting the GL context to either
340 * GL10 or GL11.
341 */
342 final GL11 gl = (GL11) context.getGL();
343 mGL = gl;
344 mGlCanvas = new Canvas(gl);
345 mUseGL = true;
346 }
347
348 private void destroyGL() {
349 // inform skia that the context is gone
350 nativeAbandonGlCaches();
351
352 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
353 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
354 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
355 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
356 mEgl.eglTerminate(mEglDisplay);
357 mEglContext = null;
358 mEglSurface = null;
359 mEglDisplay = null;
360 mEgl = null;
361 mGlCanvas = null;
362 mGL = null;
363 mUseGL = false;
364 }
365
366 private void checkEglErrors() {
367 if (mUseGL) {
368 int err = mEgl.eglGetError();
369 if (err != EGL10.EGL_SUCCESS) {
370 // something bad has happened revert to
371 // normal rendering.
372 destroyGL();
373 if (err != EGL11.EGL_CONTEXT_LOST) {
374 // we'll try again if it was context lost
375 mGlWanted = false;
376 }
377 }
378 }
379 }
380
381 /**
382 * We have one child
383 */
384 public void setView(View view, WindowManager.LayoutParams attrs,
385 View panelParentView) {
386 synchronized (this) {
387 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700388 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700389 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700390 mCompatibilityInfo = mView.getContext().getResources().getCompatibilityInfo();
391 boolean restore = false;
392 if (mCompatibilityInfo.mScalingRequired || !mCompatibilityInfo.mExpandable) {
393 restore = true;
394 mWindowAttributes.backup();
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700395 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700396 if (!mCompatibilityInfo.mExpandable) {
397 adjustWindowAttributesForCompatibleMode(mWindowAttributes);
398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 mSoftInputMode = attrs.softInputMode;
400 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 mAttachInfo.mRootView = view;
Romain Guy8506ab42009-06-11 17:35:47 -0700402 mAttachInfo.mScalingRequired = mCompatibilityInfo.mScalingRequired;
403 mAttachInfo.mApplicationScale = mCompatibilityInfo.mApplicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 if (panelParentView != null) {
405 mAttachInfo.mPanelParentWindowToken
406 = panelParentView.getApplicationWindowToken();
407 }
408 mAdded = true;
409 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 // Schedule the first layout -before- adding to the window
412 // manager, to make sure we do the relayout before receiving
413 // any other events from the system.
414 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700416 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 getHostVisibility(), mAttachInfo.mContentInsets);
418 } catch (RemoteException e) {
419 mAdded = false;
420 mView = null;
421 mAttachInfo.mRootView = null;
422 unscheduleTraversals();
423 throw new RuntimeException("Adding window failed", e);
424 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700425
426 if (restore) {
427 mWindowAttributes.restore();
428 }
429
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700430 if (mCompatibilityInfo.mScalingRequired) {
431 mAttachInfo.mContentInsets.scale(
432 mCompatibilityInfo.mApplicationInvertedScale);
433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 mPendingContentInsets.set(mAttachInfo.mContentInsets);
435 mPendingVisibleInsets.set(0, 0, 0, 0);
436 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
437 if (res < WindowManagerImpl.ADD_OKAY) {
438 mView = null;
439 mAttachInfo.mRootView = null;
440 mAdded = false;
441 unscheduleTraversals();
442 switch (res) {
443 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
444 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
445 throw new WindowManagerImpl.BadTokenException(
446 "Unable to add window -- token " + attrs.token
447 + " is not valid; is your activity running?");
448 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
449 throw new WindowManagerImpl.BadTokenException(
450 "Unable to add window -- token " + attrs.token
451 + " is not for an application");
452 case WindowManagerImpl.ADD_APP_EXITING:
453 throw new WindowManagerImpl.BadTokenException(
454 "Unable to add window -- app for token " + attrs.token
455 + " is exiting");
456 case WindowManagerImpl.ADD_DUPLICATE_ADD:
457 throw new WindowManagerImpl.BadTokenException(
458 "Unable to add window -- window " + mWindow
459 + " has already been added");
460 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
461 // Silently ignore -- we would have just removed it
462 // right away, anyway.
463 return;
464 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
465 throw new WindowManagerImpl.BadTokenException(
466 "Unable to add window " + mWindow +
467 " -- another window of this type already exists");
468 case WindowManagerImpl.ADD_PERMISSION_DENIED:
469 throw new WindowManagerImpl.BadTokenException(
470 "Unable to add window " + mWindow +
471 " -- permission denied for this window type");
472 }
473 throw new RuntimeException(
474 "Unable to add window -- unknown error code " + res);
475 }
476 view.assignParent(this);
477 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
478 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
479 }
480 }
481 }
482
483 public View getView() {
484 return mView;
485 }
486
487 final WindowLeaked getLocation() {
488 return mLocation;
489 }
490
491 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
492 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700493 int oldSoftInputMode = mWindowAttributes.softInputMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 if (newView) {
497 mSoftInputMode = attrs.softInputMode;
498 requestLayout();
499 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700500 // Don't lose the mode we last auto-computed.
501 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
502 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
503 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
504 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
505 | (oldSoftInputMode
506 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 mWindowAttributesChanged = true;
509 scheduleTraversals();
510 }
511 }
512
513 void handleAppVisibility(boolean visible) {
514 if (mAppVisible != visible) {
515 mAppVisible = visible;
516 scheduleTraversals();
517 }
518 }
519
520 void handleGetNewSurface() {
521 mNewSurfaceNeeded = true;
522 mFullRedrawNeeded = true;
523 scheduleTraversals();
524 }
525
526 /**
527 * {@inheritDoc}
528 */
529 public void requestLayout() {
530 checkThread();
531 mLayoutRequested = true;
532 scheduleTraversals();
533 }
534
535 /**
536 * {@inheritDoc}
537 */
538 public boolean isLayoutRequested() {
539 return mLayoutRequested;
540 }
541
542 public void invalidateChild(View child, Rect dirty) {
543 checkThread();
544 if (LOCAL_LOGV) Log.v(TAG, "Invalidate child: " + dirty);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700545 if (mCurScrollY != 0 || mCompatibilityInfo.mScalingRequired) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 mTempRect.set(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700547 if (mCurScrollY != 0) {
548 mTempRect.offset(0, -mCurScrollY);
549 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700550 if (mCompatibilityInfo.mScalingRequired) {
551 mTempRect.scale(mCompatibilityInfo.mApplicationScale);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 dirty = mTempRect;
554 }
555 mDirty.union(dirty);
556 if (!mWillDrawSoon) {
557 scheduleTraversals();
558 }
559 }
560
561 public ViewParent getParent() {
562 return null;
563 }
564
565 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
566 invalidateChild(null, dirty);
567 return null;
568 }
569
570 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
571 if (child != mView) {
572 throw new RuntimeException("child is not mine, honest!");
573 }
574 // Note: don't apply scroll offset, because we want to know its
575 // visibility in the virtual canvas being given to the view hierarchy.
576 return r.intersect(0, 0, mWidth, mHeight);
577 }
578
579 public void bringChildToFront(View child) {
580 }
581
582 public void scheduleTraversals() {
583 if (!mTraversalScheduled) {
584 mTraversalScheduled = true;
585 sendEmptyMessage(DO_TRAVERSAL);
586 }
587 }
588
589 public void unscheduleTraversals() {
590 if (mTraversalScheduled) {
591 mTraversalScheduled = false;
592 removeMessages(DO_TRAVERSAL);
593 }
594 }
595
596 int getHostVisibility() {
597 return mAppVisible ? mView.getVisibility() : View.GONE;
598 }
Romain Guy8506ab42009-06-11 17:35:47 -0700599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 private void performTraversals() {
601 // cache mView since it is used so much below...
602 final View host = mView;
603
604 if (DBG) {
605 System.out.println("======================================");
606 System.out.println("performTraversals");
607 host.debug();
608 }
609
610 if (host == null || !mAdded)
611 return;
612
613 mTraversalScheduled = false;
614 mWillDrawSoon = true;
615 boolean windowResizesToFitContent = false;
616 boolean fullRedrawNeeded = mFullRedrawNeeded;
617 boolean newSurface = false;
618 WindowManager.LayoutParams lp = mWindowAttributes;
619
620 int desiredWindowWidth;
621 int desiredWindowHeight;
622 int childWidthMeasureSpec;
623 int childHeightMeasureSpec;
624
625 final View.AttachInfo attachInfo = mAttachInfo;
626
627 final int viewVisibility = getHostVisibility();
628 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
629 || mNewSurfaceNeeded;
630
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700631 float appScale = mCompatibilityInfo.mApplicationScale;
632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 WindowManager.LayoutParams params = null;
634 if (mWindowAttributesChanged) {
635 mWindowAttributesChanged = false;
636 params = lp;
637 }
638
639 if (mFirst) {
640 fullRedrawNeeded = true;
641 mLayoutRequested = true;
642
Romain Guy8506ab42009-06-11 17:35:47 -0700643 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700644 mView.getContext().getResources().getDisplayMetrics();
645 desiredWindowWidth = packageMetrics.widthPixels;
646 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647
648 // For the very first time, tell the view hierarchy that it
649 // is attached to the window. Note that at this point the surface
650 // object is not initialized to its backing store, but soon it
651 // will be (assuming the window is visible).
652 attachInfo.mSurface = mSurface;
653 attachInfo.mHasWindowFocus = false;
654 attachInfo.mWindowVisibility = viewVisibility;
655 attachInfo.mRecomputeGlobalAttributes = false;
656 attachInfo.mKeepScreenOn = false;
657 viewVisibilityChanged = false;
658 host.dispatchAttachedToWindow(attachInfo, 0);
659 getRunQueue().executeActions(attachInfo.mHandler);
660 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 } else {
663 desiredWindowWidth = mWinFrame.width();
664 desiredWindowHeight = mWinFrame.height();
665 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
666 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
667 "View " + host + " resized to: " + mWinFrame);
668 fullRedrawNeeded = true;
669 mLayoutRequested = true;
670 windowResizesToFitContent = true;
671 }
672 }
673
674 if (viewVisibilityChanged) {
675 attachInfo.mWindowVisibility = viewVisibility;
676 host.dispatchWindowVisibilityChanged(viewVisibility);
677 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
678 if (mUseGL) {
679 destroyGL();
680 }
681 }
682 if (viewVisibility == View.GONE) {
683 // After making a window gone, we will count it as being
684 // shown for the first time the next time it gets focus.
685 mHasHadWindowFocus = false;
686 }
687 }
688
689 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 if (mLayoutRequested) {
692 if (mFirst) {
693 host.fitSystemWindows(mAttachInfo.mContentInsets);
694 // make sure touch mode code executes by setting cached value
695 // to opposite of the added touch mode.
696 mAttachInfo.mInTouchMode = !mAddedTouchMode;
697 ensureTouchModeLocally(mAddedTouchMode);
698 } else {
699 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
700 mAttachInfo.mContentInsets.set(mPendingContentInsets);
701 host.fitSystemWindows(mAttachInfo.mContentInsets);
702 insetsChanged = true;
703 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
704 + mAttachInfo.mContentInsets);
705 }
706 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
707 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
708 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
709 + mAttachInfo.mVisibleInsets);
710 }
711 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
712 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
713 windowResizesToFitContent = true;
714
Romain Guy8506ab42009-06-11 17:35:47 -0700715 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700716 mView.getContext().getResources().getDisplayMetrics();
717 desiredWindowWidth = packageMetrics.widthPixels;
718 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
720 }
721
722 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
723 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
724
725 // Ask host how big it wants to be
726 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
727 "Measuring " + host + " in display " + desiredWindowWidth
728 + "x" + desiredWindowHeight + "...");
729 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
730
731 if (DBG) {
732 System.out.println("======================================");
733 System.out.println("performTraversals -- after measure");
734 host.debug();
735 }
736 }
737
738 if (attachInfo.mRecomputeGlobalAttributes) {
739 //Log.i(TAG, "Computing screen on!");
740 attachInfo.mRecomputeGlobalAttributes = false;
741 boolean oldVal = attachInfo.mKeepScreenOn;
742 attachInfo.mKeepScreenOn = false;
743 host.dispatchCollectViewAttributes(0);
744 if (attachInfo.mKeepScreenOn != oldVal) {
745 params = lp;
746 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
747 }
748 }
749
750 if (mFirst || attachInfo.mViewVisibilityChanged) {
751 attachInfo.mViewVisibilityChanged = false;
752 int resizeMode = mSoftInputMode &
753 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
754 // If we are in auto resize mode, then we need to determine
755 // what mode to use now.
756 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
757 final int N = attachInfo.mScrollContainers.size();
758 for (int i=0; i<N; i++) {
759 if (attachInfo.mScrollContainers.get(i).isShown()) {
760 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
761 }
762 }
763 if (resizeMode == 0) {
764 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
765 }
766 if ((lp.softInputMode &
767 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
768 lp.softInputMode = (lp.softInputMode &
769 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
770 resizeMode;
771 params = lp;
772 }
773 }
774 }
Romain Guy8506ab42009-06-11 17:35:47 -0700775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
777 if (!PixelFormat.formatHasAlpha(params.format)) {
778 params.format = PixelFormat.TRANSLUCENT;
779 }
780 }
781
782 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
783 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
784
785 final boolean computesInternalInsets =
786 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
787 boolean insetsPending = false;
788 int relayoutResult = 0;
789 if (mFirst || windowShouldResize || insetsChanged
790 || viewVisibilityChanged || params != null) {
791
792 if (viewVisibility == View.VISIBLE) {
793 // If this window is giving internal insets to the window
794 // manager, and it is being added or changing its visibility,
795 // then we want to first give the window manager "fake"
796 // insets to cause it to effectively ignore the content of
797 // the window during layout. This avoids it briefly causing
798 // other windows to resize/move based on the raw frame of the
799 // window, waiting until we can finish laying out this window
800 // and get back to the window manager with the ultimately
801 // computed insets.
802 insetsPending = computesInternalInsets
803 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
806 if (params == null) {
807 params = mWindowAttributes;
808 }
809 mGlWanted = true;
810 }
811 }
812
813 final Rect frame = mWinFrame;
814 boolean initialized = false;
815 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700816 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 try {
818 boolean hadSurface = mSurface.isValid();
819 int fl = 0;
820 if (params != null) {
821 fl = params.flags;
822 if (attachInfo.mKeepScreenOn) {
823 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
824 }
825 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700826 if (DEBUG_LAYOUT) {
827 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
828 host.mMeasuredHeight + ", params=" + params);
829 }
830 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 if (params != null) {
833 params.flags = fl;
834 }
835
836 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
837 + " content=" + mPendingContentInsets.toShortString()
838 + " visible=" + mPendingVisibleInsets.toShortString()
839 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 contentInsetsChanged = !mPendingContentInsets.equals(
842 mAttachInfo.mContentInsets);
843 visibleInsetsChanged = !mPendingVisibleInsets.equals(
844 mAttachInfo.mVisibleInsets);
845 if (contentInsetsChanged) {
846 mAttachInfo.mContentInsets.set(mPendingContentInsets);
847 host.fitSystemWindows(mAttachInfo.mContentInsets);
848 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
849 + mAttachInfo.mContentInsets);
850 }
851 if (visibleInsetsChanged) {
852 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
853 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
854 + mAttachInfo.mVisibleInsets);
855 }
856
857 if (!hadSurface) {
858 if (mSurface.isValid()) {
859 // If we are creating a new surface, then we need to
860 // completely redraw it. Also, when we get to the
861 // point of drawing it we will hold off and schedule
862 // a new traversal instead. This is so we can tell the
863 // window manager about all of the windows being displayed
864 // before actually drawing them, so it can display then
865 // all at once.
866 newSurface = true;
867 fullRedrawNeeded = true;
Romain Guy8506ab42009-06-11 17:35:47 -0700868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 if (mGlWanted && !mUseGL) {
870 initializeGL();
871 initialized = mGlCanvas != null;
872 }
873 }
874 } else if (!mSurface.isValid()) {
875 // If the surface has been removed, then reset the scroll
876 // positions.
877 mLastScrolledFocus = null;
878 mScrollY = mCurScrollY = 0;
879 if (mScroller != null) {
880 mScroller.abortAnimation();
881 }
882 }
883 } catch (RemoteException e) {
884 }
885 if (DEBUG_ORIENTATION) Log.v(
886 "ViewRoot", "Relayout returned: frame=" + mWinFrame + ", surface=" + mSurface);
887
888 attachInfo.mWindowLeft = frame.left;
889 attachInfo.mWindowTop = frame.top;
890
891 // !!FIXME!! This next section handles the case where we did not get the
892 // window size we asked for. We should avoid this by getting a maximum size from
893 // the window session beforehand.
894 mWidth = frame.width();
895 mHeight = frame.height();
896
897 if (initialized) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700898 mGlCanvas.setViewport((int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
900
901 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
902 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
903 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
904 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
905 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
906 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
907
908 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
909 + mWidth + " measuredWidth=" + host.mMeasuredWidth
910 + " mHeight=" + mHeight
911 + " measuredHeight" + host.mMeasuredHeight
912 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 // Ask host how big it wants to be
915 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
916
917 // Implementation of weights from WindowManager.LayoutParams
918 // We just grow the dimensions as needed and re-measure if
919 // needs be
920 int width = host.mMeasuredWidth;
921 int height = host.mMeasuredHeight;
922 boolean measureAgain = false;
923
924 if (lp.horizontalWeight > 0.0f) {
925 width += (int) ((mWidth - width) * lp.horizontalWeight);
926 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
927 MeasureSpec.EXACTLY);
928 measureAgain = true;
929 }
930 if (lp.verticalWeight > 0.0f) {
931 height += (int) ((mHeight - height) * lp.verticalWeight);
932 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
933 MeasureSpec.EXACTLY);
934 measureAgain = true;
935 }
936
937 if (measureAgain) {
938 if (DEBUG_LAYOUT) Log.v(TAG,
939 "And hey let's measure once more: width=" + width
940 + " height=" + height);
941 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
942 }
943
944 mLayoutRequested = true;
945 }
946 }
947
948 final boolean didLayout = mLayoutRequested;
949 boolean triggerGlobalLayoutListener = didLayout
950 || attachInfo.mRecomputeGlobalAttributes;
951 if (didLayout) {
952 mLayoutRequested = false;
953 mScrollMayChange = true;
954 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
955 "ViewRoot", "Laying out " + host + " to (" +
956 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -0700957 long startTime = 0L;
958 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 startTime = SystemClock.elapsedRealtime();
960 }
961
962 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
963
Romain Guy13922e02009-05-12 17:56:14 -0700964 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
965 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
966 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
967 + "please refer to the logs with the tag "
968 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
969 }
970 }
971
972 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
974 }
975
976 // By this point all views have been sized and positionned
977 // We can compute the transparent area
978
979 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
980 // start out transparent
981 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
982 host.getLocationInWindow(mTmpLocation);
983 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
984 mTmpLocation[0] + host.mRight - host.mLeft,
985 mTmpLocation[1] + host.mBottom - host.mTop);
986
987 host.gatherTransparentRegion(mTransparentRegion);
Romain Guy8506ab42009-06-11 17:35:47 -0700988 mTransparentRegion.scale(appScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
990 mPreviousTransparentRegion.set(mTransparentRegion);
991 // reconfigure window manager
992 try {
993 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
994 } catch (RemoteException e) {
995 }
996 }
997 }
998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 if (DBG) {
1000 System.out.println("======================================");
1001 System.out.println("performTraversals -- after setFrame");
1002 host.debug();
1003 }
1004 }
1005
1006 if (triggerGlobalLayoutListener) {
1007 attachInfo.mRecomputeGlobalAttributes = false;
1008 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1009 }
1010
1011 if (computesInternalInsets) {
1012 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1013 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1014 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1015 givenContent.left = givenContent.top = givenContent.right
1016 = givenContent.bottom = givenVisible.left = givenVisible.top
1017 = givenVisible.right = givenVisible.bottom = 0;
1018 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001019 if (mCompatibilityInfo.mScalingRequired) {
1020 insets.contentInsets.scale(appScale);
1021 insets.visibleInsets.scale(appScale);
1022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1024 mLastGivenInsets.set(insets);
1025 try {
1026 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
1027 insets.contentInsets, insets.visibleInsets);
1028 } catch (RemoteException e) {
1029 }
1030 }
1031 }
Romain Guy8506ab42009-06-11 17:35:47 -07001032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 if (mFirst) {
1034 // handle first focus request
1035 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1036 + mView.hasFocus());
1037 if (mView != null) {
1038 if (!mView.hasFocus()) {
1039 mView.requestFocus(View.FOCUS_FORWARD);
1040 mFocusedView = mRealFocusedView = mView.findFocus();
1041 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1042 + mFocusedView);
1043 } else {
1044 mRealFocusedView = mView.findFocus();
1045 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1046 + mRealFocusedView);
1047 }
1048 }
1049 }
1050
1051 mFirst = false;
1052 mWillDrawSoon = false;
1053 mNewSurfaceNeeded = false;
1054 mViewVisibility = viewVisibility;
1055
1056 if (mAttachInfo.mHasWindowFocus) {
1057 final boolean imTarget = WindowManager.LayoutParams
1058 .mayUseInputMethod(mWindowAttributes.flags);
1059 if (imTarget != mLastWasImTarget) {
1060 mLastWasImTarget = imTarget;
1061 InputMethodManager imm = InputMethodManager.peekInstance();
1062 if (imm != null && imTarget) {
1063 imm.startGettingWindowFocus(mView);
1064 imm.onWindowFocus(mView, mView.findFocus(),
1065 mWindowAttributes.softInputMode,
1066 !mHasHadWindowFocus, mWindowAttributes.flags);
1067 }
1068 }
1069 }
Romain Guy8506ab42009-06-11 17:35:47 -07001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1072
1073 if (!cancelDraw && !newSurface) {
1074 mFullRedrawNeeded = false;
1075 draw(fullRedrawNeeded);
1076
1077 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1078 || mReportNextDraw) {
1079 if (LOCAL_LOGV) {
1080 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1081 }
1082 mReportNextDraw = false;
1083 try {
1084 sWindowSession.finishDrawing(mWindow);
1085 } catch (RemoteException e) {
1086 }
1087 }
1088 } else {
1089 // We were supposed to report when we are done drawing. Since we canceled the
1090 // draw, remember it here.
1091 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1092 mReportNextDraw = true;
1093 }
1094 if (fullRedrawNeeded) {
1095 mFullRedrawNeeded = true;
1096 }
1097 // Try again
1098 scheduleTraversals();
1099 }
1100 }
1101
1102 public void requestTransparentRegion(View child) {
1103 // the test below should not fail unless someone is messing with us
1104 checkThread();
1105 if (mView == child) {
1106 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1107 // Need to make sure we re-evaluate the window attributes next
1108 // time around, to ensure the window has the correct format.
1109 mWindowAttributesChanged = true;
1110 }
1111 }
1112
1113 /**
1114 * Figures out the measure spec for the root view in a window based on it's
1115 * layout params.
1116 *
1117 * @param windowSize
1118 * The available width or height of the window
1119 *
1120 * @param rootDimension
1121 * The layout params for one dimension (width or height) of the
1122 * window.
1123 *
1124 * @return The measure spec to use to measure the root view.
1125 */
1126 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1127 int measureSpec;
1128 switch (rootDimension) {
1129
1130 case ViewGroup.LayoutParams.FILL_PARENT:
1131 // Window can't resize. Force root view to be windowSize.
1132 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1133 break;
1134 case ViewGroup.LayoutParams.WRAP_CONTENT:
1135 // Window can resize. Set max size for root view.
1136 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1137 break;
1138 default:
1139 // Window wants to be an exact size. Force root view to be that size.
1140 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1141 break;
1142 }
1143 return measureSpec;
1144 }
1145
1146 private void draw(boolean fullRedrawNeeded) {
1147 Surface surface = mSurface;
1148 if (surface == null || !surface.isValid()) {
1149 return;
1150 }
1151
1152 scrollToRectOrFocus(null, false);
1153
1154 if (mAttachInfo.mViewScrollChanged) {
1155 mAttachInfo.mViewScrollChanged = false;
1156 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1157 }
Romain Guy8506ab42009-06-11 17:35:47 -07001158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001160 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 if (scrolling) {
1162 yoff = mScroller.getCurrY();
1163 } else {
1164 yoff = mScrollY;
1165 }
1166 if (mCurScrollY != yoff) {
1167 mCurScrollY = yoff;
1168 fullRedrawNeeded = true;
1169 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001170 float appScale = mCompatibilityInfo.mApplicationScale;
1171 boolean scalingRequired = mCompatibilityInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172
1173 Rect dirty = mDirty;
1174 if (mUseGL) {
1175 if (!dirty.isEmpty()) {
1176 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001177 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 mGL.glDisable(GL_SCISSOR_TEST);
1179 mGL.glClearColor(0, 0, 0, 0);
1180 mGL.glClear(GL_COLOR_BUFFER_BIT);
1181 mGL.glEnable(GL_SCISSOR_TEST);
1182
1183 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001184 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001186
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001187 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1188 try {
1189 canvas.translate(0, -yoff);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001190 if (scalingRequired) {
1191 canvas.scale(appScale, appScale);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001192 }
1193 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001194 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1195 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1196 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001197 } finally {
1198 canvas.restoreToCount(saveCount);
1199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200
Romain Guy5bcdff42009-05-14 21:27:18 -07001201 mAttachInfo.mIgnoreDirtyState = false;
1202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1204 checkEglErrors();
1205
Romain Guy13922e02009-05-12 17:56:14 -07001206 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 int now = (int)SystemClock.elapsedRealtime();
1208 if (sDrawTime != 0) {
1209 nativeShowFPS(canvas, now - sDrawTime);
1210 }
1211 sDrawTime = now;
1212 }
1213 }
1214 }
1215 if (scrolling) {
1216 mFullRedrawNeeded = true;
1217 scheduleTraversals();
1218 }
1219 return;
1220 }
1221
Romain Guy5bcdff42009-05-14 21:27:18 -07001222 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001223 mAttachInfo.mIgnoreDirtyState = true;
1224 dirty.union(0, 0, (int) (mWidth * appScale), (int) (mHeight * appScale));
Romain Guy5bcdff42009-05-14 21:27:18 -07001225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226
1227 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1228 Log.v("ViewRoot", "Draw " + mView + "/"
1229 + mWindowAttributes.getTitle()
1230 + ": dirty={" + dirty.left + "," + dirty.top
1231 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001232 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1233 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
1235
1236 Canvas canvas;
1237 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001238 int left = dirty.left;
1239 int top = dirty.top;
1240 int right = dirty.right;
1241 int bottom = dirty.bottom;
1242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001244
1245 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1246 bottom != dirty.bottom) {
1247 mAttachInfo.mIgnoreDirtyState = true;
1248 }
1249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 // TODO: Do this in native
1251 canvas.setDensityScale(mDensity);
1252 } catch (Surface.OutOfResourcesException e) {
1253 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1254 // TODO: we should ask the window manager to do something!
1255 // for now we just do nothing
1256 return;
1257 }
1258
1259 try {
Romain Guybb93d552009-03-24 21:04:15 -07001260 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001261 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262
1263 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1264 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1265 + canvas.getWidth() + ", h=" + canvas.getHeight());
1266 //canvas.drawARGB(255, 255, 0, 0);
1267 }
1268
Romain Guy13922e02009-05-12 17:56:14 -07001269 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 startTime = SystemClock.elapsedRealtime();
1271 }
1272
1273 // If this bitmap's format includes an alpha channel, we
1274 // need to clear it before drawing so that the child will
1275 // properly re-composite its drawing on a transparent
1276 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001277 // or
1278 // If we are applying an offset, we need to clear the area
1279 // where the offset doesn't appear to avoid having garbage
1280 // left in the blank areas.
1281 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1283 }
1284
1285 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001286 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001288 mView.mPrivateFlags |= View.DRAWN;
1289
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001290 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001291 Context cxt = mView.getContext();
1292 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001293 ", metrics=" + mView.getContext().getResources().getDisplayMetrics());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001294 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001295 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001296 try {
1297 canvas.translate(0, -yoff);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001298 if (scalingRequired) {
1299 canvas.scale(appScale, appScale);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001300 }
1301 mView.draw(canvas);
1302 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001303 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001304 canvas.restoreToCount(saveCount);
1305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306
Romain Guy5bcdff42009-05-14 21:27:18 -07001307 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1308 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1309 }
1310
Romain Guy13922e02009-05-12 17:56:14 -07001311 if (Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 int now = (int)SystemClock.elapsedRealtime();
1313 if (sDrawTime != 0) {
1314 nativeShowFPS(canvas, now - sDrawTime);
1315 }
1316 sDrawTime = now;
1317 }
1318
Romain Guy13922e02009-05-12 17:56:14 -07001319 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1321 }
1322 }
Romain Guy8506ab42009-06-11 17:35:47 -07001323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 } finally {
1325 surface.unlockCanvasAndPost(canvas);
1326 }
1327
1328 if (LOCAL_LOGV) {
1329 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1330 }
Romain Guy8506ab42009-06-11 17:35:47 -07001331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 if (scrolling) {
1333 mFullRedrawNeeded = true;
1334 scheduleTraversals();
1335 }
1336 }
1337
1338 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1339 final View.AttachInfo attachInfo = mAttachInfo;
1340 final Rect ci = attachInfo.mContentInsets;
1341 final Rect vi = attachInfo.mVisibleInsets;
1342 int scrollY = 0;
1343 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 if (vi.left > ci.left || vi.top > ci.top
1346 || vi.right > ci.right || vi.bottom > ci.bottom) {
1347 // We'll assume that we aren't going to change the scroll
1348 // offset, since we want to avoid that unless it is actually
1349 // going to make the focus visible... otherwise we scroll
1350 // all over the place.
1351 scrollY = mScrollY;
1352 // We can be called for two different situations: during a draw,
1353 // to update the scroll position if the focus has changed (in which
1354 // case 'rectangle' is null), or in response to a
1355 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1356 // is non-null and we just want to scroll to whatever that
1357 // rectangle is).
1358 View focus = mRealFocusedView;
1359 if (focus != mLastScrolledFocus) {
1360 // If the focus has changed, then ignore any requests to scroll
1361 // to a rectangle; first we want to make sure the entire focus
1362 // view is visible.
1363 rectangle = null;
1364 }
1365 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1366 + " rectangle=" + rectangle + " ci=" + ci
1367 + " vi=" + vi);
1368 if (focus == mLastScrolledFocus && !mScrollMayChange
1369 && rectangle == null) {
1370 // Optimization: if the focus hasn't changed since last
1371 // time, and no layout has happened, then just leave things
1372 // as they are.
1373 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1374 + mScrollY + " vi=" + vi.toShortString());
1375 } else if (focus != null) {
1376 // We need to determine if the currently focused view is
1377 // within the visible part of the window and, if not, apply
1378 // a pan so it can be seen.
1379 mLastScrolledFocus = focus;
1380 mScrollMayChange = false;
1381 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1382 // Try to find the rectangle from the focus view.
1383 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1384 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1385 + mView.getWidth() + " h=" + mView.getHeight()
1386 + " ci=" + ci.toShortString()
1387 + " vi=" + vi.toShortString());
1388 if (rectangle == null) {
1389 focus.getFocusedRect(mTempRect);
1390 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1391 + ": focusRect=" + mTempRect.toShortString());
1392 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1393 focus, mTempRect);
1394 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1395 "Focus in window: focusRect="
1396 + mTempRect.toShortString()
1397 + " visRect=" + mVisRect.toShortString());
1398 } else {
1399 mTempRect.set(rectangle);
1400 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1401 "Request scroll to rect: "
1402 + mTempRect.toShortString()
1403 + " visRect=" + mVisRect.toShortString());
1404 }
1405 if (mTempRect.intersect(mVisRect)) {
1406 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1407 "Focus window visible rect: "
1408 + mTempRect.toShortString());
1409 if (mTempRect.height() >
1410 (mView.getHeight()-vi.top-vi.bottom)) {
1411 // If the focus simply is not going to fit, then
1412 // best is probably just to leave things as-is.
1413 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1414 "Too tall; leaving scrollY=" + scrollY);
1415 } else if ((mTempRect.top-scrollY) < vi.top) {
1416 scrollY -= vi.top - (mTempRect.top-scrollY);
1417 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1418 "Top covered; scrollY=" + scrollY);
1419 } else if ((mTempRect.bottom-scrollY)
1420 > (mView.getHeight()-vi.bottom)) {
1421 scrollY += (mTempRect.bottom-scrollY)
1422 - (mView.getHeight()-vi.bottom);
1423 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1424 "Bottom covered; scrollY=" + scrollY);
1425 }
1426 handled = true;
1427 }
1428 }
1429 }
1430 }
Romain Guy8506ab42009-06-11 17:35:47 -07001431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 if (scrollY != mScrollY) {
1433 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1434 + mScrollY + " , new=" + scrollY);
1435 if (!immediate) {
1436 if (mScroller == null) {
1437 mScroller = new Scroller(mView.getContext());
1438 }
1439 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1440 } else if (mScroller != null) {
1441 mScroller.abortAnimation();
1442 }
1443 mScrollY = scrollY;
1444 }
Romain Guy8506ab42009-06-11 17:35:47 -07001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 return handled;
1447 }
Romain Guy8506ab42009-06-11 17:35:47 -07001448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 public void requestChildFocus(View child, View focused) {
1450 checkThread();
1451 if (mFocusedView != focused) {
1452 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1453 scheduleTraversals();
1454 }
1455 mFocusedView = mRealFocusedView = focused;
1456 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1457 + mFocusedView);
1458 }
1459
1460 public void clearChildFocus(View child) {
1461 checkThread();
1462
1463 View oldFocus = mFocusedView;
1464
1465 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1466 mFocusedView = mRealFocusedView = null;
1467 if (mView != null && !mView.hasFocus()) {
1468 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1469 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1470 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1471 }
1472 } else if (oldFocus != null) {
1473 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1474 }
1475 }
1476
1477
1478 public void focusableViewAvailable(View v) {
1479 checkThread();
1480
1481 if (mView != null && !mView.hasFocus()) {
1482 v.requestFocus();
1483 } else {
1484 // the one case where will transfer focus away from the current one
1485 // is if the current view is a view group that prefers to give focus
1486 // to its children first AND the view is a descendant of it.
1487 mFocusedView = mView.findFocus();
1488 boolean descendantsHaveDibsOnFocus =
1489 (mFocusedView instanceof ViewGroup) &&
1490 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1491 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1492 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1493 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1494 v.requestFocus();
1495 }
1496 }
1497 }
1498
1499 public void recomputeViewAttributes(View child) {
1500 checkThread();
1501 if (mView == child) {
1502 mAttachInfo.mRecomputeGlobalAttributes = true;
1503 if (!mWillDrawSoon) {
1504 scheduleTraversals();
1505 }
1506 }
1507 }
1508
1509 void dispatchDetachedFromWindow() {
1510 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1511
1512 if (mView != null) {
1513 mView.dispatchDetachedFromWindow();
1514 }
1515
1516 mView = null;
1517 mAttachInfo.mRootView = null;
1518
1519 if (mUseGL) {
1520 destroyGL();
1521 }
1522
1523 try {
1524 sWindowSession.remove(mWindow);
1525 } catch (RemoteException e) {
1526 }
1527 }
Romain Guy8506ab42009-06-11 17:35:47 -07001528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 /**
1530 * Return true if child is an ancestor of parent, (or equal to the parent).
1531 */
1532 private static boolean isViewDescendantOf(View child, View parent) {
1533 if (child == parent) {
1534 return true;
1535 }
1536
1537 final ViewParent theParent = child.getParent();
1538 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1539 }
1540
1541
1542 public final static int DO_TRAVERSAL = 1000;
1543 public final static int DIE = 1001;
1544 public final static int RESIZED = 1002;
1545 public final static int RESIZED_REPORT = 1003;
1546 public final static int WINDOW_FOCUS_CHANGED = 1004;
1547 public final static int DISPATCH_KEY = 1005;
1548 public final static int DISPATCH_POINTER = 1006;
1549 public final static int DISPATCH_TRACKBALL = 1007;
1550 public final static int DISPATCH_APP_VISIBILITY = 1008;
1551 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1552 public final static int FINISHED_EVENT = 1010;
1553 public final static int DISPATCH_KEY_FROM_IME = 1011;
1554 public final static int FINISH_INPUT_CONNECTION = 1012;
1555 public final static int CHECK_FOCUS = 1013;
1556
1557 @Override
1558 public void handleMessage(Message msg) {
1559 switch (msg.what) {
1560 case View.AttachInfo.INVALIDATE_MSG:
1561 ((View) msg.obj).invalidate();
1562 break;
1563 case View.AttachInfo.INVALIDATE_RECT_MSG:
1564 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1565 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1566 info.release();
1567 break;
1568 case DO_TRAVERSAL:
1569 if (mProfile) {
1570 Debug.startMethodTracing("ViewRoot");
1571 }
1572
1573 performTraversals();
1574
1575 if (mProfile) {
1576 Debug.stopMethodTracing();
1577 mProfile = false;
1578 }
1579 break;
1580 case FINISHED_EVENT:
1581 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1582 break;
1583 case DISPATCH_KEY:
1584 if (LOCAL_LOGV) Log.v(
1585 "ViewRoot", "Dispatching key "
1586 + msg.obj + " to " + mView);
1587 deliverKeyEvent((KeyEvent)msg.obj, true);
1588 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001589 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 MotionEvent event = (MotionEvent)msg.obj;
1591
1592 boolean didFinish;
1593 if (event == null) {
1594 try {
1595 event = sWindowSession.getPendingPointerMove(mWindow);
1596 } catch (RemoteException e) {
1597 }
1598 didFinish = true;
1599 } else {
1600 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
1601 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001602 if (event != null && mCompatibilityInfo.mScalingRequired) {
1603 event.scale(mCompatibilityInfo.mApplicationInvertedScale);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605
1606 try {
1607 boolean handled;
1608 if (mView != null && mAdded && event != null) {
1609
1610 // enter touch mode on the down
1611 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1612 if (isDown) {
1613 ensureTouchMode(true);
1614 }
1615 if(Config.LOGV) {
1616 captureMotionLog("captureDispatchPointer", event);
1617 }
1618 event.offsetLocation(0, mCurScrollY);
1619 handled = mView.dispatchTouchEvent(event);
1620 if (!handled && isDown) {
1621 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1622
1623 final int edgeFlags = event.getEdgeFlags();
1624 int direction = View.FOCUS_UP;
1625 int x = (int)event.getX();
1626 int y = (int)event.getY();
1627 final int[] deltas = new int[2];
1628
1629 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1630 direction = View.FOCUS_DOWN;
1631 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1632 deltas[0] = edgeSlop;
1633 x += edgeSlop;
1634 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1635 deltas[0] = -edgeSlop;
1636 x -= edgeSlop;
1637 }
1638 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1639 direction = View.FOCUS_UP;
1640 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1641 deltas[0] = edgeSlop;
1642 x += edgeSlop;
1643 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1644 deltas[0] = -edgeSlop;
1645 x -= edgeSlop;
1646 }
1647 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1648 direction = View.FOCUS_RIGHT;
1649 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1650 direction = View.FOCUS_LEFT;
1651 }
1652
1653 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1654 View nearest = FocusFinder.getInstance().findNearestTouchable(
1655 ((ViewGroup) mView), x, y, direction, deltas);
1656 if (nearest != null) {
1657 event.offsetLocation(deltas[0], deltas[1]);
1658 event.setEdgeFlags(0);
1659 mView.dispatchTouchEvent(event);
1660 }
1661 }
1662 }
1663 }
1664 } finally {
1665 if (!didFinish) {
1666 try {
1667 sWindowSession.finishKey(mWindow);
1668 } catch (RemoteException e) {
1669 }
1670 }
1671 if (event != null) {
1672 event.recycle();
1673 }
1674 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1675 // Let the exception fall through -- the looper will catch
1676 // it and take care of the bad app for us.
1677 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001678 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 case DISPATCH_TRACKBALL:
1680 deliverTrackballEvent((MotionEvent)msg.obj);
1681 break;
1682 case DISPATCH_APP_VISIBILITY:
1683 handleAppVisibility(msg.arg1 != 0);
1684 break;
1685 case DISPATCH_GET_NEW_SURFACE:
1686 handleGetNewSurface();
1687 break;
1688 case RESIZED:
1689 Rect coveredInsets = ((Rect[])msg.obj)[0];
1690 Rect visibleInsets = ((Rect[])msg.obj)[1];
1691 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
1692 && mPendingContentInsets.equals(coveredInsets)
1693 && mPendingVisibleInsets.equals(visibleInsets)) {
1694 break;
1695 }
1696 // fall through...
1697 case RESIZED_REPORT:
1698 if (mAdded) {
1699 mWinFrame.left = 0;
1700 mWinFrame.right = msg.arg1;
1701 mWinFrame.top = 0;
1702 mWinFrame.bottom = msg.arg2;
1703 mPendingContentInsets.set(((Rect[])msg.obj)[0]);
1704 mPendingVisibleInsets.set(((Rect[])msg.obj)[1]);
1705 if (msg.what == RESIZED_REPORT) {
1706 mReportNextDraw = true;
1707 }
1708 requestLayout();
1709 }
1710 break;
1711 case WINDOW_FOCUS_CHANGED: {
1712 if (mAdded) {
1713 boolean hasWindowFocus = msg.arg1 != 0;
1714 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1715 if (hasWindowFocus) {
1716 boolean inTouchMode = msg.arg2 != 0;
1717 ensureTouchModeLocally(inTouchMode);
1718
1719 if (mGlWanted) {
1720 checkEglErrors();
1721 // we lost the gl context, so recreate it.
1722 if (mGlWanted && !mUseGL) {
1723 initializeGL();
1724 if (mGlCanvas != null) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001725 float appScale = mCompatibilityInfo.mApplicationScale;
1726 mGlCanvas.setViewport(
1727 (int) (mWidth * appScale), (int) (mHeight * appScale));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729 }
1730 }
1731 }
Romain Guy8506ab42009-06-11 17:35:47 -07001732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 mLastWasImTarget = WindowManager.LayoutParams
1734 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 InputMethodManager imm = InputMethodManager.peekInstance();
1737 if (mView != null) {
1738 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1739 imm.startGettingWindowFocus(mView);
1740 }
1741 mView.dispatchWindowFocusChanged(hasWindowFocus);
1742 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 // Note: must be done after the focus change callbacks,
1745 // so all of the view state is set up correctly.
1746 if (hasWindowFocus) {
1747 if (imm != null && mLastWasImTarget) {
1748 imm.onWindowFocus(mView, mView.findFocus(),
1749 mWindowAttributes.softInputMode,
1750 !mHasHadWindowFocus, mWindowAttributes.flags);
1751 }
1752 // Clear the forward bit. We can just do this directly, since
1753 // the window manager doesn't care about it.
1754 mWindowAttributes.softInputMode &=
1755 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1756 ((WindowManager.LayoutParams)mView.getLayoutParams())
1757 .softInputMode &=
1758 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1759 mHasHadWindowFocus = true;
1760 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001761
1762 if (hasWindowFocus && mView != null) {
1763 sendAccessibilityEvents();
1764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
1766 } break;
1767 case DIE:
1768 dispatchDetachedFromWindow();
1769 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001770 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 if (LOCAL_LOGV) Log.v(
1772 "ViewRoot", "Dispatching key "
1773 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001774 KeyEvent event = (KeyEvent)msg.obj;
1775 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1776 // The IME is trying to say this event is from the
1777 // system! Bad bad bad!
1778 event = KeyEvent.changeFlags(event,
1779 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001782 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 case FINISH_INPUT_CONNECTION: {
1784 InputMethodManager imm = InputMethodManager.peekInstance();
1785 if (imm != null) {
1786 imm.reportFinishInputConnection((InputConnection)msg.obj);
1787 }
1788 } break;
1789 case CHECK_FOCUS: {
1790 InputMethodManager imm = InputMethodManager.peekInstance();
1791 if (imm != null) {
1792 imm.checkFocus();
1793 }
1794 } break;
1795 }
1796 }
1797
1798 /**
1799 * Something in the current window tells us we need to change the touch mode. For
1800 * example, we are not in touch mode, and the user touches the screen.
1801 *
1802 * If the touch mode has changed, tell the window manager, and handle it locally.
1803 *
1804 * @param inTouchMode Whether we want to be in touch mode.
1805 * @return True if the touch mode changed and focus changed was changed as a result
1806 */
1807 boolean ensureTouchMode(boolean inTouchMode) {
1808 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1809 + "touch mode is " + mAttachInfo.mInTouchMode);
1810 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1811
1812 // tell the window manager
1813 try {
1814 sWindowSession.setInTouchMode(inTouchMode);
1815 } catch (RemoteException e) {
1816 throw new RuntimeException(e);
1817 }
1818
1819 // handle the change
1820 return ensureTouchModeLocally(inTouchMode);
1821 }
1822
1823 /**
1824 * Ensure that the touch mode for this window is set, and if it is changing,
1825 * take the appropriate action.
1826 * @param inTouchMode Whether we want to be in touch mode.
1827 * @return True if the touch mode changed and focus changed was changed as a result
1828 */
1829 private boolean ensureTouchModeLocally(boolean inTouchMode) {
1830 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1831 + "touch mode is " + mAttachInfo.mInTouchMode);
1832
1833 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1834
1835 mAttachInfo.mInTouchMode = inTouchMode;
1836 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1837
1838 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
1839 }
1840
1841 private boolean enterTouchMode() {
1842 if (mView != null) {
1843 if (mView.hasFocus()) {
1844 // note: not relying on mFocusedView here because this could
1845 // be when the window is first being added, and mFocused isn't
1846 // set yet.
1847 final View focused = mView.findFocus();
1848 if (focused != null && !focused.isFocusableInTouchMode()) {
1849
1850 final ViewGroup ancestorToTakeFocus =
1851 findAncestorToTakeFocusInTouchMode(focused);
1852 if (ancestorToTakeFocus != null) {
1853 // there is an ancestor that wants focus after its descendants that
1854 // is focusable in touch mode.. give it focus
1855 return ancestorToTakeFocus.requestFocus();
1856 } else {
1857 // nothing appropriate to have focus in touch mode, clear it out
1858 mView.unFocus();
1859 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1860 mFocusedView = null;
1861 return true;
1862 }
1863 }
1864 }
1865 }
1866 return false;
1867 }
1868
1869
1870 /**
1871 * Find an ancestor of focused that wants focus after its descendants and is
1872 * focusable in touch mode.
1873 * @param focused The currently focused view.
1874 * @return An appropriate view, or null if no such view exists.
1875 */
1876 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1877 ViewParent parent = focused.getParent();
1878 while (parent instanceof ViewGroup) {
1879 final ViewGroup vgParent = (ViewGroup) parent;
1880 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1881 && vgParent.isFocusableInTouchMode()) {
1882 return vgParent;
1883 }
1884 if (vgParent.isRootNamespace()) {
1885 return null;
1886 } else {
1887 parent = vgParent.getParent();
1888 }
1889 }
1890 return null;
1891 }
1892
1893 private boolean leaveTouchMode() {
1894 if (mView != null) {
1895 if (mView.hasFocus()) {
1896 // i learned the hard way to not trust mFocusedView :)
1897 mFocusedView = mView.findFocus();
1898 if (!(mFocusedView instanceof ViewGroup)) {
1899 // some view has focus, let it keep it
1900 return false;
1901 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1902 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1903 // some view group has focus, and doesn't prefer its children
1904 // over itself for focus, so let them keep it.
1905 return false;
1906 }
1907 }
1908
1909 // find the best view to give focus to in this brave new non-touch-mode
1910 // world
1911 final View focused = focusSearch(null, View.FOCUS_DOWN);
1912 if (focused != null) {
1913 return focused.requestFocus(View.FOCUS_DOWN);
1914 }
1915 }
1916 return false;
1917 }
1918
1919
1920 private void deliverTrackballEvent(MotionEvent event) {
1921 boolean didFinish;
1922 if (event == null) {
1923 try {
1924 event = sWindowSession.getPendingTrackballMove(mWindow);
1925 } catch (RemoteException e) {
1926 }
1927 didFinish = true;
1928 } else {
1929 didFinish = false;
1930 }
1931
1932 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
1933
1934 boolean handled = false;
1935 try {
1936 if (event == null) {
1937 handled = true;
1938 } else if (mView != null && mAdded) {
1939 handled = mView.dispatchTrackballEvent(event);
1940 if (!handled) {
1941 // we could do something here, like changing the focus
1942 // or something?
1943 }
1944 }
1945 } finally {
1946 if (handled) {
1947 if (!didFinish) {
1948 try {
1949 sWindowSession.finishKey(mWindow);
1950 } catch (RemoteException e) {
1951 }
1952 }
1953 if (event != null) {
1954 event.recycle();
1955 }
1956 // If we reach this, we delivered a trackball event to mView and
1957 // mView consumed it. Because we will not translate the trackball
1958 // event into a key event, touch mode will not exit, so we exit
1959 // touch mode here.
1960 ensureTouchMode(false);
1961 //noinspection ReturnInsideFinallyBlock
1962 return;
1963 }
1964 // Let the exception fall through -- the looper will catch
1965 // it and take care of the bad app for us.
1966 }
1967
1968 final TrackballAxis x = mTrackballAxisX;
1969 final TrackballAxis y = mTrackballAxisY;
1970
1971 long curTime = SystemClock.uptimeMillis();
1972 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
1973 // It has been too long since the last movement,
1974 // so restart at the beginning.
1975 x.reset(0);
1976 y.reset(0);
1977 mLastTrackballTime = curTime;
1978 }
1979
1980 try {
1981 final int action = event.getAction();
1982 final int metastate = event.getMetaState();
1983 switch (action) {
1984 case MotionEvent.ACTION_DOWN:
1985 x.reset(2);
1986 y.reset(2);
1987 deliverKeyEvent(new KeyEvent(curTime, curTime,
1988 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
1989 0, metastate), false);
1990 break;
1991 case MotionEvent.ACTION_UP:
1992 x.reset(2);
1993 y.reset(2);
1994 deliverKeyEvent(new KeyEvent(curTime, curTime,
1995 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
1996 0, metastate), false);
1997 break;
1998 }
1999
2000 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2001 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2002 + " move=" + event.getX()
2003 + " / Y=" + y.position + " step="
2004 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2005 + " move=" + event.getY());
2006 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2007 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2008
2009 // Generate DPAD events based on the trackball movement.
2010 // We pick the axis that has moved the most as the direction of
2011 // the DPAD. When we generate DPAD events for one axis, then the
2012 // other axis is reset -- we don't want to perform DPAD jumps due
2013 // to slight movements in the trackball when making major movements
2014 // along the other axis.
2015 int keycode = 0;
2016 int movement = 0;
2017 float accel = 1;
2018 if (xOff > yOff) {
2019 movement = x.generate((2/event.getXPrecision()));
2020 if (movement != 0) {
2021 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2022 : KeyEvent.KEYCODE_DPAD_LEFT;
2023 accel = x.acceleration;
2024 y.reset(2);
2025 }
2026 } else if (yOff > 0) {
2027 movement = y.generate((2/event.getYPrecision()));
2028 if (movement != 0) {
2029 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2030 : KeyEvent.KEYCODE_DPAD_UP;
2031 accel = y.acceleration;
2032 x.reset(2);
2033 }
2034 }
2035
2036 if (keycode != 0) {
2037 if (movement < 0) movement = -movement;
2038 int accelMovement = (int)(movement * accel);
2039 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2040 + " accelMovement=" + accelMovement
2041 + " accel=" + accel);
2042 if (accelMovement > movement) {
2043 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2044 + keycode);
2045 movement--;
2046 deliverKeyEvent(new KeyEvent(curTime, curTime,
2047 KeyEvent.ACTION_MULTIPLE, keycode,
2048 accelMovement-movement, metastate), false);
2049 }
2050 while (movement > 0) {
2051 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2052 + keycode);
2053 movement--;
2054 curTime = SystemClock.uptimeMillis();
2055 deliverKeyEvent(new KeyEvent(curTime, curTime,
2056 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2057 deliverKeyEvent(new KeyEvent(curTime, curTime,
2058 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2059 }
2060 mLastTrackballTime = curTime;
2061 }
2062 } finally {
2063 if (!didFinish) {
2064 try {
2065 sWindowSession.finishKey(mWindow);
2066 } catch (RemoteException e) {
2067 }
2068 if (event != null) {
2069 event.recycle();
2070 }
2071 }
2072 // Let the exception fall through -- the looper will catch
2073 // it and take care of the bad app for us.
2074 }
2075 }
2076
2077 /**
2078 * @param keyCode The key code
2079 * @return True if the key is directional.
2080 */
2081 static boolean isDirectional(int keyCode) {
2082 switch (keyCode) {
2083 case KeyEvent.KEYCODE_DPAD_LEFT:
2084 case KeyEvent.KEYCODE_DPAD_RIGHT:
2085 case KeyEvent.KEYCODE_DPAD_UP:
2086 case KeyEvent.KEYCODE_DPAD_DOWN:
2087 return true;
2088 }
2089 return false;
2090 }
2091
2092 /**
2093 * Returns true if this key is a keyboard key.
2094 * @param keyEvent The key event.
2095 * @return whether this key is a keyboard key.
2096 */
2097 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2098 final int convertedKey = keyEvent.getUnicodeChar();
2099 return convertedKey > 0;
2100 }
2101
2102
2103
2104 /**
2105 * See if the key event means we should leave touch mode (and leave touch
2106 * mode if so).
2107 * @param event The key event.
2108 * @return Whether this key event should be consumed (meaning the act of
2109 * leaving touch mode alone is considered the event).
2110 */
2111 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
2112 if (event.getAction() != KeyEvent.ACTION_DOWN) {
2113 return false;
2114 }
2115 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2116 return false;
2117 }
2118
2119 // only relevant if we are in touch mode
2120 if (!mAttachInfo.mInTouchMode) {
2121 return false;
2122 }
2123
2124 // if something like an edit text has focus and the user is typing,
2125 // leave touch mode
2126 //
2127 // note: the condition of not being a keyboard key is kind of a hacky
2128 // approximation of whether we think the focused view will want the
2129 // key; if we knew for sure whether the focused view would consume
2130 // the event, that would be better.
2131 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2132 mFocusedView = mView.findFocus();
2133 if ((mFocusedView instanceof ViewGroup)
2134 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2135 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2136 // something has focus, but is holding it weakly as a container
2137 return false;
2138 }
2139 if (ensureTouchMode(false)) {
2140 throw new IllegalStateException("should not have changed focus "
2141 + "when leaving touch mode while a view has focus.");
2142 }
2143 return false;
2144 }
2145
2146 if (isDirectional(event.getKeyCode())) {
2147 // no view has focus, so we leave touch mode (and find something
2148 // to give focus to). the event is consumed if we were able to
2149 // find something to give focus to.
2150 return ensureTouchMode(false);
2151 }
2152 return false;
2153 }
2154
2155 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002156 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 */
2158 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002159 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 if (ev == null ||
2161 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2162 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 }
Romain Guy8506ab42009-06-11 17:35:47 -07002164
2165 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 sb.append(ev.getDownTime()).append(',');
2167 sb.append(ev.getEventTime()).append(',');
2168 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002169 sb.append(ev.getX()).append(',');
2170 sb.append(ev.getY()).append(',');
2171 sb.append(ev.getPressure()).append(',');
2172 sb.append(ev.getSize()).append(',');
2173 sb.append(ev.getMetaState()).append(',');
2174 sb.append(ev.getXPrecision()).append(',');
2175 sb.append(ev.getYPrecision()).append(',');
2176 sb.append(ev.getDeviceId()).append(',');
2177 sb.append(ev.getEdgeFlags());
2178 Log.d(TAG, sb.toString());
2179 }
2180 /**
2181 * log motion events
2182 */
2183 private static void captureKeyLog(String subTag, KeyEvent ev) {
2184 //check dynamic switch
2185 if (ev == null ||
2186 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2187 return;
2188 }
2189 StringBuilder sb = new StringBuilder(subTag + ": ");
2190 sb.append(ev.getDownTime()).append(',');
2191 sb.append(ev.getEventTime()).append(',');
2192 sb.append(ev.getAction()).append(',');
2193 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 sb.append(ev.getRepeatCount()).append(',');
2195 sb.append(ev.getMetaState()).append(',');
2196 sb.append(ev.getDeviceId()).append(',');
2197 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002198 Log.d(TAG, sb.toString());
2199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200
2201 int enqueuePendingEvent(Object event, boolean sendDone) {
2202 int seq = mPendingEventSeq+1;
2203 if (seq < 0) seq = 0;
2204 mPendingEventSeq = seq;
2205 mPendingEvents.put(seq, event);
2206 return sendDone ? seq : -seq;
2207 }
2208
2209 Object retrievePendingEvent(int seq) {
2210 if (seq < 0) seq = -seq;
2211 Object event = mPendingEvents.get(seq);
2212 if (event != null) {
2213 mPendingEvents.remove(seq);
2214 }
2215 return event;
2216 }
Romain Guy8506ab42009-06-11 17:35:47 -07002217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2219 // If mView is null, we just consume the key event because it doesn't
2220 // make sense to do anything else with it.
2221 boolean handled = mView != null
2222 ? mView.dispatchKeyEventPreIme(event) : true;
2223 if (handled) {
2224 if (sendDone) {
2225 if (LOCAL_LOGV) Log.v(
2226 "ViewRoot", "Telling window manager key is finished");
2227 try {
2228 sWindowSession.finishKey(mWindow);
2229 } catch (RemoteException e) {
2230 }
2231 }
2232 return;
2233 }
2234 // If it is possible for this window to interact with the input
2235 // method window, then we want to first dispatch our key events
2236 // to the input method.
2237 if (mLastWasImTarget) {
2238 InputMethodManager imm = InputMethodManager.peekInstance();
2239 if (imm != null && mView != null) {
2240 int seq = enqueuePendingEvent(event, sendDone);
2241 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2242 + seq + " event=" + event);
2243 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2244 mInputMethodCallback);
2245 return;
2246 }
2247 }
2248 deliverKeyEventToViewHierarchy(event, sendDone);
2249 }
2250
2251 void handleFinishedEvent(int seq, boolean handled) {
2252 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2253 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2254 + " handled=" + handled + " event=" + event);
2255 if (event != null) {
2256 final boolean sendDone = seq >= 0;
2257 if (!handled) {
2258 deliverKeyEventToViewHierarchy(event, sendDone);
2259 return;
2260 } else if (sendDone) {
2261 if (LOCAL_LOGV) Log.v(
2262 "ViewRoot", "Telling window manager key is finished");
2263 try {
2264 sWindowSession.finishKey(mWindow);
2265 } catch (RemoteException e) {
2266 }
2267 } else {
2268 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2269 + " handled=" + handled + " ev=" + event
2270 + ") neither delivering nor finishing key");
2271 }
2272 }
2273 }
Romain Guy8506ab42009-06-11 17:35:47 -07002274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2276 try {
2277 if (mView != null && mAdded) {
2278 final int action = event.getAction();
2279 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2280
2281 if (checkForLeavingTouchModeAndConsume(event)) {
2282 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002283 }
2284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 if (Config.LOGV) {
2286 captureKeyLog("captureDispatchKeyEvent", event);
2287 }
2288 boolean keyHandled = mView.dispatchKeyEvent(event);
2289
2290 if (!keyHandled && isDown) {
2291 int direction = 0;
2292 switch (event.getKeyCode()) {
2293 case KeyEvent.KEYCODE_DPAD_LEFT:
2294 direction = View.FOCUS_LEFT;
2295 break;
2296 case KeyEvent.KEYCODE_DPAD_RIGHT:
2297 direction = View.FOCUS_RIGHT;
2298 break;
2299 case KeyEvent.KEYCODE_DPAD_UP:
2300 direction = View.FOCUS_UP;
2301 break;
2302 case KeyEvent.KEYCODE_DPAD_DOWN:
2303 direction = View.FOCUS_DOWN;
2304 break;
2305 }
2306
2307 if (direction != 0) {
2308
2309 View focused = mView != null ? mView.findFocus() : null;
2310 if (focused != null) {
2311 View v = focused.focusSearch(direction);
2312 boolean focusPassed = false;
2313 if (v != null && v != focused) {
2314 // do the math the get the interesting rect
2315 // of previous focused into the coord system of
2316 // newly focused view
2317 focused.getFocusedRect(mTempRect);
2318 ((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);
2319 ((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);
2320 focusPassed = v.requestFocus(direction, mTempRect);
2321 }
2322
2323 if (!focusPassed) {
2324 mView.dispatchUnhandledMove(focused, direction);
2325 } else {
2326 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2327 }
2328 }
2329 }
2330 }
2331 }
2332
2333 } finally {
2334 if (sendDone) {
2335 if (LOCAL_LOGV) Log.v(
2336 "ViewRoot", "Telling window manager key is finished");
2337 try {
2338 sWindowSession.finishKey(mWindow);
2339 } catch (RemoteException e) {
2340 }
2341 }
2342 // Let the exception fall through -- the looper will catch
2343 // it and take care of the bad app for us.
2344 }
2345 }
2346
2347 private AudioManager getAudioManager() {
2348 if (mView == null) {
2349 throw new IllegalStateException("getAudioManager called when there is no mView");
2350 }
2351 if (mAudioManager == null) {
2352 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2353 }
2354 return mAudioManager;
2355 }
2356
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002357 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2358 boolean insetsPending) throws RemoteException {
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002359 boolean restore = false;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002360 float appScale = mCompatibilityInfo.mApplicationScale;
2361 boolean scalingRequired = mCompatibilityInfo.mScalingRequired;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002362 if (params != null && !mCompatibilityInfo.mExpandable) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002363 restore = true;
2364 params.backup();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002365 adjustWindowAttributesForCompatibleMode(params);
2366 }
2367 if (params != null && scalingRequired) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002368 if (!restore) params.backup();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002369 restore = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002370 params.scale(appScale);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002371 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002372 int relayoutResult = sWindowSession.relayout(
2373 mWindow, params,
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002374 (int) (mView.mMeasuredWidth * appScale),
2375 (int) (mView.mMeasuredHeight * appScale),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002376 viewVisibility, insetsPending, mWinFrame,
2377 mPendingContentInsets, mPendingVisibleInsets, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002378 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002379 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002380 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002381 if (scalingRequired) {
2382 float invertedScale = mCompatibilityInfo.mApplicationInvertedScale;
2383 mPendingContentInsets.scale(invertedScale);
2384 mPendingVisibleInsets.scale(invertedScale);
2385 mWinFrame.scale(invertedScale);
2386 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002387 return relayoutResult;
2388 }
Romain Guy8506ab42009-06-11 17:35:47 -07002389
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002390 /**
2391 * Adjust the window's layout parameter for compatibility mode. It replaces FILL_PARENT
2392 * with the default window size, and centers if the window wanted to fill
2393 * horizontally.
Romain Guy8506ab42009-06-11 17:35:47 -07002394 *
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002395 * @param attrs the window's layout params to adjust
2396 */
2397 private void adjustWindowAttributesForCompatibleMode(WindowManager.LayoutParams attrs) {
2398 // fix app windows only
2399 if (attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
2400 DisplayMetrics metrics = mView.getContext().getResources().getDisplayMetrics();
2401 // TODO: improve gravity logic
2402 if (attrs.width == ViewGroup.LayoutParams.FILL_PARENT) {
2403 attrs.width = metrics.widthPixels;
2404 attrs.gravity |= Gravity.CENTER_HORIZONTAL;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002405 mWindowAttributesChanged = attrs == mWindowAttributes;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002406 }
2407 if (attrs.height == ViewGroup.LayoutParams.FILL_PARENT) {
2408 attrs.height = metrics.heightPixels;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002409 attrs.gravity |= Gravity.TOP;
2410 mWindowAttributesChanged = attrs == mWindowAttributes;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002411 }
2412 if (DEBUG_LAYOUT) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002413 Log.d(TAG, "Adjusted Attributes for compatibility : " + attrs);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002414 }
2415 }
2416 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 /**
2419 * {@inheritDoc}
2420 */
2421 public void playSoundEffect(int effectId) {
2422 checkThread();
2423
2424 final AudioManager audioManager = getAudioManager();
2425
2426 switch (effectId) {
2427 case SoundEffectConstants.CLICK:
2428 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2429 return;
2430 case SoundEffectConstants.NAVIGATION_DOWN:
2431 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2432 return;
2433 case SoundEffectConstants.NAVIGATION_LEFT:
2434 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2435 return;
2436 case SoundEffectConstants.NAVIGATION_RIGHT:
2437 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2438 return;
2439 case SoundEffectConstants.NAVIGATION_UP:
2440 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2441 return;
2442 default:
2443 throw new IllegalArgumentException("unknown effect id " + effectId +
2444 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2445 }
2446 }
2447
2448 /**
2449 * {@inheritDoc}
2450 */
2451 public boolean performHapticFeedback(int effectId, boolean always) {
2452 try {
2453 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2454 } catch (RemoteException e) {
2455 return false;
2456 }
2457 }
2458
2459 /**
2460 * {@inheritDoc}
2461 */
2462 public View focusSearch(View focused, int direction) {
2463 checkThread();
2464 if (!(mView instanceof ViewGroup)) {
2465 return null;
2466 }
2467 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2468 }
2469
2470 public void debug() {
2471 mView.debug();
2472 }
2473
2474 public void die(boolean immediate) {
2475 checkThread();
2476 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2477 synchronized (this) {
2478 if (mAdded && !mFirst) {
2479 int viewVisibility = mView.getVisibility();
2480 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2481 if (mWindowAttributesChanged || viewVisibilityChanged) {
2482 // If layout params have been changed, first give them
2483 // to the window manager to make sure it has the correct
2484 // animation info.
2485 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002486 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2487 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 sWindowSession.finishDrawing(mWindow);
2489 }
2490 } catch (RemoteException e) {
2491 }
2492 }
2493
2494 mSurface = null;
2495 }
2496 if (mAdded) {
2497 mAdded = false;
2498 if (immediate) {
2499 dispatchDetachedFromWindow();
2500 } else if (mView != null) {
2501 sendEmptyMessage(DIE);
2502 }
2503 }
2504 }
2505 }
2506
2507 public void dispatchFinishedEvent(int seq, boolean handled) {
2508 Message msg = obtainMessage(FINISHED_EVENT);
2509 msg.arg1 = seq;
2510 msg.arg2 = handled ? 1 : 0;
2511 sendMessage(msg);
2512 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 public void dispatchResized(int w, int h, Rect coveredInsets,
2515 Rect visibleInsets, boolean reportDraw) {
2516 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2517 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2518 + " visibleInsets=" + visibleInsets.toShortString()
2519 + " reportDraw=" + reportDraw);
2520 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002521 if (mCompatibilityInfo.mScalingRequired) {
2522 float invertedScale = mCompatibilityInfo.mApplicationInvertedScale;
2523 coveredInsets.scale(invertedScale);
2524 visibleInsets.scale(invertedScale);
2525 msg.arg1 = (int) (w * invertedScale);
2526 msg.arg2 = (int) (h * invertedScale);
2527 } else {
2528 msg.arg1 = w;
2529 msg.arg2 = h;
2530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 msg.obj = new Rect[] { new Rect(coveredInsets), new Rect(visibleInsets) };
2532 sendMessage(msg);
2533 }
2534
2535 public void dispatchKey(KeyEvent event) {
2536 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2537 //noinspection ConstantConditions
2538 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2539 if (Config.LOGD) Log.d("keydisp",
2540 "===================================================");
2541 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2542 debug();
2543
2544 if (Config.LOGD) Log.d("keydisp",
2545 "===================================================");
2546 }
2547 }
2548
2549 Message msg = obtainMessage(DISPATCH_KEY);
2550 msg.obj = event;
2551
2552 if (LOCAL_LOGV) Log.v(
2553 "ViewRoot", "sending key " + event + " to " + mView);
2554
2555 sendMessageAtTime(msg, event.getEventTime());
2556 }
2557
2558 public void dispatchPointer(MotionEvent event, long eventTime) {
2559 Message msg = obtainMessage(DISPATCH_POINTER);
2560 msg.obj = event;
2561 sendMessageAtTime(msg, eventTime);
2562 }
2563
2564 public void dispatchTrackball(MotionEvent event, long eventTime) {
2565 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2566 msg.obj = event;
2567 sendMessageAtTime(msg, eventTime);
2568 }
2569
2570 public void dispatchAppVisibility(boolean visible) {
2571 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2572 msg.arg1 = visible ? 1 : 0;
2573 sendMessage(msg);
2574 }
2575
2576 public void dispatchGetNewSurface() {
2577 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2578 sendMessage(msg);
2579 }
2580
2581 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2582 Message msg = Message.obtain();
2583 msg.what = WINDOW_FOCUS_CHANGED;
2584 msg.arg1 = hasFocus ? 1 : 0;
2585 msg.arg2 = inTouchMode ? 1 : 0;
2586 sendMessage(msg);
2587 }
2588
svetoslavganov75986cf2009-05-14 22:28:01 -07002589 /**
2590 * The window is getting focus so if there is anything focused/selected
2591 * send an {@link AccessibilityEvent} to announce that.
2592 */
2593 private void sendAccessibilityEvents() {
2594 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2595 return;
2596 }
2597 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2598 View focusedView = mView.findFocus();
2599 if (focusedView != null && focusedView != mView) {
2600 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2601 }
2602 }
2603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 public boolean showContextMenuForChild(View originalView) {
2605 return false;
2606 }
2607
2608 public void createContextMenu(ContextMenu menu) {
2609 }
2610
2611 public void childDrawableStateChanged(View child) {
2612 }
2613
2614 protected Rect getWindowFrame() {
2615 return mWinFrame;
2616 }
2617
2618 void checkThread() {
2619 if (mThread != Thread.currentThread()) {
2620 throw new CalledFromWrongThreadException(
2621 "Only the original thread that created a view hierarchy can touch its views.");
2622 }
2623 }
2624
2625 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2626 // ViewRoot never intercepts touch event, so this can be a no-op
2627 }
2628
2629 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2630 boolean immediate) {
2631 return scrollToRectOrFocus(rectangle, immediate);
2632 }
Romain Guy8506ab42009-06-11 17:35:47 -07002633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 static class InputMethodCallback extends IInputMethodCallback.Stub {
2635 private WeakReference<ViewRoot> mViewRoot;
2636
2637 public InputMethodCallback(ViewRoot viewRoot) {
2638 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2639 }
Romain Guy8506ab42009-06-11 17:35:47 -07002640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 public void finishedEvent(int seq, boolean handled) {
2642 final ViewRoot viewRoot = mViewRoot.get();
2643 if (viewRoot != null) {
2644 viewRoot.dispatchFinishedEvent(seq, handled);
2645 }
2646 }
2647
2648 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2649 // Stub -- not for use in the client.
2650 }
2651 }
Romain Guy8506ab42009-06-11 17:35:47 -07002652
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002653 static class EventCompletion extends Handler {
2654 final IWindow mWindow;
2655 final KeyEvent mKeyEvent;
2656 final boolean mIsPointer;
2657 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002658
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002659 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2660 boolean isPointer, MotionEvent motion) {
2661 super(looper);
2662 mWindow = window;
2663 mKeyEvent = key;
2664 mIsPointer = isPointer;
2665 mMotionEvent = motion;
2666 sendEmptyMessage(0);
2667 }
Romain Guy8506ab42009-06-11 17:35:47 -07002668
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002669 @Override
2670 public void handleMessage(Message msg) {
2671 if (mKeyEvent != null) {
2672 try {
2673 sWindowSession.finishKey(mWindow);
2674 } catch (RemoteException e) {
2675 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002676 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002677 boolean didFinish;
2678 MotionEvent event = mMotionEvent;
2679 if (event == null) {
2680 try {
2681 event = sWindowSession.getPendingPointerMove(mWindow);
2682 } catch (RemoteException e) {
2683 }
2684 didFinish = true;
2685 } else {
2686 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2687 }
2688 if (!didFinish) {
2689 try {
2690 sWindowSession.finishKey(mWindow);
2691 } catch (RemoteException e) {
2692 }
2693 }
2694 } else {
2695 MotionEvent event = mMotionEvent;
2696 if (event == null) {
2697 try {
2698 event = sWindowSession.getPendingTrackballMove(mWindow);
2699 } catch (RemoteException e) {
2700 }
2701 } else {
2702 try {
2703 sWindowSession.finishKey(mWindow);
2704 } catch (RemoteException e) {
2705 }
2706 }
2707 }
2708 }
2709 }
Romain Guy8506ab42009-06-11 17:35:47 -07002710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002712 private final WeakReference<ViewRoot> mViewRoot;
2713 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002715 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002717 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 }
2719
2720 public void resized(int w, int h, Rect coveredInsets,
2721 Rect visibleInsets, boolean reportDraw) {
2722 final ViewRoot viewRoot = mViewRoot.get();
2723 if (viewRoot != null) {
2724 viewRoot.dispatchResized(w, h, coveredInsets,
2725 visibleInsets, reportDraw);
2726 }
2727 }
2728
2729 public void dispatchKey(KeyEvent event) {
2730 final ViewRoot viewRoot = mViewRoot.get();
2731 if (viewRoot != null) {
2732 viewRoot.dispatchKey(event);
2733 } else {
2734 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002735 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 }
2737 }
2738
2739 public void dispatchPointer(MotionEvent event, long eventTime) {
2740 final ViewRoot viewRoot = mViewRoot.get();
2741 if (viewRoot != null) {
2742 viewRoot.dispatchPointer(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002743 } else {
2744 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 }
2746 }
2747
2748 public void dispatchTrackball(MotionEvent event, long eventTime) {
2749 final ViewRoot viewRoot = mViewRoot.get();
2750 if (viewRoot != null) {
2751 viewRoot.dispatchTrackball(event, eventTime);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002752 } else {
2753 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 }
2755 }
2756
2757 public void dispatchAppVisibility(boolean visible) {
2758 final ViewRoot viewRoot = mViewRoot.get();
2759 if (viewRoot != null) {
2760 viewRoot.dispatchAppVisibility(visible);
2761 }
2762 }
2763
2764 public void dispatchGetNewSurface() {
2765 final ViewRoot viewRoot = mViewRoot.get();
2766 if (viewRoot != null) {
2767 viewRoot.dispatchGetNewSurface();
2768 }
2769 }
2770
2771 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2772 final ViewRoot viewRoot = mViewRoot.get();
2773 if (viewRoot != null) {
2774 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2775 }
2776 }
2777
2778 private static int checkCallingPermission(String permission) {
2779 if (!Process.supportsProcesses()) {
2780 return PackageManager.PERMISSION_GRANTED;
2781 }
2782
2783 try {
2784 return ActivityManagerNative.getDefault().checkPermission(
2785 permission, Binder.getCallingPid(), Binder.getCallingUid());
2786 } catch (RemoteException e) {
2787 return PackageManager.PERMISSION_DENIED;
2788 }
2789 }
2790
2791 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2792 final ViewRoot viewRoot = mViewRoot.get();
2793 if (viewRoot != null) {
2794 final View view = viewRoot.mView;
2795 if (view != null) {
2796 if (checkCallingPermission(Manifest.permission.DUMP) !=
2797 PackageManager.PERMISSION_GRANTED) {
2798 throw new SecurityException("Insufficient permissions to invoke"
2799 + " executeCommand() from pid=" + Binder.getCallingPid()
2800 + ", uid=" + Binder.getCallingUid());
2801 }
2802
2803 OutputStream clientStream = null;
2804 try {
2805 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2806 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2807 } catch (IOException e) {
2808 e.printStackTrace();
2809 } finally {
2810 if (clientStream != null) {
2811 try {
2812 clientStream.close();
2813 } catch (IOException e) {
2814 e.printStackTrace();
2815 }
2816 }
2817 }
2818 }
2819 }
2820 }
2821 }
2822
2823 /**
2824 * Maintains state information for a single trackball axis, generating
2825 * discrete (DPAD) movements based on raw trackball motion.
2826 */
2827 static final class TrackballAxis {
2828 /**
2829 * The maximum amount of acceleration we will apply.
2830 */
2831 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 /**
2834 * The maximum amount of time (in milliseconds) between events in order
2835 * for us to consider the user to be doing fast trackball movements,
2836 * and thus apply an acceleration.
2837 */
2838 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 /**
2841 * Scaling factor to the time (in milliseconds) between events to how
2842 * much to multiple/divide the current acceleration. When movement
2843 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2844 * FAST_MOVE_TIME it divides it.
2845 */
2846 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 float position;
2849 float absPosition;
2850 float acceleration = 1;
2851 long lastMoveTime = 0;
2852 int step;
2853 int dir;
2854 int nonAccelMovement;
2855
2856 void reset(int _step) {
2857 position = 0;
2858 acceleration = 1;
2859 lastMoveTime = 0;
2860 step = _step;
2861 dir = 0;
2862 }
2863
2864 /**
2865 * Add trackball movement into the state. If the direction of movement
2866 * has been reversed, the state is reset before adding the
2867 * movement (so that you don't have to compensate for any previously
2868 * collected movement before see the result of the movement in the
2869 * new direction).
2870 *
2871 * @return Returns the absolute value of the amount of movement
2872 * collected so far.
2873 */
2874 float collect(float off, long time, String axis) {
2875 long normTime;
2876 if (off > 0) {
2877 normTime = (long)(off * FAST_MOVE_TIME);
2878 if (dir < 0) {
2879 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2880 position = 0;
2881 step = 0;
2882 acceleration = 1;
2883 lastMoveTime = 0;
2884 }
2885 dir = 1;
2886 } else if (off < 0) {
2887 normTime = (long)((-off) * FAST_MOVE_TIME);
2888 if (dir > 0) {
2889 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2890 position = 0;
2891 step = 0;
2892 acceleration = 1;
2893 lastMoveTime = 0;
2894 }
2895 dir = -1;
2896 } else {
2897 normTime = 0;
2898 }
Romain Guy8506ab42009-06-11 17:35:47 -07002899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 // The number of milliseconds between each movement that is
2901 // considered "normal" and will not result in any acceleration
2902 // or deceleration, scaled by the offset we have here.
2903 if (normTime > 0) {
2904 long delta = time - lastMoveTime;
2905 lastMoveTime = time;
2906 float acc = acceleration;
2907 if (delta < normTime) {
2908 // The user is scrolling rapidly, so increase acceleration.
2909 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2910 if (scale > 1) acc *= scale;
2911 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2912 + off + " normTime=" + normTime + " delta=" + delta
2913 + " scale=" + scale + " acc=" + acc);
2914 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2915 } else {
2916 // The user is scrolling slowly, so decrease acceleration.
2917 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
2918 if (scale > 1) acc /= scale;
2919 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
2920 + off + " normTime=" + normTime + " delta=" + delta
2921 + " scale=" + scale + " acc=" + acc);
2922 acceleration = acc > 1 ? acc : 1;
2923 }
2924 }
2925 position += off;
2926 return (absPosition = Math.abs(position));
2927 }
2928
2929 /**
2930 * Generate the number of discrete movement events appropriate for
2931 * the currently collected trackball movement.
2932 *
2933 * @param precision The minimum movement required to generate the
2934 * first discrete movement.
2935 *
2936 * @return Returns the number of discrete movements, either positive
2937 * or negative, or 0 if there is not enough trackball movement yet
2938 * for a discrete movement.
2939 */
2940 int generate(float precision) {
2941 int movement = 0;
2942 nonAccelMovement = 0;
2943 do {
2944 final int dir = position >= 0 ? 1 : -1;
2945 switch (step) {
2946 // If we are going to execute the first step, then we want
2947 // to do this as soon as possible instead of waiting for
2948 // a full movement, in order to make things look responsive.
2949 case 0:
2950 if (absPosition < precision) {
2951 return movement;
2952 }
2953 movement += dir;
2954 nonAccelMovement += dir;
2955 step = 1;
2956 break;
2957 // If we have generated the first movement, then we need
2958 // to wait for the second complete trackball motion before
2959 // generating the second discrete movement.
2960 case 1:
2961 if (absPosition < 2) {
2962 return movement;
2963 }
2964 movement += dir;
2965 nonAccelMovement += dir;
2966 position += dir > 0 ? -2 : 2;
2967 absPosition = Math.abs(position);
2968 step = 2;
2969 break;
2970 // After the first two, we generate discrete movements
2971 // consistently with the trackball, applying an acceleration
2972 // if the trackball is moving quickly. This is a simple
2973 // acceleration on top of what we already compute based
2974 // on how quickly the wheel is being turned, to apply
2975 // a longer increasing acceleration to continuous movement
2976 // in one direction.
2977 default:
2978 if (absPosition < 1) {
2979 return movement;
2980 }
2981 movement += dir;
2982 position += dir >= 0 ? -1 : 1;
2983 absPosition = Math.abs(position);
2984 float acc = acceleration;
2985 acc *= 1.1f;
2986 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
2987 break;
2988 }
2989 } while (true);
2990 }
2991 }
2992
2993 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
2994 public CalledFromWrongThreadException(String msg) {
2995 super(msg);
2996 }
2997 }
2998
2999 private SurfaceHolder mHolder = new SurfaceHolder() {
3000 // we only need a SurfaceHolder for opengl. it would be nice
3001 // to implement everything else though, especially the callback
3002 // support (opengl doesn't make use of it right now, but eventually
3003 // will).
3004 public Surface getSurface() {
3005 return mSurface;
3006 }
3007
3008 public boolean isCreating() {
3009 return false;
3010 }
3011
3012 public void addCallback(Callback callback) {
3013 }
3014
3015 public void removeCallback(Callback callback) {
3016 }
3017
3018 public void setFixedSize(int width, int height) {
3019 }
3020
3021 public void setSizeFromLayout() {
3022 }
3023
3024 public void setFormat(int format) {
3025 }
3026
3027 public void setType(int type) {
3028 }
3029
3030 public void setKeepScreenOn(boolean screenOn) {
3031 }
3032
3033 public Canvas lockCanvas() {
3034 return null;
3035 }
3036
3037 public Canvas lockCanvas(Rect dirty) {
3038 return null;
3039 }
3040
3041 public void unlockCanvasAndPost(Canvas canvas) {
3042 }
3043 public Rect getSurfaceFrame() {
3044 return null;
3045 }
3046 };
3047
3048 static RunQueue getRunQueue() {
3049 RunQueue rq = sRunQueues.get();
3050 if (rq != null) {
3051 return rq;
3052 }
3053 rq = new RunQueue();
3054 sRunQueues.set(rq);
3055 return rq;
3056 }
Romain Guy8506ab42009-06-11 17:35:47 -07003057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 /**
3059 * @hide
3060 */
3061 static final class RunQueue {
3062 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3063
3064 void post(Runnable action) {
3065 postDelayed(action, 0);
3066 }
3067
3068 void postDelayed(Runnable action, long delayMillis) {
3069 HandlerAction handlerAction = new HandlerAction();
3070 handlerAction.action = action;
3071 handlerAction.delay = delayMillis;
3072
3073 synchronized (mActions) {
3074 mActions.add(handlerAction);
3075 }
3076 }
3077
3078 void removeCallbacks(Runnable action) {
3079 final HandlerAction handlerAction = new HandlerAction();
3080 handlerAction.action = action;
3081
3082 synchronized (mActions) {
3083 final ArrayList<HandlerAction> actions = mActions;
3084
3085 while (actions.remove(handlerAction)) {
3086 // Keep going
3087 }
3088 }
3089 }
3090
3091 void executeActions(Handler handler) {
3092 synchronized (mActions) {
3093 final ArrayList<HandlerAction> actions = mActions;
3094 final int count = actions.size();
3095
3096 for (int i = 0; i < count; i++) {
3097 final HandlerAction handlerAction = actions.get(i);
3098 handler.postDelayed(handlerAction.action, handlerAction.delay);
3099 }
3100
3101 mActions.clear();
3102 }
3103 }
3104
3105 private static class HandlerAction {
3106 Runnable action;
3107 long delay;
3108
3109 @Override
3110 public boolean equals(Object o) {
3111 if (this == o) return true;
3112 if (o == null || getClass() != o.getClass()) return false;
3113
3114 HandlerAction that = (HandlerAction) o;
3115
3116 return !(action != null ? !action.equals(that.action) : that.action != null);
3117
3118 }
3119
3120 @Override
3121 public int hashCode() {
3122 int result = action != null ? action.hashCode() : 0;
3123 result = 31 * result + (int) (delay ^ (delay >>> 32));
3124 return result;
3125 }
3126 }
3127 }
3128
3129 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3130
3131 // inform skia to just abandon its texture cache IDs
3132 // doesn't call glDeleteTextures
3133 private static native void nativeAbandonGlCaches();
3134}