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