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