blob: 8984b746c9ff040f59749f8c8ce16989cfc7b8b8 [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
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070019import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.view.IInputMethodCallback;
21import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070022import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import android.graphics.Canvas;
25import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.PorterDuff;
27import android.graphics.Rect;
28import android.graphics.Region;
29import android.os.*;
30import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.util.AndroidRuntimeException;
32import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070033import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.Log;
35import android.util.EventLog;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070036import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070039import android.view.accessibility.AccessibilityEvent;
40import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.view.inputmethod.InputConnection;
42import android.view.inputmethod.InputMethodManager;
43import android.widget.Scroller;
44import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070045import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080046import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070047import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080048import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.Context;
50import android.app.ActivityManagerNative;
51import android.Manifest;
52import android.media.AudioManager;
53
54import java.lang.ref.WeakReference;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070055import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.io.IOException;
57import java.io.OutputStream;
58import java.util.ArrayList;
59
60import javax.microedition.khronos.egl.*;
61import javax.microedition.khronos.opengles.*;
62import static javax.microedition.khronos.opengles.GL10.*;
63
64/**
65 * The top of a view hierarchy, implementing the needed protocol between View
66 * and the WindowManager. This is for the most part an internal implementation
67 * detail of {@link WindowManagerImpl}.
68 *
69 * {@hide}
70 */
71@SuppressWarnings({"EmptyCatchBlock"})
72public final class ViewRoot extends Handler implements ViewParent,
73 View.AttachInfo.Callbacks {
74 private static final String TAG = "ViewRoot";
75 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040076 private static final boolean SHOW_FPS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 @SuppressWarnings({"ConstantConditionalExpression"})
78 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
79 /** @noinspection PointlessBooleanExpression*/
80 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
81 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070082 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
84 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
85 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
86 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070087 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final boolean WATCH_POINTER = false;
89
Michael Chan53071d62009-05-13 17:29:48 -070090 private static final boolean MEASURE_LATENCY = false;
91 private static LatencyTimer lt;
92
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 /**
94 * Maximum time we allow the user to roll the trackball enough to generate
95 * a key event, before resetting the counters.
96 */
97 static final int MAX_TRACKBALL_DELAY = 250;
98
99 static long sInstanceCount = 0;
100
101 static IWindowSession sWindowSession;
102
103 static final Object mStaticInit = new Object();
104 static boolean mInitialized = false;
105
106 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
107
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800108 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
109 static boolean sFirstDrawComplete = false;
110
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800111 static final ArrayList<ComponentCallbacks> sConfigCallbacks
112 = new ArrayList<ComponentCallbacks>();
113
Romain Guy8506ab42009-06-11 17:35:47 -0700114 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 long mLastTrackballTime = 0;
117 final TrackballAxis mTrackballAxisX = new TrackballAxis();
118 final TrackballAxis mTrackballAxisY = new TrackballAxis();
119
120 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 final InputMethodCallback mInputMethodCallback;
123 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
124 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 final Thread mThread;
127
128 final WindowLeaked mLocation;
129
130 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
131
132 final W mWindow;
133
134 View mView;
135 View mFocusedView;
136 View mRealFocusedView; // this is not set to null in touch mode
137 int mViewVisibility;
138 boolean mAppVisible = true;
139
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700140 SurfaceHolder.Callback mSurfaceHolderCallback;
141 BaseSurfaceHolder mSurfaceHolder;
142 boolean mIsCreating;
143 boolean mDrawingAllowed;
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 final Region mTransparentRegion;
146 final Region mPreviousTransparentRegion;
147
148 int mWidth;
149 int mHeight;
150 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700151 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700152
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700153 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
155 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700156 InputChannel mInputChannel;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700157 InputConsumer.Callback mInputConsumerCallback;
158 InputConsumer mInputConsumer;
159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 final Rect mTempRect; // used in the transaction to not thrash the heap.
161 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163 boolean mTraversalScheduled;
164 boolean mWillDrawSoon;
165 boolean mLayoutRequested;
166 boolean mFirst;
167 boolean mReportNextDraw;
168 boolean mFullRedrawNeeded;
169 boolean mNewSurfaceNeeded;
170 boolean mHasHadWindowFocus;
171 boolean mLastWasImTarget;
172
173 boolean mWindowAttributesChanged = false;
174
175 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700176 // Surface can never be reassigned or cleared (use Surface.clear()).
177 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
179 boolean mAdded;
180 boolean mAddedTouchMode;
181
182 /*package*/ int mAddNesting;
183
184 // These are accessed by multiple threads.
185 final Rect mWinFrame; // frame given by window manager.
186
187 final Rect mPendingVisibleInsets = new Rect();
188 final Rect mPendingContentInsets = new Rect();
189 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
190 = new ViewTreeObserver.InternalInsetsInfo();
191
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700192 final Configuration mLastConfiguration = new Configuration();
193 final Configuration mPendingConfiguration = new Configuration();
194
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800195 class ResizedInfo {
196 Rect coveredInsets;
197 Rect visibleInsets;
198 Configuration newConfig;
199 }
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 boolean mScrollMayChange;
202 int mSoftInputMode;
203 View mLastScrolledFocus;
204 int mScrollY;
205 int mCurScrollY;
206 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 EGL10 mEgl;
209 EGLDisplay mEglDisplay;
210 EGLContext mEglContext;
211 EGLSurface mEglSurface;
212 GL11 mGL;
213 Canvas mGlCanvas;
214 boolean mUseGL;
215 boolean mGlWanted;
216
Romain Guy8506ab42009-06-11 17:35:47 -0700217 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
219 /**
220 * see {@link #playSoundEffect(int)}
221 */
222 AudioManager mAudioManager;
223
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700224 private final int mDensity;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700225
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700226 public static IWindowSession getWindowSession(Looper mainLooper) {
227 synchronized (mStaticInit) {
228 if (!mInitialized) {
229 try {
230 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
231 sWindowSession = IWindowManager.Stub.asInterface(
232 ServiceManager.getService("window"))
233 .openSession(imm.getClient(), imm.getInputContext());
234 mInitialized = true;
235 } catch (RemoteException e) {
236 }
237 }
238 return sWindowSession;
239 }
240 }
241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 public ViewRoot(Context context) {
243 super();
244
Michael Chan53071d62009-05-13 17:29:48 -0700245 if (MEASURE_LATENCY && lt == null) {
246 lt = new LatencyTimer(100, 1000);
247 }
248
Carl Shapiro82fe5642010-02-24 00:14:23 -0800249 // For debug only
250 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 // Initialize the statics when this class is first instantiated. This is
253 // done here instead of in the static block because Zygote does not
254 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700255 getWindowSession(context.getMainLooper());
256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 mThread = Thread.currentThread();
258 mLocation = new WindowLeaked(null);
259 mLocation.fillInStackTrace();
260 mWidth = -1;
261 mHeight = -1;
262 mDirty = new Rect();
263 mTempRect = new Rect();
264 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700266 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 mInputMethodCallback = new InputMethodCallback(this);
268 mViewVisibility = View.GONE;
269 mTransparentRegion = new Region();
270 mPreviousTransparentRegion = new Region();
271 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 mAdded = false;
273 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
274 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700275 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 }
277
Carl Shapiro82fe5642010-02-24 00:14:23 -0800278 // For debug only
279 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 @Override
281 protected void finalize() throws Throwable {
282 super.finalize();
283 --sInstanceCount;
284 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800285 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286
287 public static long getInstanceCount() {
288 return sInstanceCount;
289 }
290
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800291 public static void addFirstDrawHandler(Runnable callback) {
292 synchronized (sFirstDrawHandlers) {
293 if (!sFirstDrawComplete) {
294 sFirstDrawHandlers.add(callback);
295 }
296 }
297 }
298
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800299 public static void addConfigCallback(ComponentCallbacks callback) {
300 synchronized (sConfigCallbacks) {
301 sConfigCallbacks.add(callback);
302 }
303 }
304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 // FIXME for perf testing only
306 private boolean mProfile = false;
307
308 /**
309 * Call this to profile the next traversal call.
310 * FIXME for perf testing only. Remove eventually
311 */
312 public void profile() {
313 mProfile = true;
314 }
315
316 /**
317 * Indicates whether we are in touch mode. Calling this method triggers an IPC
318 * call and should be avoided whenever possible.
319 *
320 * @return True, if the device is in touch mode, false otherwise.
321 *
322 * @hide
323 */
324 static boolean isInTouchMode() {
325 if (mInitialized) {
326 try {
327 return sWindowSession.getInTouchMode();
328 } catch (RemoteException e) {
329 }
330 }
331 return false;
332 }
333
334 private void initializeGL() {
335 initializeGLInner();
336 int err = mEgl.eglGetError();
337 if (err != EGL10.EGL_SUCCESS) {
338 // give-up on using GL
339 destroyGL();
340 mGlWanted = false;
341 }
342 }
343
344 private void initializeGLInner() {
345 final EGL10 egl = (EGL10) EGLContext.getEGL();
346 mEgl = egl;
347
348 /*
349 * Get to the default display.
350 */
351 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
352 mEglDisplay = eglDisplay;
353
354 /*
355 * We can now initialize EGL for that display
356 */
357 int[] version = new int[2];
358 egl.eglInitialize(eglDisplay, version);
359
360 /*
361 * Specify a configuration for our opengl session
362 * and grab the first configuration that matches is
363 */
364 final int[] configSpec = {
365 EGL10.EGL_RED_SIZE, 5,
366 EGL10.EGL_GREEN_SIZE, 6,
367 EGL10.EGL_BLUE_SIZE, 5,
368 EGL10.EGL_DEPTH_SIZE, 0,
369 EGL10.EGL_NONE
370 };
371 final EGLConfig[] configs = new EGLConfig[1];
372 final int[] num_config = new int[1];
373 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
374 final EGLConfig config = configs[0];
375
376 /*
377 * Create an OpenGL ES context. This must be done only once, an
378 * OpenGL context is a somewhat heavy object.
379 */
380 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
381 EGL10.EGL_NO_CONTEXT, null);
382 mEglContext = context;
383
384 /*
385 * Create an EGL surface we can render into.
386 */
387 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
388 mEglSurface = surface;
389
390 /*
391 * Before we can issue GL commands, we need to make sure
392 * the context is current and bound to a surface.
393 */
394 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
395
396 /*
397 * Get to the appropriate GL interface.
398 * This is simply done by casting the GL context to either
399 * GL10 or GL11.
400 */
401 final GL11 gl = (GL11) context.getGL();
402 mGL = gl;
403 mGlCanvas = new Canvas(gl);
404 mUseGL = true;
405 }
406
407 private void destroyGL() {
408 // inform skia that the context is gone
409 nativeAbandonGlCaches();
410
411 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
412 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
413 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
414 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
415 mEgl.eglTerminate(mEglDisplay);
416 mEglContext = null;
417 mEglSurface = null;
418 mEglDisplay = null;
419 mEgl = null;
420 mGlCanvas = null;
421 mGL = null;
422 mUseGL = false;
423 }
424
425 private void checkEglErrors() {
426 if (mUseGL) {
427 int err = mEgl.eglGetError();
428 if (err != EGL10.EGL_SUCCESS) {
429 // something bad has happened revert to
430 // normal rendering.
431 destroyGL();
432 if (err != EGL11.EGL_CONTEXT_LOST) {
433 // we'll try again if it was context lost
434 mGlWanted = false;
435 }
436 }
437 }
438 }
439
440 /**
441 * We have one child
442 */
443 public void setView(View view, WindowManager.LayoutParams attrs,
444 View panelParentView) {
445 synchronized (this) {
446 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700447 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700448 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700449 attrs = mWindowAttributes;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700450 if (view instanceof RootViewSurfaceTaker) {
451 mSurfaceHolderCallback =
452 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
453 if (mSurfaceHolderCallback != null) {
454 mSurfaceHolder = new TakenSurfaceHolder();
455 }
456 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700457 Resources resources = mView.getContext().getResources();
458 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700459 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700460
461 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700462 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
463 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700464 }
465
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700466 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700467 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700468 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700469 attrs.backup();
470 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700471 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700472 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
473
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700474 if (!compatibilityInfo.supportsScreen()) {
475 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
476 }
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 mSoftInputMode = attrs.softInputMode;
479 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700481 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700482 mAttachInfo.mApplicationScale =
483 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 if (panelParentView != null) {
485 mAttachInfo.mPanelParentWindowToken
486 = panelParentView.getApplicationWindowToken();
487 }
488 mAdded = true;
489 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 // Schedule the first layout -before- adding to the window
492 // manager, to make sure we do the relayout before receiving
493 // any other events from the system.
494 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700495 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700497 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700498 getHostVisibility(), mAttachInfo.mContentInsets,
499 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 } catch (RemoteException e) {
501 mAdded = false;
502 mView = null;
503 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700504 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 unscheduleTraversals();
506 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700507 } finally {
508 if (restore) {
509 attrs.restore();
510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700512
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700513 if (mTranslator != null) {
514 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 mPendingContentInsets.set(mAttachInfo.mContentInsets);
517 mPendingVisibleInsets.set(0, 0, 0, 0);
518 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
519 if (res < WindowManagerImpl.ADD_OKAY) {
520 mView = null;
521 mAttachInfo.mRootView = null;
522 mAdded = false;
523 unscheduleTraversals();
524 switch (res) {
525 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
526 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
527 throw new WindowManagerImpl.BadTokenException(
528 "Unable to add window -- token " + attrs.token
529 + " is not valid; is your activity running?");
530 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
531 throw new WindowManagerImpl.BadTokenException(
532 "Unable to add window -- token " + attrs.token
533 + " is not for an application");
534 case WindowManagerImpl.ADD_APP_EXITING:
535 throw new WindowManagerImpl.BadTokenException(
536 "Unable to add window -- app for token " + attrs.token
537 + " is exiting");
538 case WindowManagerImpl.ADD_DUPLICATE_ADD:
539 throw new WindowManagerImpl.BadTokenException(
540 "Unable to add window -- window " + mWindow
541 + " has already been added");
542 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
543 // Silently ignore -- we would have just removed it
544 // right away, anyway.
545 return;
546 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
547 throw new WindowManagerImpl.BadTokenException(
548 "Unable to add window " + mWindow +
549 " -- another window of this type already exists");
550 case WindowManagerImpl.ADD_PERMISSION_DENIED:
551 throw new WindowManagerImpl.BadTokenException(
552 "Unable to add window " + mWindow +
553 " -- permission denied for this window type");
554 }
555 throw new RuntimeException(
556 "Unable to add window -- unknown error code " + res);
557 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700558
559 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700560 if (view instanceof RootViewSurfaceTaker) {
561 mInputConsumerCallback =
562 ((RootViewSurfaceTaker)view).willYouTakeTheInputConsumer();
563 }
564 if (mInputConsumerCallback != null) {
565 mInputConsumer = new InputConsumer(mInputChannel);
566 mInputConsumerCallback.onInputConsumerCreated(mInputConsumer);
567 } else {
568 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
569 Looper.myQueue());
570 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700571 }
572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 view.assignParent(this);
574 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
575 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
576 }
577 }
578 }
579
580 public View getView() {
581 return mView;
582 }
583
584 final WindowLeaked getLocation() {
585 return mLocation;
586 }
587
588 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
589 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700590 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700591 // preserve compatible window flag if exists.
592 int compatibleWindowFlag =
593 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700595 mWindowAttributes.flags |= compatibleWindowFlag;
596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 if (newView) {
598 mSoftInputMode = attrs.softInputMode;
599 requestLayout();
600 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700601 // Don't lose the mode we last auto-computed.
602 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
603 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
604 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
605 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
606 | (oldSoftInputMode
607 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 mWindowAttributesChanged = true;
610 scheduleTraversals();
611 }
612 }
613
614 void handleAppVisibility(boolean visible) {
615 if (mAppVisible != visible) {
616 mAppVisible = visible;
617 scheduleTraversals();
618 }
619 }
620
621 void handleGetNewSurface() {
622 mNewSurfaceNeeded = true;
623 mFullRedrawNeeded = true;
624 scheduleTraversals();
625 }
626
627 /**
628 * {@inheritDoc}
629 */
630 public void requestLayout() {
631 checkThread();
632 mLayoutRequested = true;
633 scheduleTraversals();
634 }
635
636 /**
637 * {@inheritDoc}
638 */
639 public boolean isLayoutRequested() {
640 return mLayoutRequested;
641 }
642
643 public void invalidateChild(View child, Rect dirty) {
644 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700645 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
646 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700648 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700649 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700650 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700651 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700652 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700653 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700654 }
Romain Guy1e095972009-07-07 11:22:45 -0700655 if (mAttachInfo.mScalingRequired) {
656 dirty.inset(-1, -1);
657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 }
659 mDirty.union(dirty);
660 if (!mWillDrawSoon) {
661 scheduleTraversals();
662 }
663 }
664
665 public ViewParent getParent() {
666 return null;
667 }
668
669 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
670 invalidateChild(null, dirty);
671 return null;
672 }
673
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700674 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 if (child != mView) {
676 throw new RuntimeException("child is not mine, honest!");
677 }
678 // Note: don't apply scroll offset, because we want to know its
679 // visibility in the virtual canvas being given to the view hierarchy.
680 return r.intersect(0, 0, mWidth, mHeight);
681 }
682
683 public void bringChildToFront(View child) {
684 }
685
686 public void scheduleTraversals() {
687 if (!mTraversalScheduled) {
688 mTraversalScheduled = true;
689 sendEmptyMessage(DO_TRAVERSAL);
690 }
691 }
692
693 public void unscheduleTraversals() {
694 if (mTraversalScheduled) {
695 mTraversalScheduled = false;
696 removeMessages(DO_TRAVERSAL);
697 }
698 }
699
700 int getHostVisibility() {
701 return mAppVisible ? mView.getVisibility() : View.GONE;
702 }
Romain Guy8506ab42009-06-11 17:35:47 -0700703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 private void performTraversals() {
705 // cache mView since it is used so much below...
706 final View host = mView;
707
708 if (DBG) {
709 System.out.println("======================================");
710 System.out.println("performTraversals");
711 host.debug();
712 }
713
714 if (host == null || !mAdded)
715 return;
716
717 mTraversalScheduled = false;
718 mWillDrawSoon = true;
719 boolean windowResizesToFitContent = false;
720 boolean fullRedrawNeeded = mFullRedrawNeeded;
721 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700722 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 WindowManager.LayoutParams lp = mWindowAttributes;
724
725 int desiredWindowWidth;
726 int desiredWindowHeight;
727 int childWidthMeasureSpec;
728 int childHeightMeasureSpec;
729
730 final View.AttachInfo attachInfo = mAttachInfo;
731
732 final int viewVisibility = getHostVisibility();
733 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
734 || mNewSurfaceNeeded;
735
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700736 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 WindowManager.LayoutParams params = null;
739 if (mWindowAttributesChanged) {
740 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700741 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 params = lp;
743 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700744 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 if (mFirst) {
746 fullRedrawNeeded = true;
747 mLayoutRequested = true;
748
Romain Guy8506ab42009-06-11 17:35:47 -0700749 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700750 mView.getContext().getResources().getDisplayMetrics();
751 desiredWindowWidth = packageMetrics.widthPixels;
752 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753
754 // For the very first time, tell the view hierarchy that it
755 // is attached to the window. Note that at this point the surface
756 // object is not initialized to its backing store, but soon it
757 // will be (assuming the window is visible).
758 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700759 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 attachInfo.mHasWindowFocus = false;
761 attachInfo.mWindowVisibility = viewVisibility;
762 attachInfo.mRecomputeGlobalAttributes = false;
763 attachInfo.mKeepScreenOn = false;
764 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700765 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700770 desiredWindowWidth = frame.width();
771 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
773 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700774 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 fullRedrawNeeded = true;
776 mLayoutRequested = true;
777 windowResizesToFitContent = true;
778 }
779 }
780
781 if (viewVisibilityChanged) {
782 attachInfo.mWindowVisibility = viewVisibility;
783 host.dispatchWindowVisibilityChanged(viewVisibility);
784 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
785 if (mUseGL) {
786 destroyGL();
787 }
788 }
789 if (viewVisibility == View.GONE) {
790 // After making a window gone, we will count it as being
791 // shown for the first time the next time it gets focus.
792 mHasHadWindowFocus = false;
793 }
794 }
795
796 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700799 // Execute enqueued actions on every layout in case a view that was detached
800 // enqueued an action after being detached
801 getRunQueue().executeActions(attachInfo.mHandler);
802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 if (mFirst) {
804 host.fitSystemWindows(mAttachInfo.mContentInsets);
805 // make sure touch mode code executes by setting cached value
806 // to opposite of the added touch mode.
807 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700808 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 } else {
810 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
811 mAttachInfo.mContentInsets.set(mPendingContentInsets);
812 host.fitSystemWindows(mAttachInfo.mContentInsets);
813 insetsChanged = true;
814 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
815 + mAttachInfo.mContentInsets);
816 }
817 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
818 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
819 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
820 + mAttachInfo.mVisibleInsets);
821 }
822 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
823 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
824 windowResizesToFitContent = true;
825
Romain Guy8506ab42009-06-11 17:35:47 -0700826 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700827 mView.getContext().getResources().getDisplayMetrics();
828 desiredWindowWidth = packageMetrics.widthPixels;
829 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831 }
832
833 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
834 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
835
836 // Ask host how big it wants to be
837 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
838 "Measuring " + host + " in display " + desiredWindowWidth
839 + "x" + desiredWindowHeight + "...");
840 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
841
842 if (DBG) {
843 System.out.println("======================================");
844 System.out.println("performTraversals -- after measure");
845 host.debug();
846 }
847 }
848
849 if (attachInfo.mRecomputeGlobalAttributes) {
850 //Log.i(TAG, "Computing screen on!");
851 attachInfo.mRecomputeGlobalAttributes = false;
852 boolean oldVal = attachInfo.mKeepScreenOn;
853 attachInfo.mKeepScreenOn = false;
854 host.dispatchCollectViewAttributes(0);
855 if (attachInfo.mKeepScreenOn != oldVal) {
856 params = lp;
857 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
858 }
859 }
860
861 if (mFirst || attachInfo.mViewVisibilityChanged) {
862 attachInfo.mViewVisibilityChanged = false;
863 int resizeMode = mSoftInputMode &
864 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
865 // If we are in auto resize mode, then we need to determine
866 // what mode to use now.
867 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
868 final int N = attachInfo.mScrollContainers.size();
869 for (int i=0; i<N; i++) {
870 if (attachInfo.mScrollContainers.get(i).isShown()) {
871 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
872 }
873 }
874 if (resizeMode == 0) {
875 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
876 }
877 if ((lp.softInputMode &
878 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
879 lp.softInputMode = (lp.softInputMode &
880 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
881 resizeMode;
882 params = lp;
883 }
884 }
885 }
Romain Guy8506ab42009-06-11 17:35:47 -0700886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
888 if (!PixelFormat.formatHasAlpha(params.format)) {
889 params.format = PixelFormat.TRANSLUCENT;
890 }
891 }
892
893 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700894 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
895 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
896 frame.width() < desiredWindowWidth && frame.width() != mWidth)
897 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
898 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899
900 final boolean computesInternalInsets =
901 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
902 boolean insetsPending = false;
903 int relayoutResult = 0;
904 if (mFirst || windowShouldResize || insetsChanged
905 || viewVisibilityChanged || params != null) {
906
907 if (viewVisibility == View.VISIBLE) {
908 // If this window is giving internal insets to the window
909 // manager, and it is being added or changing its visibility,
910 // then we want to first give the window manager "fake"
911 // insets to cause it to effectively ignore the content of
912 // the window during layout. This avoids it briefly causing
913 // other windows to resize/move based on the raw frame of the
914 // window, waiting until we can finish laying out this window
915 // and get back to the window manager with the ultimately
916 // computed insets.
917 insetsPending = computesInternalInsets
918 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
921 if (params == null) {
922 params = mWindowAttributes;
923 }
924 mGlWanted = true;
925 }
926 }
927
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700928 if (mSurfaceHolder != null) {
929 mSurfaceHolder.mSurfaceLock.lock();
930 mDrawingAllowed = true;
931 lp.format = mSurfaceHolder.getRequestedFormat();
932 lp.type = mSurfaceHolder.getRequestedType();
933 }
934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 boolean initialized = false;
936 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700937 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700938 boolean hadSurface = mSurface.isValid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 int fl = 0;
941 if (params != null) {
942 fl = params.flags;
943 if (attachInfo.mKeepScreenOn) {
944 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
945 }
946 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700947 if (DEBUG_LAYOUT) {
948 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
949 host.mMeasuredHeight + ", params=" + params);
950 }
951 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 if (params != null) {
954 params.flags = fl;
955 }
956
957 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
958 + " content=" + mPendingContentInsets.toShortString()
959 + " visible=" + mPendingVisibleInsets.toShortString()
960 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700961
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700962 if (mPendingConfiguration.seq != 0) {
963 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
964 + mPendingConfiguration);
965 updateConfiguration(mPendingConfiguration, !mFirst);
966 mPendingConfiguration.seq = 0;
967 }
968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 contentInsetsChanged = !mPendingContentInsets.equals(
970 mAttachInfo.mContentInsets);
971 visibleInsetsChanged = !mPendingVisibleInsets.equals(
972 mAttachInfo.mVisibleInsets);
973 if (contentInsetsChanged) {
974 mAttachInfo.mContentInsets.set(mPendingContentInsets);
975 host.fitSystemWindows(mAttachInfo.mContentInsets);
976 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
977 + mAttachInfo.mContentInsets);
978 }
979 if (visibleInsetsChanged) {
980 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
981 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
982 + mAttachInfo.mVisibleInsets);
983 }
984
985 if (!hadSurface) {
986 if (mSurface.isValid()) {
987 // If we are creating a new surface, then we need to
988 // completely redraw it. Also, when we get to the
989 // point of drawing it we will hold off and schedule
990 // a new traversal instead. This is so we can tell the
991 // window manager about all of the windows being displayed
992 // before actually drawing them, so it can display then
993 // all at once.
994 newSurface = true;
995 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700996 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 if (mGlWanted && !mUseGL) {
999 initializeGL();
1000 initialized = mGlCanvas != null;
1001 }
1002 }
1003 } else if (!mSurface.isValid()) {
1004 // If the surface has been removed, then reset the scroll
1005 // positions.
1006 mLastScrolledFocus = null;
1007 mScrollY = mCurScrollY = 0;
1008 if (mScroller != null) {
1009 mScroller.abortAnimation();
1010 }
1011 }
1012 } catch (RemoteException e) {
1013 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001016 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017
1018 attachInfo.mWindowLeft = frame.left;
1019 attachInfo.mWindowTop = frame.top;
1020
1021 // !!FIXME!! This next section handles the case where we did not get the
1022 // window size we asked for. We should avoid this by getting a maximum size from
1023 // the window session beforehand.
1024 mWidth = frame.width();
1025 mHeight = frame.height();
1026
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001027 if (mSurfaceHolder != null) {
1028 // The app owns the surface; tell it about what is going on.
1029 if (mSurface.isValid()) {
1030 // XXX .copyFrom() doesn't work!
1031 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1032 mSurfaceHolder.mSurface = mSurface;
1033 }
1034 mSurfaceHolder.mSurfaceLock.unlock();
1035 if (mSurface.isValid()) {
1036 if (!hadSurface) {
1037 mSurfaceHolder.ungetCallbacks();
1038
1039 mIsCreating = true;
1040 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1041 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1042 if (callbacks != null) {
1043 for (SurfaceHolder.Callback c : callbacks) {
1044 c.surfaceCreated(mSurfaceHolder);
1045 }
1046 }
1047 surfaceChanged = true;
1048 }
1049 if (surfaceChanged) {
1050 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1051 lp.format, mWidth, mHeight);
1052 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1053 if (callbacks != null) {
1054 for (SurfaceHolder.Callback c : callbacks) {
1055 c.surfaceChanged(mSurfaceHolder, lp.format,
1056 mWidth, mHeight);
1057 }
1058 }
1059 }
1060 mIsCreating = false;
1061 } else if (hadSurface) {
1062 mSurfaceHolder.ungetCallbacks();
1063 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1064 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1065 if (callbacks != null) {
1066 for (SurfaceHolder.Callback c : callbacks) {
1067 c.surfaceDestroyed(mSurfaceHolder);
1068 }
1069 }
1070 mSurfaceHolder.mSurfaceLock.lock();
1071 // Make surface invalid.
1072 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1073 mSurfaceHolder.mSurface = new Surface();
1074 mSurfaceHolder.mSurfaceLock.unlock();
1075 }
1076 }
1077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001079 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
1080 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082
1083 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001084 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1086 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1087 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1088 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1089
1090 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1091 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1092 + " mHeight=" + mHeight
1093 + " measuredHeight" + host.mMeasuredHeight
1094 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 // Ask host how big it wants to be
1097 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1098
1099 // Implementation of weights from WindowManager.LayoutParams
1100 // We just grow the dimensions as needed and re-measure if
1101 // needs be
1102 int width = host.mMeasuredWidth;
1103 int height = host.mMeasuredHeight;
1104 boolean measureAgain = false;
1105
1106 if (lp.horizontalWeight > 0.0f) {
1107 width += (int) ((mWidth - width) * lp.horizontalWeight);
1108 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1109 MeasureSpec.EXACTLY);
1110 measureAgain = true;
1111 }
1112 if (lp.verticalWeight > 0.0f) {
1113 height += (int) ((mHeight - height) * lp.verticalWeight);
1114 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1115 MeasureSpec.EXACTLY);
1116 measureAgain = true;
1117 }
1118
1119 if (measureAgain) {
1120 if (DEBUG_LAYOUT) Log.v(TAG,
1121 "And hey let's measure once more: width=" + width
1122 + " height=" + height);
1123 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1124 }
1125
1126 mLayoutRequested = true;
1127 }
1128 }
1129
1130 final boolean didLayout = mLayoutRequested;
1131 boolean triggerGlobalLayoutListener = didLayout
1132 || attachInfo.mRecomputeGlobalAttributes;
1133 if (didLayout) {
1134 mLayoutRequested = false;
1135 mScrollMayChange = true;
1136 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1137 "ViewRoot", "Laying out " + host + " to (" +
1138 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001139 long startTime = 0L;
1140 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 startTime = SystemClock.elapsedRealtime();
1142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1144
Romain Guy13922e02009-05-12 17:56:14 -07001145 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1146 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1147 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1148 + "please refer to the logs with the tag "
1149 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1150 }
1151 }
1152
1153 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1155 }
1156
1157 // By this point all views have been sized and positionned
1158 // We can compute the transparent area
1159
1160 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1161 // start out transparent
1162 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1163 host.getLocationInWindow(mTmpLocation);
1164 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1165 mTmpLocation[0] + host.mRight - host.mLeft,
1166 mTmpLocation[1] + host.mBottom - host.mTop);
1167
1168 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001169 if (mTranslator != null) {
1170 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1171 }
1172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1174 mPreviousTransparentRegion.set(mTransparentRegion);
1175 // reconfigure window manager
1176 try {
1177 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1178 } catch (RemoteException e) {
1179 }
1180 }
1181 }
1182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 if (DBG) {
1184 System.out.println("======================================");
1185 System.out.println("performTraversals -- after setFrame");
1186 host.debug();
1187 }
1188 }
1189
1190 if (triggerGlobalLayoutListener) {
1191 attachInfo.mRecomputeGlobalAttributes = false;
1192 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1193 }
1194
1195 if (computesInternalInsets) {
1196 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1197 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1198 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1199 givenContent.left = givenContent.top = givenContent.right
1200 = givenContent.bottom = givenVisible.left = givenVisible.top
1201 = givenVisible.right = givenVisible.bottom = 0;
1202 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001203 Rect contentInsets = insets.contentInsets;
1204 Rect visibleInsets = insets.visibleInsets;
1205 if (mTranslator != null) {
1206 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1207 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1210 mLastGivenInsets.set(insets);
1211 try {
1212 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001213 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 } catch (RemoteException e) {
1215 }
1216 }
1217 }
Romain Guy8506ab42009-06-11 17:35:47 -07001218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 if (mFirst) {
1220 // handle first focus request
1221 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1222 + mView.hasFocus());
1223 if (mView != null) {
1224 if (!mView.hasFocus()) {
1225 mView.requestFocus(View.FOCUS_FORWARD);
1226 mFocusedView = mRealFocusedView = mView.findFocus();
1227 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1228 + mFocusedView);
1229 } else {
1230 mRealFocusedView = mView.findFocus();
1231 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1232 + mRealFocusedView);
1233 }
1234 }
1235 }
1236
1237 mFirst = false;
1238 mWillDrawSoon = false;
1239 mNewSurfaceNeeded = false;
1240 mViewVisibility = viewVisibility;
1241
1242 if (mAttachInfo.mHasWindowFocus) {
1243 final boolean imTarget = WindowManager.LayoutParams
1244 .mayUseInputMethod(mWindowAttributes.flags);
1245 if (imTarget != mLastWasImTarget) {
1246 mLastWasImTarget = imTarget;
1247 InputMethodManager imm = InputMethodManager.peekInstance();
1248 if (imm != null && imTarget) {
1249 imm.startGettingWindowFocus(mView);
1250 imm.onWindowFocus(mView, mView.findFocus(),
1251 mWindowAttributes.softInputMode,
1252 !mHasHadWindowFocus, mWindowAttributes.flags);
1253 }
1254 }
1255 }
Romain Guy8506ab42009-06-11 17:35:47 -07001256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1258
1259 if (!cancelDraw && !newSurface) {
1260 mFullRedrawNeeded = false;
1261 draw(fullRedrawNeeded);
1262
1263 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1264 || mReportNextDraw) {
1265 if (LOCAL_LOGV) {
1266 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1267 }
1268 mReportNextDraw = false;
1269 try {
1270 sWindowSession.finishDrawing(mWindow);
1271 } catch (RemoteException e) {
1272 }
1273 }
1274 } else {
1275 // We were supposed to report when we are done drawing. Since we canceled the
1276 // draw, remember it here.
1277 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1278 mReportNextDraw = true;
1279 }
1280 if (fullRedrawNeeded) {
1281 mFullRedrawNeeded = true;
1282 }
1283 // Try again
1284 scheduleTraversals();
1285 }
1286 }
1287
1288 public void requestTransparentRegion(View child) {
1289 // the test below should not fail unless someone is messing with us
1290 checkThread();
1291 if (mView == child) {
1292 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1293 // Need to make sure we re-evaluate the window attributes next
1294 // time around, to ensure the window has the correct format.
1295 mWindowAttributesChanged = true;
1296 }
1297 }
1298
1299 /**
1300 * Figures out the measure spec for the root view in a window based on it's
1301 * layout params.
1302 *
1303 * @param windowSize
1304 * The available width or height of the window
1305 *
1306 * @param rootDimension
1307 * The layout params for one dimension (width or height) of the
1308 * window.
1309 *
1310 * @return The measure spec to use to measure the root view.
1311 */
1312 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1313 int measureSpec;
1314 switch (rootDimension) {
1315
Romain Guy980a9382010-01-08 15:06:28 -08001316 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 // Window can't resize. Force root view to be windowSize.
1318 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1319 break;
1320 case ViewGroup.LayoutParams.WRAP_CONTENT:
1321 // Window can resize. Set max size for root view.
1322 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1323 break;
1324 default:
1325 // Window wants to be an exact size. Force root view to be that size.
1326 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1327 break;
1328 }
1329 return measureSpec;
1330 }
1331
1332 private void draw(boolean fullRedrawNeeded) {
1333 Surface surface = mSurface;
1334 if (surface == null || !surface.isValid()) {
1335 return;
1336 }
1337
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001338 if (!sFirstDrawComplete) {
1339 synchronized (sFirstDrawHandlers) {
1340 sFirstDrawComplete = true;
1341 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1342 post(sFirstDrawHandlers.get(i));
1343 }
1344 }
1345 }
1346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 scrollToRectOrFocus(null, false);
1348
1349 if (mAttachInfo.mViewScrollChanged) {
1350 mAttachInfo.mViewScrollChanged = false;
1351 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1352 }
Romain Guy8506ab42009-06-11 17:35:47 -07001353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001355 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 if (scrolling) {
1357 yoff = mScroller.getCurrY();
1358 } else {
1359 yoff = mScrollY;
1360 }
1361 if (mCurScrollY != yoff) {
1362 mCurScrollY = yoff;
1363 fullRedrawNeeded = true;
1364 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001365 float appScale = mAttachInfo.mApplicationScale;
1366 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367
1368 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001369 if (mSurfaceHolder != null) {
1370 // The app owns the surface, we won't draw.
1371 dirty.setEmpty();
1372 return;
1373 }
1374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 if (mUseGL) {
1376 if (!dirty.isEmpty()) {
1377 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001378 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 mGL.glDisable(GL_SCISSOR_TEST);
1380 mGL.glClearColor(0, 0, 0, 0);
1381 mGL.glClear(GL_COLOR_BUFFER_BIT);
1382 mGL.glEnable(GL_SCISSOR_TEST);
1383
1384 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001385 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001387
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001388 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1389 try {
1390 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001391 if (mTranslator != null) {
1392 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001393 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001394 canvas.setScreenDensity(scalingRequired
1395 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001396 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001397 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1398 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1399 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001400 } finally {
1401 canvas.restoreToCount(saveCount);
1402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403
Romain Guy5bcdff42009-05-14 21:27:18 -07001404 mAttachInfo.mIgnoreDirtyState = false;
1405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1407 checkEglErrors();
1408
Mike Reedfd716532009-10-12 14:42:56 -04001409 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 int now = (int)SystemClock.elapsedRealtime();
1411 if (sDrawTime != 0) {
1412 nativeShowFPS(canvas, now - sDrawTime);
1413 }
1414 sDrawTime = now;
1415 }
1416 }
1417 }
1418 if (scrolling) {
1419 mFullRedrawNeeded = true;
1420 scheduleTraversals();
1421 }
1422 return;
1423 }
1424
Romain Guy5bcdff42009-05-14 21:27:18 -07001425 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001426 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001427 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429
1430 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1431 Log.v("ViewRoot", "Draw " + mView + "/"
1432 + mWindowAttributes.getTitle()
1433 + ": dirty={" + dirty.left + "," + dirty.top
1434 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001435 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1436 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
1438
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001439 if (!dirty.isEmpty() || mIsAnimating) {
1440 Canvas canvas;
1441 try {
1442 int left = dirty.left;
1443 int top = dirty.top;
1444 int right = dirty.right;
1445 int bottom = dirty.bottom;
1446 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001447
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001448 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1449 bottom != dirty.bottom) {
1450 mAttachInfo.mIgnoreDirtyState = true;
1451 }
1452
1453 // TODO: Do this in native
1454 canvas.setDensity(mDensity);
1455 } catch (Surface.OutOfResourcesException e) {
1456 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1457 // TODO: we should ask the window manager to do something!
1458 // for now we just do nothing
1459 return;
1460 } catch (IllegalArgumentException e) {
1461 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1462 // TODO: we should ask the window manager to do something!
1463 // for now we just do nothing
1464 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001465 }
1466
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001467 try {
1468 if (!dirty.isEmpty() || mIsAnimating) {
1469 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001471 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1472 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1473 + canvas.getWidth() + ", h=" + canvas.getHeight());
1474 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001477 if (Config.DEBUG && ViewDebug.profileDrawing) {
1478 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001480
1481 // If this bitmap's format includes an alpha channel, we
1482 // need to clear it before drawing so that the child will
1483 // properly re-composite its drawing on a transparent
1484 // background. This automatically respects the clip/dirty region
1485 // or
1486 // If we are applying an offset, we need to clear the area
1487 // where the offset doesn't appear to avoid having garbage
1488 // left in the blank areas.
1489 if (!canvas.isOpaque() || yoff != 0) {
1490 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1491 }
1492
1493 dirty.setEmpty();
1494 mIsAnimating = false;
1495 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1496 mView.mPrivateFlags |= View.DRAWN;
1497
1498 if (DEBUG_DRAW) {
1499 Context cxt = mView.getContext();
1500 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1501 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1502 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1503 }
1504 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1505 try {
1506 canvas.translate(0, -yoff);
1507 if (mTranslator != null) {
1508 mTranslator.translateCanvas(canvas);
1509 }
1510 canvas.setScreenDensity(scalingRequired
1511 ? DisplayMetrics.DENSITY_DEVICE : 0);
1512 mView.draw(canvas);
1513 } finally {
1514 mAttachInfo.mIgnoreDirtyState = false;
1515 canvas.restoreToCount(saveCount);
1516 }
1517
1518 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1519 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1520 }
1521
1522 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1523 int now = (int)SystemClock.elapsedRealtime();
1524 if (sDrawTime != 0) {
1525 nativeShowFPS(canvas, now - sDrawTime);
1526 }
1527 sDrawTime = now;
1528 }
1529
1530 if (Config.DEBUG && ViewDebug.profileDrawing) {
1531 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001535 } finally {
1536 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539
1540 if (LOCAL_LOGV) {
1541 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1542 }
Romain Guy8506ab42009-06-11 17:35:47 -07001543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 if (scrolling) {
1545 mFullRedrawNeeded = true;
1546 scheduleTraversals();
1547 }
1548 }
1549
1550 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1551 final View.AttachInfo attachInfo = mAttachInfo;
1552 final Rect ci = attachInfo.mContentInsets;
1553 final Rect vi = attachInfo.mVisibleInsets;
1554 int scrollY = 0;
1555 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 if (vi.left > ci.left || vi.top > ci.top
1558 || vi.right > ci.right || vi.bottom > ci.bottom) {
1559 // We'll assume that we aren't going to change the scroll
1560 // offset, since we want to avoid that unless it is actually
1561 // going to make the focus visible... otherwise we scroll
1562 // all over the place.
1563 scrollY = mScrollY;
1564 // We can be called for two different situations: during a draw,
1565 // to update the scroll position if the focus has changed (in which
1566 // case 'rectangle' is null), or in response to a
1567 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1568 // is non-null and we just want to scroll to whatever that
1569 // rectangle is).
1570 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001571
1572 // When in touch mode, focus points to the previously focused view,
1573 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001574 // line checks whether the view is still in our hierarchy.
1575 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001576 mRealFocusedView = null;
1577 return false;
1578 }
1579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 if (focus != mLastScrolledFocus) {
1581 // If the focus has changed, then ignore any requests to scroll
1582 // to a rectangle; first we want to make sure the entire focus
1583 // view is visible.
1584 rectangle = null;
1585 }
1586 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1587 + " rectangle=" + rectangle + " ci=" + ci
1588 + " vi=" + vi);
1589 if (focus == mLastScrolledFocus && !mScrollMayChange
1590 && rectangle == null) {
1591 // Optimization: if the focus hasn't changed since last
1592 // time, and no layout has happened, then just leave things
1593 // as they are.
1594 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1595 + mScrollY + " vi=" + vi.toShortString());
1596 } else if (focus != null) {
1597 // We need to determine if the currently focused view is
1598 // within the visible part of the window and, if not, apply
1599 // a pan so it can be seen.
1600 mLastScrolledFocus = focus;
1601 mScrollMayChange = false;
1602 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1603 // Try to find the rectangle from the focus view.
1604 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1605 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1606 + mView.getWidth() + " h=" + mView.getHeight()
1607 + " ci=" + ci.toShortString()
1608 + " vi=" + vi.toShortString());
1609 if (rectangle == null) {
1610 focus.getFocusedRect(mTempRect);
1611 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1612 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001613 if (mView instanceof ViewGroup) {
1614 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1615 focus, mTempRect);
1616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1618 "Focus in window: focusRect="
1619 + mTempRect.toShortString()
1620 + " visRect=" + mVisRect.toShortString());
1621 } else {
1622 mTempRect.set(rectangle);
1623 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1624 "Request scroll to rect: "
1625 + mTempRect.toShortString()
1626 + " visRect=" + mVisRect.toShortString());
1627 }
1628 if (mTempRect.intersect(mVisRect)) {
1629 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1630 "Focus window visible rect: "
1631 + mTempRect.toShortString());
1632 if (mTempRect.height() >
1633 (mView.getHeight()-vi.top-vi.bottom)) {
1634 // If the focus simply is not going to fit, then
1635 // best is probably just to leave things as-is.
1636 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1637 "Too tall; leaving scrollY=" + scrollY);
1638 } else if ((mTempRect.top-scrollY) < vi.top) {
1639 scrollY -= vi.top - (mTempRect.top-scrollY);
1640 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1641 "Top covered; scrollY=" + scrollY);
1642 } else if ((mTempRect.bottom-scrollY)
1643 > (mView.getHeight()-vi.bottom)) {
1644 scrollY += (mTempRect.bottom-scrollY)
1645 - (mView.getHeight()-vi.bottom);
1646 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1647 "Bottom covered; scrollY=" + scrollY);
1648 }
1649 handled = true;
1650 }
1651 }
1652 }
1653 }
Romain Guy8506ab42009-06-11 17:35:47 -07001654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 if (scrollY != mScrollY) {
1656 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1657 + mScrollY + " , new=" + scrollY);
1658 if (!immediate) {
1659 if (mScroller == null) {
1660 mScroller = new Scroller(mView.getContext());
1661 }
1662 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1663 } else if (mScroller != null) {
1664 mScroller.abortAnimation();
1665 }
1666 mScrollY = scrollY;
1667 }
Romain Guy8506ab42009-06-11 17:35:47 -07001668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 return handled;
1670 }
Romain Guy8506ab42009-06-11 17:35:47 -07001671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 public void requestChildFocus(View child, View focused) {
1673 checkThread();
1674 if (mFocusedView != focused) {
1675 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1676 scheduleTraversals();
1677 }
1678 mFocusedView = mRealFocusedView = focused;
1679 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1680 + mFocusedView);
1681 }
1682
1683 public void clearChildFocus(View child) {
1684 checkThread();
1685
1686 View oldFocus = mFocusedView;
1687
1688 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1689 mFocusedView = mRealFocusedView = null;
1690 if (mView != null && !mView.hasFocus()) {
1691 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1692 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1693 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1694 }
1695 } else if (oldFocus != null) {
1696 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1697 }
1698 }
1699
1700
1701 public void focusableViewAvailable(View v) {
1702 checkThread();
1703
1704 if (mView != null && !mView.hasFocus()) {
1705 v.requestFocus();
1706 } else {
1707 // the one case where will transfer focus away from the current one
1708 // is if the current view is a view group that prefers to give focus
1709 // to its children first AND the view is a descendant of it.
1710 mFocusedView = mView.findFocus();
1711 boolean descendantsHaveDibsOnFocus =
1712 (mFocusedView instanceof ViewGroup) &&
1713 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1714 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1715 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1716 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1717 v.requestFocus();
1718 }
1719 }
1720 }
1721
1722 public void recomputeViewAttributes(View child) {
1723 checkThread();
1724 if (mView == child) {
1725 mAttachInfo.mRecomputeGlobalAttributes = true;
1726 if (!mWillDrawSoon) {
1727 scheduleTraversals();
1728 }
1729 }
1730 }
1731
1732 void dispatchDetachedFromWindow() {
1733 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1734
1735 if (mView != null) {
1736 mView.dispatchDetachedFromWindow();
1737 }
1738
1739 mView = null;
1740 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001741 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742
1743 if (mUseGL) {
1744 destroyGL();
1745 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001746 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747
Jeff Brown46b9ac02010-04-22 18:58:52 -07001748 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
1749 if (mInputChannel != null) {
Dianne Hackborna95e4cb2010-06-18 18:09:33 -07001750 if (mInputConsumerCallback != null) {
1751 mInputConsumerCallback.onInputConsumerDestroyed(mInputConsumer);
1752 mInputConsumerCallback = null;
1753 } else {
1754 InputQueue.unregisterInputChannel(mInputChannel);
1755 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001756 mInputChannel.dispose();
1757 mInputChannel = null;
1758 }
1759 }
1760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 try {
1762 sWindowSession.remove(mWindow);
1763 } catch (RemoteException e) {
1764 }
1765 }
Romain Guy8506ab42009-06-11 17:35:47 -07001766
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001767 void updateConfiguration(Configuration config, boolean force) {
1768 if (DEBUG_CONFIGURATION) Log.v(TAG,
1769 "Applying new config to window "
1770 + mWindowAttributes.getTitle()
1771 + ": " + config);
1772 synchronized (sConfigCallbacks) {
1773 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1774 sConfigCallbacks.get(i).onConfigurationChanged(config);
1775 }
1776 }
1777 if (mView != null) {
1778 // At this point the resources have been updated to
1779 // have the most recent config, whatever that is. Use
1780 // the on in them which may be newer.
1781 if (mView != null) {
1782 config = mView.getResources().getConfiguration();
1783 }
1784 if (force || mLastConfiguration.diff(config) != 0) {
1785 mLastConfiguration.setTo(config);
1786 mView.dispatchConfigurationChanged(config);
1787 }
1788 }
1789 }
1790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 /**
1792 * Return true if child is an ancestor of parent, (or equal to the parent).
1793 */
1794 private static boolean isViewDescendantOf(View child, View parent) {
1795 if (child == parent) {
1796 return true;
1797 }
1798
1799 final ViewParent theParent = child.getParent();
1800 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1801 }
1802
Romain Guycdb86672010-03-18 18:54:50 -07001803 private static void forceLayout(View view) {
1804 view.forceLayout();
1805 if (view instanceof ViewGroup) {
1806 ViewGroup group = (ViewGroup) view;
1807 final int count = group.getChildCount();
1808 for (int i = 0; i < count; i++) {
1809 forceLayout(group.getChildAt(i));
1810 }
1811 }
1812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813
1814 public final static int DO_TRAVERSAL = 1000;
1815 public final static int DIE = 1001;
1816 public final static int RESIZED = 1002;
1817 public final static int RESIZED_REPORT = 1003;
1818 public final static int WINDOW_FOCUS_CHANGED = 1004;
1819 public final static int DISPATCH_KEY = 1005;
1820 public final static int DISPATCH_POINTER = 1006;
1821 public final static int DISPATCH_TRACKBALL = 1007;
1822 public final static int DISPATCH_APP_VISIBILITY = 1008;
1823 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1824 public final static int FINISHED_EVENT = 1010;
1825 public final static int DISPATCH_KEY_FROM_IME = 1011;
1826 public final static int FINISH_INPUT_CONNECTION = 1012;
1827 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001828 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829
1830 @Override
1831 public void handleMessage(Message msg) {
1832 switch (msg.what) {
1833 case View.AttachInfo.INVALIDATE_MSG:
1834 ((View) msg.obj).invalidate();
1835 break;
1836 case View.AttachInfo.INVALIDATE_RECT_MSG:
1837 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1838 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1839 info.release();
1840 break;
1841 case DO_TRAVERSAL:
1842 if (mProfile) {
1843 Debug.startMethodTracing("ViewRoot");
1844 }
1845
1846 performTraversals();
1847
1848 if (mProfile) {
1849 Debug.stopMethodTracing();
1850 mProfile = false;
1851 }
1852 break;
1853 case FINISHED_EVENT:
1854 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1855 break;
1856 case DISPATCH_KEY:
1857 if (LOCAL_LOGV) Log.v(
1858 "ViewRoot", "Dispatching key "
1859 + msg.obj + " to " + mView);
1860 deliverKeyEvent((KeyEvent)msg.obj, true);
1861 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001862 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001864 boolean callWhenDone = msg.arg1 != 0;
1865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001867 long timeBeforeGettingEvents;
1868 if (MEASURE_LATENCY) {
1869 timeBeforeGettingEvents = System.nanoTime();
1870 }
Michael Chan53071d62009-05-13 17:29:48 -07001871
Jeff Brown46b9ac02010-04-22 18:58:52 -07001872 event = getPendingPointerMotionEvent();
Michael Chan53071d62009-05-13 17:29:48 -07001873
Jeff Brown46b9ac02010-04-22 18:58:52 -07001874 if (MEASURE_LATENCY && event != null) {
1875 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1876 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001878 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001880 if (event != null && mTranslator != null) {
1881 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 try {
1884 boolean handled;
1885 if (mView != null && mAdded && event != null) {
1886
1887 // enter touch mode on the down
1888 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1889 if (isDown) {
1890 ensureTouchMode(true);
1891 }
1892 if(Config.LOGV) {
1893 captureMotionLog("captureDispatchPointer", event);
1894 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001895 if (mCurScrollY != 0) {
1896 event.offsetLocation(0, mCurScrollY);
1897 }
Michael Chan53071d62009-05-13 17:29:48 -07001898 if (MEASURE_LATENCY) {
1899 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001902 if (MEASURE_LATENCY) {
1903 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 if (!handled && isDown) {
1906 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1907
1908 final int edgeFlags = event.getEdgeFlags();
1909 int direction = View.FOCUS_UP;
1910 int x = (int)event.getX();
1911 int y = (int)event.getY();
1912 final int[] deltas = new int[2];
1913
1914 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1915 direction = View.FOCUS_DOWN;
1916 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1917 deltas[0] = edgeSlop;
1918 x += edgeSlop;
1919 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1920 deltas[0] = -edgeSlop;
1921 x -= edgeSlop;
1922 }
1923 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1924 direction = View.FOCUS_UP;
1925 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1926 deltas[0] = edgeSlop;
1927 x += edgeSlop;
1928 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1929 deltas[0] = -edgeSlop;
1930 x -= edgeSlop;
1931 }
1932 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1933 direction = View.FOCUS_RIGHT;
1934 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1935 direction = View.FOCUS_LEFT;
1936 }
1937
1938 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1939 View nearest = FocusFinder.getInstance().findNearestTouchable(
1940 ((ViewGroup) mView), x, y, direction, deltas);
1941 if (nearest != null) {
1942 event.offsetLocation(deltas[0], deltas[1]);
1943 event.setEdgeFlags(0);
1944 mView.dispatchTouchEvent(event);
1945 }
1946 }
1947 }
1948 }
1949 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001950 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001951 finishMotionEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001953 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1955 // Let the exception fall through -- the looper will catch
1956 // it and take care of the bad app for us.
1957 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001958 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001960 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 break;
1962 case DISPATCH_APP_VISIBILITY:
1963 handleAppVisibility(msg.arg1 != 0);
1964 break;
1965 case DISPATCH_GET_NEW_SURFACE:
1966 handleGetNewSurface();
1967 break;
1968 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001969 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001972 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001973 && mPendingVisibleInsets.equals(ri.visibleInsets)
1974 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 break;
1976 }
1977 // fall through...
1978 case RESIZED_REPORT:
1979 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001980 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1981 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001982 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 mWinFrame.left = 0;
1985 mWinFrame.right = msg.arg1;
1986 mWinFrame.top = 0;
1987 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001988 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1989 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 if (msg.what == RESIZED_REPORT) {
1991 mReportNextDraw = true;
1992 }
Romain Guycdb86672010-03-18 18:54:50 -07001993
1994 if (mView != null) {
1995 forceLayout(mView);
1996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 requestLayout();
1998 }
1999 break;
2000 case WINDOW_FOCUS_CHANGED: {
2001 if (mAdded) {
2002 boolean hasWindowFocus = msg.arg1 != 0;
2003 mAttachInfo.mHasWindowFocus = hasWindowFocus;
2004 if (hasWindowFocus) {
2005 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07002006 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007
2008 if (mGlWanted) {
2009 checkEglErrors();
2010 // we lost the gl context, so recreate it.
2011 if (mGlWanted && !mUseGL) {
2012 initializeGL();
2013 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002014 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002015 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002016 (int) (mWidth * appScale + 0.5f),
2017 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 }
2019 }
2020 }
2021 }
Romain Guy8506ab42009-06-11 17:35:47 -07002022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 mLastWasImTarget = WindowManager.LayoutParams
2024 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 InputMethodManager imm = InputMethodManager.peekInstance();
2027 if (mView != null) {
2028 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2029 imm.startGettingWindowFocus(mView);
2030 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002031 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 mView.dispatchWindowFocusChanged(hasWindowFocus);
2033 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 // Note: must be done after the focus change callbacks,
2036 // so all of the view state is set up correctly.
2037 if (hasWindowFocus) {
2038 if (imm != null && mLastWasImTarget) {
2039 imm.onWindowFocus(mView, mView.findFocus(),
2040 mWindowAttributes.softInputMode,
2041 !mHasHadWindowFocus, mWindowAttributes.flags);
2042 }
2043 // Clear the forward bit. We can just do this directly, since
2044 // the window manager doesn't care about it.
2045 mWindowAttributes.softInputMode &=
2046 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2047 ((WindowManager.LayoutParams)mView.getLayoutParams())
2048 .softInputMode &=
2049 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2050 mHasHadWindowFocus = true;
2051 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002052
2053 if (hasWindowFocus && mView != null) {
2054 sendAccessibilityEvents();
2055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057 } break;
2058 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002059 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002061 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 if (LOCAL_LOGV) Log.v(
2063 "ViewRoot", "Dispatching key "
2064 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002065 KeyEvent event = (KeyEvent)msg.obj;
2066 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2067 // The IME is trying to say this event is from the
2068 // system! Bad bad bad!
2069 event = KeyEvent.changeFlags(event,
2070 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
2071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002073 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 case FINISH_INPUT_CONNECTION: {
2075 InputMethodManager imm = InputMethodManager.peekInstance();
2076 if (imm != null) {
2077 imm.reportFinishInputConnection((InputConnection)msg.obj);
2078 }
2079 } break;
2080 case CHECK_FOCUS: {
2081 InputMethodManager imm = InputMethodManager.peekInstance();
2082 if (imm != null) {
2083 imm.checkFocus();
2084 }
2085 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002086 case CLOSE_SYSTEM_DIALOGS: {
2087 if (mView != null) {
2088 mView.onCloseSystemDialogs((String)msg.obj);
2089 }
2090 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002093
2094 private void finishKeyEvent(KeyEvent event) {
2095 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2096 if (mFinishedCallback != null) {
2097 mFinishedCallback.run();
2098 mFinishedCallback = null;
2099 }
2100 } else {
2101 try {
2102 sWindowSession.finishKey(mWindow);
2103 } catch (RemoteException e) {
2104 }
2105 }
2106 }
2107
2108 private void finishMotionEvent() {
2109 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2110 throw new IllegalStateException("Should not be reachable with native input dispatch.");
2111 }
2112
2113 try {
2114 sWindowSession.finishKey(mWindow);
2115 } catch (RemoteException e) {
2116 }
2117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118
Jeff Brown46b9ac02010-04-22 18:58:52 -07002119 private void recycleMotionEvent(MotionEvent event) {
2120 if (event != null) {
2121 event.recycle();
2122 }
2123 }
2124
2125 private MotionEvent getPendingPointerMotionEvent() {
2126 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2127 throw new IllegalStateException("Should not be reachable with native input dispatch.");
2128 }
2129
2130 try {
2131 return sWindowSession.getPendingPointerMove(mWindow);
2132 } catch (RemoteException e) {
2133 return null;
2134 }
2135 }
2136
2137 private MotionEvent getPendingTrackballMotionEvent() {
2138 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2139 throw new IllegalStateException("Should not be reachable with native input dispatch.");
2140 }
2141
2142 try {
2143 return sWindowSession.getPendingTrackballMove(mWindow);
2144 } catch (RemoteException e) {
2145 return null;
2146 }
2147 }
2148
2149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 /**
2151 * Something in the current window tells us we need to change the touch mode. For
2152 * example, we are not in touch mode, and the user touches the screen.
2153 *
2154 * If the touch mode has changed, tell the window manager, and handle it locally.
2155 *
2156 * @param inTouchMode Whether we want to be in touch mode.
2157 * @return True if the touch mode changed and focus changed was changed as a result
2158 */
2159 boolean ensureTouchMode(boolean inTouchMode) {
2160 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2161 + "touch mode is " + mAttachInfo.mInTouchMode);
2162 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2163
2164 // tell the window manager
2165 try {
2166 sWindowSession.setInTouchMode(inTouchMode);
2167 } catch (RemoteException e) {
2168 throw new RuntimeException(e);
2169 }
2170
2171 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002172 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
2174
2175 /**
2176 * Ensure that the touch mode for this window is set, and if it is changing,
2177 * take the appropriate action.
2178 * @param inTouchMode Whether we want to be in touch mode.
2179 * @return True if the touch mode changed and focus changed was changed as a result
2180 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002181 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2183 + "touch mode is " + mAttachInfo.mInTouchMode);
2184
2185 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2186
2187 mAttachInfo.mInTouchMode = inTouchMode;
2188 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2189
Romain Guy2d4cff62010-04-09 15:39:00 -07002190 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 }
2192
2193 private boolean enterTouchMode() {
2194 if (mView != null) {
2195 if (mView.hasFocus()) {
2196 // note: not relying on mFocusedView here because this could
2197 // be when the window is first being added, and mFocused isn't
2198 // set yet.
2199 final View focused = mView.findFocus();
2200 if (focused != null && !focused.isFocusableInTouchMode()) {
2201
2202 final ViewGroup ancestorToTakeFocus =
2203 findAncestorToTakeFocusInTouchMode(focused);
2204 if (ancestorToTakeFocus != null) {
2205 // there is an ancestor that wants focus after its descendants that
2206 // is focusable in touch mode.. give it focus
2207 return ancestorToTakeFocus.requestFocus();
2208 } else {
2209 // nothing appropriate to have focus in touch mode, clear it out
2210 mView.unFocus();
2211 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2212 mFocusedView = null;
2213 return true;
2214 }
2215 }
2216 }
2217 }
2218 return false;
2219 }
2220
2221
2222 /**
2223 * Find an ancestor of focused that wants focus after its descendants and is
2224 * focusable in touch mode.
2225 * @param focused The currently focused view.
2226 * @return An appropriate view, or null if no such view exists.
2227 */
2228 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2229 ViewParent parent = focused.getParent();
2230 while (parent instanceof ViewGroup) {
2231 final ViewGroup vgParent = (ViewGroup) parent;
2232 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2233 && vgParent.isFocusableInTouchMode()) {
2234 return vgParent;
2235 }
2236 if (vgParent.isRootNamespace()) {
2237 return null;
2238 } else {
2239 parent = vgParent.getParent();
2240 }
2241 }
2242 return null;
2243 }
2244
2245 private boolean leaveTouchMode() {
2246 if (mView != null) {
2247 if (mView.hasFocus()) {
2248 // i learned the hard way to not trust mFocusedView :)
2249 mFocusedView = mView.findFocus();
2250 if (!(mFocusedView instanceof ViewGroup)) {
2251 // some view has focus, let it keep it
2252 return false;
2253 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2254 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2255 // some view group has focus, and doesn't prefer its children
2256 // over itself for focus, so let them keep it.
2257 return false;
2258 }
2259 }
2260
2261 // find the best view to give focus to in this brave new non-touch-mode
2262 // world
2263 final View focused = focusSearch(null, View.FOCUS_DOWN);
2264 if (focused != null) {
2265 return focused.requestFocus(View.FOCUS_DOWN);
2266 }
2267 }
2268 return false;
2269 }
2270
2271
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002272 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002274 event = getPendingTrackballMotionEvent();
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002275 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 }
2277
2278 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2279
2280 boolean handled = false;
2281 try {
2282 if (event == null) {
2283 handled = true;
2284 } else if (mView != null && mAdded) {
2285 handled = mView.dispatchTrackballEvent(event);
2286 if (!handled) {
2287 // we could do something here, like changing the focus
2288 // or something?
2289 }
2290 }
2291 } finally {
2292 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002293 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002294 finishMotionEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002296 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 // If we reach this, we delivered a trackball event to mView and
2298 // mView consumed it. Because we will not translate the trackball
2299 // event into a key event, touch mode will not exit, so we exit
2300 // touch mode here.
2301 ensureTouchMode(false);
2302 //noinspection ReturnInsideFinallyBlock
2303 return;
2304 }
2305 // Let the exception fall through -- the looper will catch
2306 // it and take care of the bad app for us.
2307 }
2308
2309 final TrackballAxis x = mTrackballAxisX;
2310 final TrackballAxis y = mTrackballAxisY;
2311
2312 long curTime = SystemClock.uptimeMillis();
2313 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2314 // It has been too long since the last movement,
2315 // so restart at the beginning.
2316 x.reset(0);
2317 y.reset(0);
2318 mLastTrackballTime = curTime;
2319 }
2320
2321 try {
2322 final int action = event.getAction();
2323 final int metastate = event.getMetaState();
2324 switch (action) {
2325 case MotionEvent.ACTION_DOWN:
2326 x.reset(2);
2327 y.reset(2);
2328 deliverKeyEvent(new KeyEvent(curTime, curTime,
2329 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2330 0, metastate), false);
2331 break;
2332 case MotionEvent.ACTION_UP:
2333 x.reset(2);
2334 y.reset(2);
2335 deliverKeyEvent(new KeyEvent(curTime, curTime,
2336 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2337 0, metastate), false);
2338 break;
2339 }
2340
2341 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2342 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2343 + " move=" + event.getX()
2344 + " / Y=" + y.position + " step="
2345 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2346 + " move=" + event.getY());
2347 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2348 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2349
2350 // Generate DPAD events based on the trackball movement.
2351 // We pick the axis that has moved the most as the direction of
2352 // the DPAD. When we generate DPAD events for one axis, then the
2353 // other axis is reset -- we don't want to perform DPAD jumps due
2354 // to slight movements in the trackball when making major movements
2355 // along the other axis.
2356 int keycode = 0;
2357 int movement = 0;
2358 float accel = 1;
2359 if (xOff > yOff) {
2360 movement = x.generate((2/event.getXPrecision()));
2361 if (movement != 0) {
2362 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2363 : KeyEvent.KEYCODE_DPAD_LEFT;
2364 accel = x.acceleration;
2365 y.reset(2);
2366 }
2367 } else if (yOff > 0) {
2368 movement = y.generate((2/event.getYPrecision()));
2369 if (movement != 0) {
2370 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2371 : KeyEvent.KEYCODE_DPAD_UP;
2372 accel = y.acceleration;
2373 x.reset(2);
2374 }
2375 }
2376
2377 if (keycode != 0) {
2378 if (movement < 0) movement = -movement;
2379 int accelMovement = (int)(movement * accel);
2380 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2381 + " accelMovement=" + accelMovement
2382 + " accel=" + accel);
2383 if (accelMovement > movement) {
2384 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2385 + keycode);
2386 movement--;
2387 deliverKeyEvent(new KeyEvent(curTime, curTime,
2388 KeyEvent.ACTION_MULTIPLE, keycode,
2389 accelMovement-movement, metastate), false);
2390 }
2391 while (movement > 0) {
2392 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2393 + keycode);
2394 movement--;
2395 curTime = SystemClock.uptimeMillis();
2396 deliverKeyEvent(new KeyEvent(curTime, curTime,
2397 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2398 deliverKeyEvent(new KeyEvent(curTime, curTime,
2399 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2400 }
2401 mLastTrackballTime = curTime;
2402 }
2403 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002404 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002405 finishMotionEvent();
2406 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 }
2408 // Let the exception fall through -- the looper will catch
2409 // it and take care of the bad app for us.
2410 }
2411 }
2412
2413 /**
2414 * @param keyCode The key code
2415 * @return True if the key is directional.
2416 */
2417 static boolean isDirectional(int keyCode) {
2418 switch (keyCode) {
2419 case KeyEvent.KEYCODE_DPAD_LEFT:
2420 case KeyEvent.KEYCODE_DPAD_RIGHT:
2421 case KeyEvent.KEYCODE_DPAD_UP:
2422 case KeyEvent.KEYCODE_DPAD_DOWN:
2423 return true;
2424 }
2425 return false;
2426 }
2427
2428 /**
2429 * Returns true if this key is a keyboard key.
2430 * @param keyEvent The key event.
2431 * @return whether this key is a keyboard key.
2432 */
2433 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2434 final int convertedKey = keyEvent.getUnicodeChar();
2435 return convertedKey > 0;
2436 }
2437
2438
2439
2440 /**
2441 * See if the key event means we should leave touch mode (and leave touch
2442 * mode if so).
2443 * @param event The key event.
2444 * @return Whether this key event should be consumed (meaning the act of
2445 * leaving touch mode alone is considered the event).
2446 */
2447 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002448 final int action = event.getAction();
2449 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 return false;
2451 }
2452 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2453 return false;
2454 }
2455
2456 // only relevant if we are in touch mode
2457 if (!mAttachInfo.mInTouchMode) {
2458 return false;
2459 }
2460
2461 // if something like an edit text has focus and the user is typing,
2462 // leave touch mode
2463 //
2464 // note: the condition of not being a keyboard key is kind of a hacky
2465 // approximation of whether we think the focused view will want the
2466 // key; if we knew for sure whether the focused view would consume
2467 // the event, that would be better.
2468 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2469 mFocusedView = mView.findFocus();
2470 if ((mFocusedView instanceof ViewGroup)
2471 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2472 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2473 // something has focus, but is holding it weakly as a container
2474 return false;
2475 }
2476 if (ensureTouchMode(false)) {
2477 throw new IllegalStateException("should not have changed focus "
2478 + "when leaving touch mode while a view has focus.");
2479 }
2480 return false;
2481 }
2482
2483 if (isDirectional(event.getKeyCode())) {
2484 // no view has focus, so we leave touch mode (and find something
2485 // to give focus to). the event is consumed if we were able to
2486 // find something to give focus to.
2487 return ensureTouchMode(false);
2488 }
2489 return false;
2490 }
2491
2492 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002493 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 */
2495 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002496 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 if (ev == null ||
2498 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2499 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
Romain Guy8506ab42009-06-11 17:35:47 -07002501
2502 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 sb.append(ev.getDownTime()).append(',');
2504 sb.append(ev.getEventTime()).append(',');
2505 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002506 sb.append(ev.getX()).append(',');
2507 sb.append(ev.getY()).append(',');
2508 sb.append(ev.getPressure()).append(',');
2509 sb.append(ev.getSize()).append(',');
2510 sb.append(ev.getMetaState()).append(',');
2511 sb.append(ev.getXPrecision()).append(',');
2512 sb.append(ev.getYPrecision()).append(',');
2513 sb.append(ev.getDeviceId()).append(',');
2514 sb.append(ev.getEdgeFlags());
2515 Log.d(TAG, sb.toString());
2516 }
2517 /**
2518 * log motion events
2519 */
2520 private static void captureKeyLog(String subTag, KeyEvent ev) {
2521 //check dynamic switch
2522 if (ev == null ||
2523 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2524 return;
2525 }
2526 StringBuilder sb = new StringBuilder(subTag + ": ");
2527 sb.append(ev.getDownTime()).append(',');
2528 sb.append(ev.getEventTime()).append(',');
2529 sb.append(ev.getAction()).append(',');
2530 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 sb.append(ev.getRepeatCount()).append(',');
2532 sb.append(ev.getMetaState()).append(',');
2533 sb.append(ev.getDeviceId()).append(',');
2534 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002535 Log.d(TAG, sb.toString());
2536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537
2538 int enqueuePendingEvent(Object event, boolean sendDone) {
2539 int seq = mPendingEventSeq+1;
2540 if (seq < 0) seq = 0;
2541 mPendingEventSeq = seq;
2542 mPendingEvents.put(seq, event);
2543 return sendDone ? seq : -seq;
2544 }
2545
2546 Object retrievePendingEvent(int seq) {
2547 if (seq < 0) seq = -seq;
2548 Object event = mPendingEvents.get(seq);
2549 if (event != null) {
2550 mPendingEvents.remove(seq);
2551 }
2552 return event;
2553 }
Romain Guy8506ab42009-06-11 17:35:47 -07002554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2556 // If mView is null, we just consume the key event because it doesn't
2557 // make sense to do anything else with it.
2558 boolean handled = mView != null
2559 ? mView.dispatchKeyEventPreIme(event) : true;
2560 if (handled) {
2561 if (sendDone) {
2562 if (LOCAL_LOGV) Log.v(
2563 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002564 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566 return;
2567 }
2568 // If it is possible for this window to interact with the input
2569 // method window, then we want to first dispatch our key events
2570 // to the input method.
2571 if (mLastWasImTarget) {
2572 InputMethodManager imm = InputMethodManager.peekInstance();
2573 if (imm != null && mView != null) {
2574 int seq = enqueuePendingEvent(event, sendDone);
2575 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2576 + seq + " event=" + event);
2577 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2578 mInputMethodCallback);
2579 return;
2580 }
2581 }
2582 deliverKeyEventToViewHierarchy(event, sendDone);
2583 }
2584
2585 void handleFinishedEvent(int seq, boolean handled) {
2586 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2587 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2588 + " handled=" + handled + " event=" + event);
2589 if (event != null) {
2590 final boolean sendDone = seq >= 0;
2591 if (!handled) {
2592 deliverKeyEventToViewHierarchy(event, sendDone);
2593 return;
2594 } else if (sendDone) {
2595 if (LOCAL_LOGV) Log.v(
2596 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002597 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 } else {
2599 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2600 + " handled=" + handled + " ev=" + event
2601 + ") neither delivering nor finishing key");
2602 }
2603 }
2604 }
Romain Guy8506ab42009-06-11 17:35:47 -07002605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2607 try {
2608 if (mView != null && mAdded) {
2609 final int action = event.getAction();
2610 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2611
2612 if (checkForLeavingTouchModeAndConsume(event)) {
2613 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002614 }
2615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 if (Config.LOGV) {
2617 captureKeyLog("captureDispatchKeyEvent", event);
2618 }
2619 boolean keyHandled = mView.dispatchKeyEvent(event);
2620
2621 if (!keyHandled && isDown) {
2622 int direction = 0;
2623 switch (event.getKeyCode()) {
2624 case KeyEvent.KEYCODE_DPAD_LEFT:
2625 direction = View.FOCUS_LEFT;
2626 break;
2627 case KeyEvent.KEYCODE_DPAD_RIGHT:
2628 direction = View.FOCUS_RIGHT;
2629 break;
2630 case KeyEvent.KEYCODE_DPAD_UP:
2631 direction = View.FOCUS_UP;
2632 break;
2633 case KeyEvent.KEYCODE_DPAD_DOWN:
2634 direction = View.FOCUS_DOWN;
2635 break;
2636 }
2637
2638 if (direction != 0) {
2639
2640 View focused = mView != null ? mView.findFocus() : null;
2641 if (focused != null) {
2642 View v = focused.focusSearch(direction);
2643 boolean focusPassed = false;
2644 if (v != null && v != focused) {
2645 // do the math the get the interesting rect
2646 // of previous focused into the coord system of
2647 // newly focused view
2648 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002649 if (mView instanceof ViewGroup) {
2650 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2651 focused, mTempRect);
2652 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2653 v, mTempRect);
2654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 focusPassed = v.requestFocus(direction, mTempRect);
2656 }
2657
2658 if (!focusPassed) {
2659 mView.dispatchUnhandledMove(focused, direction);
2660 } else {
2661 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2662 }
2663 }
2664 }
2665 }
2666 }
2667
2668 } finally {
2669 if (sendDone) {
2670 if (LOCAL_LOGV) Log.v(
2671 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002672 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674 // Let the exception fall through -- the looper will catch
2675 // it and take care of the bad app for us.
2676 }
2677 }
2678
2679 private AudioManager getAudioManager() {
2680 if (mView == null) {
2681 throw new IllegalStateException("getAudioManager called when there is no mView");
2682 }
2683 if (mAudioManager == null) {
2684 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2685 }
2686 return mAudioManager;
2687 }
2688
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002689 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2690 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002691
2692 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002693 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002694 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002695 restore = true;
2696 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002697 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002698 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002699 if (params != null) {
2700 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002701 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002702 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002703 int relayoutResult = sWindowSession.relayout(
2704 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002705 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2706 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002707 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002708 mPendingContentInsets, mPendingVisibleInsets,
2709 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002710 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002711 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002712 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002713
2714 if (mTranslator != null) {
2715 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2716 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2717 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002718 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002719 return relayoutResult;
2720 }
Romain Guy8506ab42009-06-11 17:35:47 -07002721
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002722 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 * {@inheritDoc}
2724 */
2725 public void playSoundEffect(int effectId) {
2726 checkThread();
2727
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002728 try {
2729 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002731 switch (effectId) {
2732 case SoundEffectConstants.CLICK:
2733 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2734 return;
2735 case SoundEffectConstants.NAVIGATION_DOWN:
2736 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2737 return;
2738 case SoundEffectConstants.NAVIGATION_LEFT:
2739 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2740 return;
2741 case SoundEffectConstants.NAVIGATION_RIGHT:
2742 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2743 return;
2744 case SoundEffectConstants.NAVIGATION_UP:
2745 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2746 return;
2747 default:
2748 throw new IllegalArgumentException("unknown effect id " + effectId +
2749 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2750 }
2751 } catch (IllegalStateException e) {
2752 // Exception thrown by getAudioManager() when mView is null
2753 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2754 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
2756 }
2757
2758 /**
2759 * {@inheritDoc}
2760 */
2761 public boolean performHapticFeedback(int effectId, boolean always) {
2762 try {
2763 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2764 } catch (RemoteException e) {
2765 return false;
2766 }
2767 }
2768
2769 /**
2770 * {@inheritDoc}
2771 */
2772 public View focusSearch(View focused, int direction) {
2773 checkThread();
2774 if (!(mView instanceof ViewGroup)) {
2775 return null;
2776 }
2777 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2778 }
2779
2780 public void debug() {
2781 mView.debug();
2782 }
2783
2784 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002785 if (immediate) {
2786 doDie();
2787 } else {
2788 sendEmptyMessage(DIE);
2789 }
2790 }
2791
2792 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 checkThread();
2794 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2795 synchronized (this) {
2796 if (mAdded && !mFirst) {
2797 int viewVisibility = mView.getVisibility();
2798 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2799 if (mWindowAttributesChanged || viewVisibilityChanged) {
2800 // If layout params have been changed, first give them
2801 // to the window manager to make sure it has the correct
2802 // animation info.
2803 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002804 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2805 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 sWindowSession.finishDrawing(mWindow);
2807 }
2808 } catch (RemoteException e) {
2809 }
2810 }
2811
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002812 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 }
2814 if (mAdded) {
2815 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002816 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 }
2818 }
2819 }
2820
2821 public void dispatchFinishedEvent(int seq, boolean handled) {
2822 Message msg = obtainMessage(FINISHED_EVENT);
2823 msg.arg1 = seq;
2824 msg.arg2 = handled ? 1 : 0;
2825 sendMessage(msg);
2826 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002829 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2831 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2832 + " visibleInsets=" + visibleInsets.toShortString()
2833 + " reportDraw=" + reportDraw);
2834 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002835 if (mTranslator != null) {
2836 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2837 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2838 w *= mTranslator.applicationInvertedScale;
2839 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002840 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002841 msg.arg1 = w;
2842 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002843 ResizedInfo ri = new ResizedInfo();
2844 ri.coveredInsets = new Rect(coveredInsets);
2845 ri.visibleInsets = new Rect(visibleInsets);
2846 ri.newConfig = newConfig;
2847 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 sendMessage(msg);
2849 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002850
2851 private Runnable mFinishedCallback;
2852
2853 private final InputHandler mInputHandler = new InputHandler() {
2854 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2855 mFinishedCallback = finishedCallback;
2856
2857 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2858 //noinspection ConstantConditions
2859 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2860 if (Config.LOGD) Log.d("keydisp",
2861 "===================================================");
2862 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2863 debug();
2864
2865 if (Config.LOGD) Log.d("keydisp",
2866 "===================================================");
2867 }
2868 }
2869
2870 Message msg = obtainMessage(DISPATCH_KEY);
2871 msg.obj = event;
2872
2873 if (LOCAL_LOGV) Log.v(
2874 "ViewRoot", "sending key " + event + " to " + mView);
2875
2876 sendMessageAtTime(msg, event.getEventTime());
2877 }
2878
2879 public void handleTouch(MotionEvent event, Runnable finishedCallback) {
2880 finishedCallback.run();
2881
2882 Message msg = obtainMessage(DISPATCH_POINTER);
2883 msg.obj = event;
2884 msg.arg1 = 0;
2885 sendMessageAtTime(msg, event.getEventTime());
2886 }
2887
2888 public void handleTrackball(MotionEvent event, Runnable finishedCallback) {
2889 finishedCallback.run();
2890
2891 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2892 msg.obj = event;
2893 msg.arg1 = 0;
2894 sendMessageAtTime(msg, event.getEventTime());
2895 }
2896 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897
2898 public void dispatchKey(KeyEvent event) {
2899 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2900 //noinspection ConstantConditions
2901 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2902 if (Config.LOGD) Log.d("keydisp",
2903 "===================================================");
2904 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2905 debug();
2906
2907 if (Config.LOGD) Log.d("keydisp",
2908 "===================================================");
2909 }
2910 }
2911
2912 Message msg = obtainMessage(DISPATCH_KEY);
2913 msg.obj = event;
2914
2915 if (LOCAL_LOGV) Log.v(
2916 "ViewRoot", "sending key " + event + " to " + mView);
2917
2918 sendMessageAtTime(msg, event.getEventTime());
2919 }
2920
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002921 public void dispatchPointer(MotionEvent event, long eventTime,
2922 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 Message msg = obtainMessage(DISPATCH_POINTER);
2924 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002925 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 sendMessageAtTime(msg, eventTime);
2927 }
2928
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002929 public void dispatchTrackball(MotionEvent event, long eventTime,
2930 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2932 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002933 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 sendMessageAtTime(msg, eventTime);
2935 }
2936
2937 public void dispatchAppVisibility(boolean visible) {
2938 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2939 msg.arg1 = visible ? 1 : 0;
2940 sendMessage(msg);
2941 }
2942
2943 public void dispatchGetNewSurface() {
2944 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2945 sendMessage(msg);
2946 }
2947
2948 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2949 Message msg = Message.obtain();
2950 msg.what = WINDOW_FOCUS_CHANGED;
2951 msg.arg1 = hasFocus ? 1 : 0;
2952 msg.arg2 = inTouchMode ? 1 : 0;
2953 sendMessage(msg);
2954 }
2955
Dianne Hackbornffa42482009-09-23 22:20:11 -07002956 public void dispatchCloseSystemDialogs(String reason) {
2957 Message msg = Message.obtain();
2958 msg.what = CLOSE_SYSTEM_DIALOGS;
2959 msg.obj = reason;
2960 sendMessage(msg);
2961 }
2962
svetoslavganov75986cf2009-05-14 22:28:01 -07002963 /**
2964 * The window is getting focus so if there is anything focused/selected
2965 * send an {@link AccessibilityEvent} to announce that.
2966 */
2967 private void sendAccessibilityEvents() {
2968 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2969 return;
2970 }
2971 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2972 View focusedView = mView.findFocus();
2973 if (focusedView != null && focusedView != mView) {
2974 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2975 }
2976 }
2977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 public boolean showContextMenuForChild(View originalView) {
2979 return false;
2980 }
2981
2982 public void createContextMenu(ContextMenu menu) {
2983 }
2984
2985 public void childDrawableStateChanged(View child) {
2986 }
2987
2988 protected Rect getWindowFrame() {
2989 return mWinFrame;
2990 }
2991
2992 void checkThread() {
2993 if (mThread != Thread.currentThread()) {
2994 throw new CalledFromWrongThreadException(
2995 "Only the original thread that created a view hierarchy can touch its views.");
2996 }
2997 }
2998
2999 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3000 // ViewRoot never intercepts touch event, so this can be a no-op
3001 }
3002
3003 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3004 boolean immediate) {
3005 return scrollToRectOrFocus(rectangle, immediate);
3006 }
Romain Guy8506ab42009-06-11 17:35:47 -07003007
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003008 class TakenSurfaceHolder extends BaseSurfaceHolder {
3009 @Override
3010 public boolean onAllowLockCanvas() {
3011 return mDrawingAllowed;
3012 }
3013
3014 @Override
3015 public void onRelayoutContainer() {
3016 // Not currently interesting -- from changing between fixed and layout size.
3017 }
3018
3019 public void setFormat(int format) {
3020 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3021 }
3022
3023 public void setType(int type) {
3024 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3025 }
3026
3027 @Override
3028 public void onUpdateSurface() {
3029 // We take care of format and type changes on our own.
3030 throw new IllegalStateException("Shouldn't be here");
3031 }
3032
3033 public boolean isCreating() {
3034 return mIsCreating;
3035 }
3036
3037 @Override
3038 public void setFixedSize(int width, int height) {
3039 throw new UnsupportedOperationException(
3040 "Currently only support sizing from layout");
3041 }
3042
3043 public void setKeepScreenOn(boolean screenOn) {
3044 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3045 }
3046 }
3047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 static class InputMethodCallback extends IInputMethodCallback.Stub {
3049 private WeakReference<ViewRoot> mViewRoot;
3050
3051 public InputMethodCallback(ViewRoot viewRoot) {
3052 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3053 }
Romain Guy8506ab42009-06-11 17:35:47 -07003054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 public void finishedEvent(int seq, boolean handled) {
3056 final ViewRoot viewRoot = mViewRoot.get();
3057 if (viewRoot != null) {
3058 viewRoot.dispatchFinishedEvent(seq, handled);
3059 }
3060 }
3061
3062 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3063 // Stub -- not for use in the client.
3064 }
3065 }
Romain Guy8506ab42009-06-11 17:35:47 -07003066
Jeff Brown46b9ac02010-04-22 18:58:52 -07003067 class EventCompletion extends Handler {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003068 final IWindow mWindow;
3069 final KeyEvent mKeyEvent;
3070 final boolean mIsPointer;
3071 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07003072
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003073 EventCompletion(Looper looper, IWindow window, KeyEvent key,
3074 boolean isPointer, MotionEvent motion) {
3075 super(looper);
3076 mWindow = window;
3077 mKeyEvent = key;
3078 mIsPointer = isPointer;
3079 mMotionEvent = motion;
3080 sendEmptyMessage(0);
3081 }
Romain Guy8506ab42009-06-11 17:35:47 -07003082
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003083 @Override
3084 public void handleMessage(Message msg) {
3085 if (mKeyEvent != null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003086 finishKeyEvent(mKeyEvent);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003087 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003088 boolean didFinish;
3089 MotionEvent event = mMotionEvent;
3090 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003091 event = getPendingPointerMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003092 didFinish = true;
3093 } else {
3094 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
3095 }
3096 if (!didFinish) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003097 finishMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003098 }
3099 } else {
3100 MotionEvent event = mMotionEvent;
3101 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003102 event = getPendingTrackballMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003103 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003104 finishMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003105 }
3106 }
3107 }
3108 }
Romain Guy8506ab42009-06-11 17:35:47 -07003109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003111 private final WeakReference<ViewRoot> mViewRoot;
3112 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003114 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003116 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 }
3118
3119 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003120 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 final ViewRoot viewRoot = mViewRoot.get();
3122 if (viewRoot != null) {
3123 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003124 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 }
3126 }
3127
3128 public void dispatchKey(KeyEvent event) {
3129 final ViewRoot viewRoot = mViewRoot.get();
3130 if (viewRoot != null) {
3131 viewRoot.dispatchKey(event);
3132 } else {
3133 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
Jeff Brown46b9ac02010-04-22 18:58:52 -07003134 viewRoot.new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 }
3136 }
3137
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003138 public void dispatchPointer(MotionEvent event, long eventTime,
3139 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07003141 if (viewRoot != null) {
3142 if (MEASURE_LATENCY) {
3143 // Note: eventTime is in milliseconds
3144 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
3145 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003146 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003147 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003148 viewRoot.new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 }
3150 }
3151
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003152 public void dispatchTrackball(MotionEvent event, long eventTime,
3153 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 final ViewRoot viewRoot = mViewRoot.get();
3155 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003156 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003157 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003158 viewRoot.new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 }
3160 }
3161
3162 public void dispatchAppVisibility(boolean visible) {
3163 final ViewRoot viewRoot = mViewRoot.get();
3164 if (viewRoot != null) {
3165 viewRoot.dispatchAppVisibility(visible);
3166 }
3167 }
3168
3169 public void dispatchGetNewSurface() {
3170 final ViewRoot viewRoot = mViewRoot.get();
3171 if (viewRoot != null) {
3172 viewRoot.dispatchGetNewSurface();
3173 }
3174 }
3175
3176 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3177 final ViewRoot viewRoot = mViewRoot.get();
3178 if (viewRoot != null) {
3179 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3180 }
3181 }
3182
3183 private static int checkCallingPermission(String permission) {
3184 if (!Process.supportsProcesses()) {
3185 return PackageManager.PERMISSION_GRANTED;
3186 }
3187
3188 try {
3189 return ActivityManagerNative.getDefault().checkPermission(
3190 permission, Binder.getCallingPid(), Binder.getCallingUid());
3191 } catch (RemoteException e) {
3192 return PackageManager.PERMISSION_DENIED;
3193 }
3194 }
3195
3196 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3197 final ViewRoot viewRoot = mViewRoot.get();
3198 if (viewRoot != null) {
3199 final View view = viewRoot.mView;
3200 if (view != null) {
3201 if (checkCallingPermission(Manifest.permission.DUMP) !=
3202 PackageManager.PERMISSION_GRANTED) {
3203 throw new SecurityException("Insufficient permissions to invoke"
3204 + " executeCommand() from pid=" + Binder.getCallingPid()
3205 + ", uid=" + Binder.getCallingUid());
3206 }
3207
3208 OutputStream clientStream = null;
3209 try {
3210 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3211 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3212 } catch (IOException e) {
3213 e.printStackTrace();
3214 } finally {
3215 if (clientStream != null) {
3216 try {
3217 clientStream.close();
3218 } catch (IOException e) {
3219 e.printStackTrace();
3220 }
3221 }
3222 }
3223 }
3224 }
3225 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003226
Dianne Hackbornffa42482009-09-23 22:20:11 -07003227 public void closeSystemDialogs(String reason) {
3228 final ViewRoot viewRoot = mViewRoot.get();
3229 if (viewRoot != null) {
3230 viewRoot.dispatchCloseSystemDialogs(reason);
3231 }
3232 }
3233
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003234 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3235 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003236 if (sync) {
3237 try {
3238 sWindowSession.wallpaperOffsetsComplete(asBinder());
3239 } catch (RemoteException e) {
3240 }
3241 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003242 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003243
3244 public void dispatchWallpaperCommand(String action, int x, int y,
3245 int z, Bundle extras, boolean sync) {
3246 if (sync) {
3247 try {
3248 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3249 } catch (RemoteException e) {
3250 }
3251 }
3252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 }
3254
3255 /**
3256 * Maintains state information for a single trackball axis, generating
3257 * discrete (DPAD) movements based on raw trackball motion.
3258 */
3259 static final class TrackballAxis {
3260 /**
3261 * The maximum amount of acceleration we will apply.
3262 */
3263 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 /**
3266 * The maximum amount of time (in milliseconds) between events in order
3267 * for us to consider the user to be doing fast trackball movements,
3268 * and thus apply an acceleration.
3269 */
3270 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 /**
3273 * Scaling factor to the time (in milliseconds) between events to how
3274 * much to multiple/divide the current acceleration. When movement
3275 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3276 * FAST_MOVE_TIME it divides it.
3277 */
3278 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 float position;
3281 float absPosition;
3282 float acceleration = 1;
3283 long lastMoveTime = 0;
3284 int step;
3285 int dir;
3286 int nonAccelMovement;
3287
3288 void reset(int _step) {
3289 position = 0;
3290 acceleration = 1;
3291 lastMoveTime = 0;
3292 step = _step;
3293 dir = 0;
3294 }
3295
3296 /**
3297 * Add trackball movement into the state. If the direction of movement
3298 * has been reversed, the state is reset before adding the
3299 * movement (so that you don't have to compensate for any previously
3300 * collected movement before see the result of the movement in the
3301 * new direction).
3302 *
3303 * @return Returns the absolute value of the amount of movement
3304 * collected so far.
3305 */
3306 float collect(float off, long time, String axis) {
3307 long normTime;
3308 if (off > 0) {
3309 normTime = (long)(off * FAST_MOVE_TIME);
3310 if (dir < 0) {
3311 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3312 position = 0;
3313 step = 0;
3314 acceleration = 1;
3315 lastMoveTime = 0;
3316 }
3317 dir = 1;
3318 } else if (off < 0) {
3319 normTime = (long)((-off) * FAST_MOVE_TIME);
3320 if (dir > 0) {
3321 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3322 position = 0;
3323 step = 0;
3324 acceleration = 1;
3325 lastMoveTime = 0;
3326 }
3327 dir = -1;
3328 } else {
3329 normTime = 0;
3330 }
Romain Guy8506ab42009-06-11 17:35:47 -07003331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 // The number of milliseconds between each movement that is
3333 // considered "normal" and will not result in any acceleration
3334 // or deceleration, scaled by the offset we have here.
3335 if (normTime > 0) {
3336 long delta = time - lastMoveTime;
3337 lastMoveTime = time;
3338 float acc = acceleration;
3339 if (delta < normTime) {
3340 // The user is scrolling rapidly, so increase acceleration.
3341 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3342 if (scale > 1) acc *= scale;
3343 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3344 + off + " normTime=" + normTime + " delta=" + delta
3345 + " scale=" + scale + " acc=" + acc);
3346 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3347 } else {
3348 // The user is scrolling slowly, so decrease acceleration.
3349 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3350 if (scale > 1) acc /= scale;
3351 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3352 + off + " normTime=" + normTime + " delta=" + delta
3353 + " scale=" + scale + " acc=" + acc);
3354 acceleration = acc > 1 ? acc : 1;
3355 }
3356 }
3357 position += off;
3358 return (absPosition = Math.abs(position));
3359 }
3360
3361 /**
3362 * Generate the number of discrete movement events appropriate for
3363 * the currently collected trackball movement.
3364 *
3365 * @param precision The minimum movement required to generate the
3366 * first discrete movement.
3367 *
3368 * @return Returns the number of discrete movements, either positive
3369 * or negative, or 0 if there is not enough trackball movement yet
3370 * for a discrete movement.
3371 */
3372 int generate(float precision) {
3373 int movement = 0;
3374 nonAccelMovement = 0;
3375 do {
3376 final int dir = position >= 0 ? 1 : -1;
3377 switch (step) {
3378 // If we are going to execute the first step, then we want
3379 // to do this as soon as possible instead of waiting for
3380 // a full movement, in order to make things look responsive.
3381 case 0:
3382 if (absPosition < precision) {
3383 return movement;
3384 }
3385 movement += dir;
3386 nonAccelMovement += dir;
3387 step = 1;
3388 break;
3389 // If we have generated the first movement, then we need
3390 // to wait for the second complete trackball motion before
3391 // generating the second discrete movement.
3392 case 1:
3393 if (absPosition < 2) {
3394 return movement;
3395 }
3396 movement += dir;
3397 nonAccelMovement += dir;
3398 position += dir > 0 ? -2 : 2;
3399 absPosition = Math.abs(position);
3400 step = 2;
3401 break;
3402 // After the first two, we generate discrete movements
3403 // consistently with the trackball, applying an acceleration
3404 // if the trackball is moving quickly. This is a simple
3405 // acceleration on top of what we already compute based
3406 // on how quickly the wheel is being turned, to apply
3407 // a longer increasing acceleration to continuous movement
3408 // in one direction.
3409 default:
3410 if (absPosition < 1) {
3411 return movement;
3412 }
3413 movement += dir;
3414 position += dir >= 0 ? -1 : 1;
3415 absPosition = Math.abs(position);
3416 float acc = acceleration;
3417 acc *= 1.1f;
3418 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3419 break;
3420 }
3421 } while (true);
3422 }
3423 }
3424
3425 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3426 public CalledFromWrongThreadException(String msg) {
3427 super(msg);
3428 }
3429 }
3430
3431 private SurfaceHolder mHolder = new SurfaceHolder() {
3432 // we only need a SurfaceHolder for opengl. it would be nice
3433 // to implement everything else though, especially the callback
3434 // support (opengl doesn't make use of it right now, but eventually
3435 // will).
3436 public Surface getSurface() {
3437 return mSurface;
3438 }
3439
3440 public boolean isCreating() {
3441 return false;
3442 }
3443
3444 public void addCallback(Callback callback) {
3445 }
3446
3447 public void removeCallback(Callback callback) {
3448 }
3449
3450 public void setFixedSize(int width, int height) {
3451 }
3452
3453 public void setSizeFromLayout() {
3454 }
3455
3456 public void setFormat(int format) {
3457 }
3458
3459 public void setType(int type) {
3460 }
3461
3462 public void setKeepScreenOn(boolean screenOn) {
3463 }
3464
3465 public Canvas lockCanvas() {
3466 return null;
3467 }
3468
3469 public Canvas lockCanvas(Rect dirty) {
3470 return null;
3471 }
3472
3473 public void unlockCanvasAndPost(Canvas canvas) {
3474 }
3475 public Rect getSurfaceFrame() {
3476 return null;
3477 }
3478 };
3479
3480 static RunQueue getRunQueue() {
3481 RunQueue rq = sRunQueues.get();
3482 if (rq != null) {
3483 return rq;
3484 }
3485 rq = new RunQueue();
3486 sRunQueues.set(rq);
3487 return rq;
3488 }
Romain Guy8506ab42009-06-11 17:35:47 -07003489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 /**
3491 * @hide
3492 */
3493 static final class RunQueue {
3494 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3495
3496 void post(Runnable action) {
3497 postDelayed(action, 0);
3498 }
3499
3500 void postDelayed(Runnable action, long delayMillis) {
3501 HandlerAction handlerAction = new HandlerAction();
3502 handlerAction.action = action;
3503 handlerAction.delay = delayMillis;
3504
3505 synchronized (mActions) {
3506 mActions.add(handlerAction);
3507 }
3508 }
3509
3510 void removeCallbacks(Runnable action) {
3511 final HandlerAction handlerAction = new HandlerAction();
3512 handlerAction.action = action;
3513
3514 synchronized (mActions) {
3515 final ArrayList<HandlerAction> actions = mActions;
3516
3517 while (actions.remove(handlerAction)) {
3518 // Keep going
3519 }
3520 }
3521 }
3522
3523 void executeActions(Handler handler) {
3524 synchronized (mActions) {
3525 final ArrayList<HandlerAction> actions = mActions;
3526 final int count = actions.size();
3527
3528 for (int i = 0; i < count; i++) {
3529 final HandlerAction handlerAction = actions.get(i);
3530 handler.postDelayed(handlerAction.action, handlerAction.delay);
3531 }
3532
Romain Guy15df6702009-08-17 20:17:30 -07003533 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 }
3535 }
3536
3537 private static class HandlerAction {
3538 Runnable action;
3539 long delay;
3540
3541 @Override
3542 public boolean equals(Object o) {
3543 if (this == o) return true;
3544 if (o == null || getClass() != o.getClass()) return false;
3545
3546 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 return !(action != null ? !action.equals(that.action) : that.action != null);
3548
3549 }
3550
3551 @Override
3552 public int hashCode() {
3553 int result = action != null ? action.hashCode() : 0;
3554 result = 31 * result + (int) (delay ^ (delay >>> 32));
3555 return result;
3556 }
3557 }
3558 }
3559
3560 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3561
3562 // inform skia to just abandon its texture cache IDs
3563 // doesn't call glDeleteTextures
3564 private static native void nativeAbandonGlCaches();
3565}