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