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