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