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