blob: 1dc82e8dbdf46d51d3a173af5c62b4659b5d13f9 [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 Hackborn1e4b9f32010-06-23 14:10:57 -0700157 InputQueue.Callback mInputQueueCallback;
158 InputQueue mInputQueue;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700159
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) {
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700561 mInputQueueCallback =
562 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700563 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700564 if (mInputQueueCallback != null) {
565 mInputQueue = new InputQueue(mInputChannel);
566 mInputQueueCallback.onInputQueueCreated(mInputQueue);
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700567 } 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 Hackborn1e4b9f32010-06-23 14:10:57 -07001750 if (mInputQueueCallback != null) {
1751 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1752 mInputQueueCallback = null;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -07001753 } 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 }
Jeff Brown349703e2010-06-22 01:27:15 -07001765
1766 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
1767 // Dispose the input channel after removing the window so the Window Manager
1768 // doesn't interpret the input channel being closed as an abnormal termination.
1769 if (mInputChannel != null) {
1770 mInputChannel.dispose();
1771 mInputChannel = null;
1772 }
1773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
Romain Guy8506ab42009-06-11 17:35:47 -07001775
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001776 void updateConfiguration(Configuration config, boolean force) {
1777 if (DEBUG_CONFIGURATION) Log.v(TAG,
1778 "Applying new config to window "
1779 + mWindowAttributes.getTitle()
1780 + ": " + config);
1781 synchronized (sConfigCallbacks) {
1782 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1783 sConfigCallbacks.get(i).onConfigurationChanged(config);
1784 }
1785 }
1786 if (mView != null) {
1787 // At this point the resources have been updated to
1788 // have the most recent config, whatever that is. Use
1789 // the on in them which may be newer.
1790 if (mView != null) {
1791 config = mView.getResources().getConfiguration();
1792 }
1793 if (force || mLastConfiguration.diff(config) != 0) {
1794 mLastConfiguration.setTo(config);
1795 mView.dispatchConfigurationChanged(config);
1796 }
1797 }
1798 }
1799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 /**
1801 * Return true if child is an ancestor of parent, (or equal to the parent).
1802 */
1803 private static boolean isViewDescendantOf(View child, View parent) {
1804 if (child == parent) {
1805 return true;
1806 }
1807
1808 final ViewParent theParent = child.getParent();
1809 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1810 }
1811
Romain Guycdb86672010-03-18 18:54:50 -07001812 private static void forceLayout(View view) {
1813 view.forceLayout();
1814 if (view instanceof ViewGroup) {
1815 ViewGroup group = (ViewGroup) view;
1816 final int count = group.getChildCount();
1817 for (int i = 0; i < count; i++) {
1818 forceLayout(group.getChildAt(i));
1819 }
1820 }
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822
1823 public final static int DO_TRAVERSAL = 1000;
1824 public final static int DIE = 1001;
1825 public final static int RESIZED = 1002;
1826 public final static int RESIZED_REPORT = 1003;
1827 public final static int WINDOW_FOCUS_CHANGED = 1004;
1828 public final static int DISPATCH_KEY = 1005;
1829 public final static int DISPATCH_POINTER = 1006;
1830 public final static int DISPATCH_TRACKBALL = 1007;
1831 public final static int DISPATCH_APP_VISIBILITY = 1008;
1832 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1833 public final static int FINISHED_EVENT = 1010;
1834 public final static int DISPATCH_KEY_FROM_IME = 1011;
1835 public final static int FINISH_INPUT_CONNECTION = 1012;
1836 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001837 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838
1839 @Override
1840 public void handleMessage(Message msg) {
1841 switch (msg.what) {
1842 case View.AttachInfo.INVALIDATE_MSG:
1843 ((View) msg.obj).invalidate();
1844 break;
1845 case View.AttachInfo.INVALIDATE_RECT_MSG:
1846 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1847 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1848 info.release();
1849 break;
1850 case DO_TRAVERSAL:
1851 if (mProfile) {
1852 Debug.startMethodTracing("ViewRoot");
1853 }
1854
1855 performTraversals();
1856
1857 if (mProfile) {
1858 Debug.stopMethodTracing();
1859 mProfile = false;
1860 }
1861 break;
1862 case FINISHED_EVENT:
1863 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1864 break;
1865 case DISPATCH_KEY:
1866 if (LOCAL_LOGV) Log.v(
1867 "ViewRoot", "Dispatching key "
1868 + msg.obj + " to " + mView);
1869 deliverKeyEvent((KeyEvent)msg.obj, true);
1870 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001871 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001873 boolean callWhenDone = msg.arg1 != 0;
1874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001876 long timeBeforeGettingEvents;
1877 if (MEASURE_LATENCY) {
1878 timeBeforeGettingEvents = System.nanoTime();
1879 }
Michael Chan53071d62009-05-13 17:29:48 -07001880
Jeff Brown46b9ac02010-04-22 18:58:52 -07001881 event = getPendingPointerMotionEvent();
Michael Chan53071d62009-05-13 17:29:48 -07001882
Jeff Brown46b9ac02010-04-22 18:58:52 -07001883 if (MEASURE_LATENCY && event != null) {
1884 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1885 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001887 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001889 if (event != null && mTranslator != null) {
1890 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 try {
1893 boolean handled;
1894 if (mView != null && mAdded && event != null) {
1895
1896 // enter touch mode on the down
1897 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1898 if (isDown) {
1899 ensureTouchMode(true);
1900 }
1901 if(Config.LOGV) {
1902 captureMotionLog("captureDispatchPointer", event);
1903 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001904 if (mCurScrollY != 0) {
1905 event.offsetLocation(0, mCurScrollY);
1906 }
Michael Chan53071d62009-05-13 17:29:48 -07001907 if (MEASURE_LATENCY) {
1908 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001911 if (MEASURE_LATENCY) {
1912 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 if (!handled && isDown) {
1915 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1916
1917 final int edgeFlags = event.getEdgeFlags();
1918 int direction = View.FOCUS_UP;
1919 int x = (int)event.getX();
1920 int y = (int)event.getY();
1921 final int[] deltas = new int[2];
1922
1923 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1924 direction = View.FOCUS_DOWN;
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_BOTTOM) != 0) {
1933 direction = View.FOCUS_UP;
1934 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1935 deltas[0] = edgeSlop;
1936 x += edgeSlop;
1937 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1938 deltas[0] = -edgeSlop;
1939 x -= edgeSlop;
1940 }
1941 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1942 direction = View.FOCUS_RIGHT;
1943 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1944 direction = View.FOCUS_LEFT;
1945 }
1946
1947 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1948 View nearest = FocusFinder.getInstance().findNearestTouchable(
1949 ((ViewGroup) mView), x, y, direction, deltas);
1950 if (nearest != null) {
1951 event.offsetLocation(deltas[0], deltas[1]);
1952 event.setEdgeFlags(0);
1953 mView.dispatchTouchEvent(event);
1954 }
1955 }
1956 }
1957 }
1958 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001959 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001960 finishMotionEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001962 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1964 // Let the exception fall through -- the looper will catch
1965 // it and take care of the bad app for us.
1966 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001967 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001969 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 break;
1971 case DISPATCH_APP_VISIBILITY:
1972 handleAppVisibility(msg.arg1 != 0);
1973 break;
1974 case DISPATCH_GET_NEW_SURFACE:
1975 handleGetNewSurface();
1976 break;
1977 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001978 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001981 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001982 && mPendingVisibleInsets.equals(ri.visibleInsets)
1983 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 break;
1985 }
1986 // fall through...
1987 case RESIZED_REPORT:
1988 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001989 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1990 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001991 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 mWinFrame.left = 0;
1994 mWinFrame.right = msg.arg1;
1995 mWinFrame.top = 0;
1996 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001997 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1998 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 if (msg.what == RESIZED_REPORT) {
2000 mReportNextDraw = true;
2001 }
Romain Guycdb86672010-03-18 18:54:50 -07002002
2003 if (mView != null) {
2004 forceLayout(mView);
2005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 requestLayout();
2007 }
2008 break;
2009 case WINDOW_FOCUS_CHANGED: {
2010 if (mAdded) {
2011 boolean hasWindowFocus = msg.arg1 != 0;
2012 mAttachInfo.mHasWindowFocus = hasWindowFocus;
2013 if (hasWindowFocus) {
2014 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07002015 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016
2017 if (mGlWanted) {
2018 checkEglErrors();
2019 // we lost the gl context, so recreate it.
2020 if (mGlWanted && !mUseGL) {
2021 initializeGL();
2022 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002023 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002024 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002025 (int) (mWidth * appScale + 0.5f),
2026 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028 }
2029 }
2030 }
Romain Guy8506ab42009-06-11 17:35:47 -07002031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 mLastWasImTarget = WindowManager.LayoutParams
2033 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 InputMethodManager imm = InputMethodManager.peekInstance();
2036 if (mView != null) {
2037 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2038 imm.startGettingWindowFocus(mView);
2039 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002040 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 mView.dispatchWindowFocusChanged(hasWindowFocus);
2042 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 // Note: must be done after the focus change callbacks,
2045 // so all of the view state is set up correctly.
2046 if (hasWindowFocus) {
2047 if (imm != null && mLastWasImTarget) {
2048 imm.onWindowFocus(mView, mView.findFocus(),
2049 mWindowAttributes.softInputMode,
2050 !mHasHadWindowFocus, mWindowAttributes.flags);
2051 }
2052 // Clear the forward bit. We can just do this directly, since
2053 // the window manager doesn't care about it.
2054 mWindowAttributes.softInputMode &=
2055 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2056 ((WindowManager.LayoutParams)mView.getLayoutParams())
2057 .softInputMode &=
2058 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2059 mHasHadWindowFocus = true;
2060 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002061
2062 if (hasWindowFocus && mView != null) {
2063 sendAccessibilityEvents();
2064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 }
2066 } break;
2067 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002068 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002070 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 if (LOCAL_LOGV) Log.v(
2072 "ViewRoot", "Dispatching key "
2073 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002074 KeyEvent event = (KeyEvent)msg.obj;
2075 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2076 // The IME is trying to say this event is from the
2077 // system! Bad bad bad!
2078 event = KeyEvent.changeFlags(event,
2079 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
2080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002082 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 case FINISH_INPUT_CONNECTION: {
2084 InputMethodManager imm = InputMethodManager.peekInstance();
2085 if (imm != null) {
2086 imm.reportFinishInputConnection((InputConnection)msg.obj);
2087 }
2088 } break;
2089 case CHECK_FOCUS: {
2090 InputMethodManager imm = InputMethodManager.peekInstance();
2091 if (imm != null) {
2092 imm.checkFocus();
2093 }
2094 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002095 case CLOSE_SYSTEM_DIALOGS: {
2096 if (mView != null) {
2097 mView.onCloseSystemDialogs((String)msg.obj);
2098 }
2099 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 }
2101 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002102
2103 private void finishKeyEvent(KeyEvent event) {
2104 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2105 if (mFinishedCallback != null) {
2106 mFinishedCallback.run();
2107 mFinishedCallback = null;
2108 }
2109 } else {
2110 try {
2111 sWindowSession.finishKey(mWindow);
2112 } catch (RemoteException e) {
2113 }
2114 }
2115 }
2116
2117 private void finishMotionEvent() {
2118 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2119 throw new IllegalStateException("Should not be reachable with native input dispatch.");
2120 }
2121
2122 try {
2123 sWindowSession.finishKey(mWindow);
2124 } catch (RemoteException e) {
2125 }
2126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127
Jeff Brown46b9ac02010-04-22 18:58:52 -07002128 private void recycleMotionEvent(MotionEvent event) {
2129 if (event != null) {
2130 event.recycle();
2131 }
2132 }
2133
2134 private MotionEvent getPendingPointerMotionEvent() {
2135 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2136 throw new IllegalStateException("Should not be reachable with native input dispatch.");
2137 }
2138
2139 try {
2140 return sWindowSession.getPendingPointerMove(mWindow);
2141 } catch (RemoteException e) {
2142 return null;
2143 }
2144 }
2145
2146 private MotionEvent getPendingTrackballMotionEvent() {
2147 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
2148 throw new IllegalStateException("Should not be reachable with native input dispatch.");
2149 }
2150
2151 try {
2152 return sWindowSession.getPendingTrackballMove(mWindow);
2153 } catch (RemoteException e) {
2154 return null;
2155 }
2156 }
2157
2158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 /**
2160 * Something in the current window tells us we need to change the touch mode. For
2161 * example, we are not in touch mode, and the user touches the screen.
2162 *
2163 * If the touch mode has changed, tell the window manager, and handle it locally.
2164 *
2165 * @param inTouchMode Whether we want to be in touch mode.
2166 * @return True if the touch mode changed and focus changed was changed as a result
2167 */
2168 boolean ensureTouchMode(boolean inTouchMode) {
2169 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2170 + "touch mode is " + mAttachInfo.mInTouchMode);
2171 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2172
2173 // tell the window manager
2174 try {
2175 sWindowSession.setInTouchMode(inTouchMode);
2176 } catch (RemoteException e) {
2177 throw new RuntimeException(e);
2178 }
2179
2180 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002181 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 }
2183
2184 /**
2185 * Ensure that the touch mode for this window is set, and if it is changing,
2186 * take the appropriate action.
2187 * @param inTouchMode Whether we want to be in touch mode.
2188 * @return True if the touch mode changed and focus changed was changed as a result
2189 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002190 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2192 + "touch mode is " + mAttachInfo.mInTouchMode);
2193
2194 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2195
2196 mAttachInfo.mInTouchMode = inTouchMode;
2197 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2198
Romain Guy2d4cff62010-04-09 15:39:00 -07002199 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201
2202 private boolean enterTouchMode() {
2203 if (mView != null) {
2204 if (mView.hasFocus()) {
2205 // note: not relying on mFocusedView here because this could
2206 // be when the window is first being added, and mFocused isn't
2207 // set yet.
2208 final View focused = mView.findFocus();
2209 if (focused != null && !focused.isFocusableInTouchMode()) {
2210
2211 final ViewGroup ancestorToTakeFocus =
2212 findAncestorToTakeFocusInTouchMode(focused);
2213 if (ancestorToTakeFocus != null) {
2214 // there is an ancestor that wants focus after its descendants that
2215 // is focusable in touch mode.. give it focus
2216 return ancestorToTakeFocus.requestFocus();
2217 } else {
2218 // nothing appropriate to have focus in touch mode, clear it out
2219 mView.unFocus();
2220 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2221 mFocusedView = null;
2222 return true;
2223 }
2224 }
2225 }
2226 }
2227 return false;
2228 }
2229
2230
2231 /**
2232 * Find an ancestor of focused that wants focus after its descendants and is
2233 * focusable in touch mode.
2234 * @param focused The currently focused view.
2235 * @return An appropriate view, or null if no such view exists.
2236 */
2237 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2238 ViewParent parent = focused.getParent();
2239 while (parent instanceof ViewGroup) {
2240 final ViewGroup vgParent = (ViewGroup) parent;
2241 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2242 && vgParent.isFocusableInTouchMode()) {
2243 return vgParent;
2244 }
2245 if (vgParent.isRootNamespace()) {
2246 return null;
2247 } else {
2248 parent = vgParent.getParent();
2249 }
2250 }
2251 return null;
2252 }
2253
2254 private boolean leaveTouchMode() {
2255 if (mView != null) {
2256 if (mView.hasFocus()) {
2257 // i learned the hard way to not trust mFocusedView :)
2258 mFocusedView = mView.findFocus();
2259 if (!(mFocusedView instanceof ViewGroup)) {
2260 // some view has focus, let it keep it
2261 return false;
2262 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2263 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2264 // some view group has focus, and doesn't prefer its children
2265 // over itself for focus, so let them keep it.
2266 return false;
2267 }
2268 }
2269
2270 // find the best view to give focus to in this brave new non-touch-mode
2271 // world
2272 final View focused = focusSearch(null, View.FOCUS_DOWN);
2273 if (focused != null) {
2274 return focused.requestFocus(View.FOCUS_DOWN);
2275 }
2276 }
2277 return false;
2278 }
2279
2280
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002281 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002283 event = getPendingTrackballMotionEvent();
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002284 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
2286
2287 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2288
2289 boolean handled = false;
2290 try {
2291 if (event == null) {
2292 handled = true;
2293 } else if (mView != null && mAdded) {
2294 handled = mView.dispatchTrackballEvent(event);
2295 if (!handled) {
2296 // we could do something here, like changing the focus
2297 // or something?
2298 }
2299 }
2300 } finally {
2301 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002302 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002303 finishMotionEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002305 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 // If we reach this, we delivered a trackball event to mView and
2307 // mView consumed it. Because we will not translate the trackball
2308 // event into a key event, touch mode will not exit, so we exit
2309 // touch mode here.
2310 ensureTouchMode(false);
2311 //noinspection ReturnInsideFinallyBlock
2312 return;
2313 }
2314 // Let the exception fall through -- the looper will catch
2315 // it and take care of the bad app for us.
2316 }
2317
2318 final TrackballAxis x = mTrackballAxisX;
2319 final TrackballAxis y = mTrackballAxisY;
2320
2321 long curTime = SystemClock.uptimeMillis();
2322 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2323 // It has been too long since the last movement,
2324 // so restart at the beginning.
2325 x.reset(0);
2326 y.reset(0);
2327 mLastTrackballTime = curTime;
2328 }
2329
2330 try {
2331 final int action = event.getAction();
2332 final int metastate = event.getMetaState();
2333 switch (action) {
2334 case MotionEvent.ACTION_DOWN:
2335 x.reset(2);
2336 y.reset(2);
2337 deliverKeyEvent(new KeyEvent(curTime, curTime,
2338 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2339 0, metastate), false);
2340 break;
2341 case MotionEvent.ACTION_UP:
2342 x.reset(2);
2343 y.reset(2);
2344 deliverKeyEvent(new KeyEvent(curTime, curTime,
2345 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2346 0, metastate), false);
2347 break;
2348 }
2349
2350 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2351 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2352 + " move=" + event.getX()
2353 + " / Y=" + y.position + " step="
2354 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2355 + " move=" + event.getY());
2356 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2357 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2358
2359 // Generate DPAD events based on the trackball movement.
2360 // We pick the axis that has moved the most as the direction of
2361 // the DPAD. When we generate DPAD events for one axis, then the
2362 // other axis is reset -- we don't want to perform DPAD jumps due
2363 // to slight movements in the trackball when making major movements
2364 // along the other axis.
2365 int keycode = 0;
2366 int movement = 0;
2367 float accel = 1;
2368 if (xOff > yOff) {
2369 movement = x.generate((2/event.getXPrecision()));
2370 if (movement != 0) {
2371 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2372 : KeyEvent.KEYCODE_DPAD_LEFT;
2373 accel = x.acceleration;
2374 y.reset(2);
2375 }
2376 } else if (yOff > 0) {
2377 movement = y.generate((2/event.getYPrecision()));
2378 if (movement != 0) {
2379 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2380 : KeyEvent.KEYCODE_DPAD_UP;
2381 accel = y.acceleration;
2382 x.reset(2);
2383 }
2384 }
2385
2386 if (keycode != 0) {
2387 if (movement < 0) movement = -movement;
2388 int accelMovement = (int)(movement * accel);
2389 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2390 + " accelMovement=" + accelMovement
2391 + " accel=" + accel);
2392 if (accelMovement > movement) {
2393 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2394 + keycode);
2395 movement--;
2396 deliverKeyEvent(new KeyEvent(curTime, curTime,
2397 KeyEvent.ACTION_MULTIPLE, keycode,
2398 accelMovement-movement, metastate), false);
2399 }
2400 while (movement > 0) {
2401 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2402 + keycode);
2403 movement--;
2404 curTime = SystemClock.uptimeMillis();
2405 deliverKeyEvent(new KeyEvent(curTime, curTime,
2406 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2407 deliverKeyEvent(new KeyEvent(curTime, curTime,
2408 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2409 }
2410 mLastTrackballTime = curTime;
2411 }
2412 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002413 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002414 finishMotionEvent();
2415 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 }
2417 // Let the exception fall through -- the looper will catch
2418 // it and take care of the bad app for us.
2419 }
2420 }
2421
2422 /**
2423 * @param keyCode The key code
2424 * @return True if the key is directional.
2425 */
2426 static boolean isDirectional(int keyCode) {
2427 switch (keyCode) {
2428 case KeyEvent.KEYCODE_DPAD_LEFT:
2429 case KeyEvent.KEYCODE_DPAD_RIGHT:
2430 case KeyEvent.KEYCODE_DPAD_UP:
2431 case KeyEvent.KEYCODE_DPAD_DOWN:
2432 return true;
2433 }
2434 return false;
2435 }
2436
2437 /**
2438 * Returns true if this key is a keyboard key.
2439 * @param keyEvent The key event.
2440 * @return whether this key is a keyboard key.
2441 */
2442 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2443 final int convertedKey = keyEvent.getUnicodeChar();
2444 return convertedKey > 0;
2445 }
2446
2447
2448
2449 /**
2450 * See if the key event means we should leave touch mode (and leave touch
2451 * mode if so).
2452 * @param event The key event.
2453 * @return Whether this key event should be consumed (meaning the act of
2454 * leaving touch mode alone is considered the event).
2455 */
2456 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002457 final int action = event.getAction();
2458 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 return false;
2460 }
2461 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2462 return false;
2463 }
2464
2465 // only relevant if we are in touch mode
2466 if (!mAttachInfo.mInTouchMode) {
2467 return false;
2468 }
2469
2470 // if something like an edit text has focus and the user is typing,
2471 // leave touch mode
2472 //
2473 // note: the condition of not being a keyboard key is kind of a hacky
2474 // approximation of whether we think the focused view will want the
2475 // key; if we knew for sure whether the focused view would consume
2476 // the event, that would be better.
2477 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2478 mFocusedView = mView.findFocus();
2479 if ((mFocusedView instanceof ViewGroup)
2480 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2481 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2482 // something has focus, but is holding it weakly as a container
2483 return false;
2484 }
2485 if (ensureTouchMode(false)) {
2486 throw new IllegalStateException("should not have changed focus "
2487 + "when leaving touch mode while a view has focus.");
2488 }
2489 return false;
2490 }
2491
2492 if (isDirectional(event.getKeyCode())) {
2493 // no view has focus, so we leave touch mode (and find something
2494 // to give focus to). the event is consumed if we were able to
2495 // find something to give focus to.
2496 return ensureTouchMode(false);
2497 }
2498 return false;
2499 }
2500
2501 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002502 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 */
2504 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002505 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 if (ev == null ||
2507 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2508 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 }
Romain Guy8506ab42009-06-11 17:35:47 -07002510
2511 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 sb.append(ev.getDownTime()).append(',');
2513 sb.append(ev.getEventTime()).append(',');
2514 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002515 sb.append(ev.getX()).append(',');
2516 sb.append(ev.getY()).append(',');
2517 sb.append(ev.getPressure()).append(',');
2518 sb.append(ev.getSize()).append(',');
2519 sb.append(ev.getMetaState()).append(',');
2520 sb.append(ev.getXPrecision()).append(',');
2521 sb.append(ev.getYPrecision()).append(',');
2522 sb.append(ev.getDeviceId()).append(',');
2523 sb.append(ev.getEdgeFlags());
2524 Log.d(TAG, sb.toString());
2525 }
2526 /**
2527 * log motion events
2528 */
2529 private static void captureKeyLog(String subTag, KeyEvent ev) {
2530 //check dynamic switch
2531 if (ev == null ||
2532 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2533 return;
2534 }
2535 StringBuilder sb = new StringBuilder(subTag + ": ");
2536 sb.append(ev.getDownTime()).append(',');
2537 sb.append(ev.getEventTime()).append(',');
2538 sb.append(ev.getAction()).append(',');
2539 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 sb.append(ev.getRepeatCount()).append(',');
2541 sb.append(ev.getMetaState()).append(',');
2542 sb.append(ev.getDeviceId()).append(',');
2543 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002544 Log.d(TAG, sb.toString());
2545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546
2547 int enqueuePendingEvent(Object event, boolean sendDone) {
2548 int seq = mPendingEventSeq+1;
2549 if (seq < 0) seq = 0;
2550 mPendingEventSeq = seq;
2551 mPendingEvents.put(seq, event);
2552 return sendDone ? seq : -seq;
2553 }
2554
2555 Object retrievePendingEvent(int seq) {
2556 if (seq < 0) seq = -seq;
2557 Object event = mPendingEvents.get(seq);
2558 if (event != null) {
2559 mPendingEvents.remove(seq);
2560 }
2561 return event;
2562 }
Romain Guy8506ab42009-06-11 17:35:47 -07002563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2565 // If mView is null, we just consume the key event because it doesn't
2566 // make sense to do anything else with it.
2567 boolean handled = mView != null
2568 ? mView.dispatchKeyEventPreIme(event) : true;
2569 if (handled) {
2570 if (sendDone) {
2571 if (LOCAL_LOGV) Log.v(
2572 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002573 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 return;
2576 }
2577 // If it is possible for this window to interact with the input
2578 // method window, then we want to first dispatch our key events
2579 // to the input method.
2580 if (mLastWasImTarget) {
2581 InputMethodManager imm = InputMethodManager.peekInstance();
2582 if (imm != null && mView != null) {
2583 int seq = enqueuePendingEvent(event, sendDone);
2584 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2585 + seq + " event=" + event);
2586 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2587 mInputMethodCallback);
2588 return;
2589 }
2590 }
2591 deliverKeyEventToViewHierarchy(event, sendDone);
2592 }
2593
2594 void handleFinishedEvent(int seq, boolean handled) {
2595 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2596 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2597 + " handled=" + handled + " event=" + event);
2598 if (event != null) {
2599 final boolean sendDone = seq >= 0;
2600 if (!handled) {
2601 deliverKeyEventToViewHierarchy(event, sendDone);
2602 return;
2603 } else if (sendDone) {
2604 if (LOCAL_LOGV) Log.v(
2605 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002606 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 } else {
2608 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2609 + " handled=" + handled + " ev=" + event
2610 + ") neither delivering nor finishing key");
2611 }
2612 }
2613 }
Romain Guy8506ab42009-06-11 17:35:47 -07002614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2616 try {
2617 if (mView != null && mAdded) {
2618 final int action = event.getAction();
2619 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2620
2621 if (checkForLeavingTouchModeAndConsume(event)) {
2622 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002623 }
2624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 if (Config.LOGV) {
2626 captureKeyLog("captureDispatchKeyEvent", event);
2627 }
2628 boolean keyHandled = mView.dispatchKeyEvent(event);
2629
2630 if (!keyHandled && isDown) {
2631 int direction = 0;
2632 switch (event.getKeyCode()) {
2633 case KeyEvent.KEYCODE_DPAD_LEFT:
2634 direction = View.FOCUS_LEFT;
2635 break;
2636 case KeyEvent.KEYCODE_DPAD_RIGHT:
2637 direction = View.FOCUS_RIGHT;
2638 break;
2639 case KeyEvent.KEYCODE_DPAD_UP:
2640 direction = View.FOCUS_UP;
2641 break;
2642 case KeyEvent.KEYCODE_DPAD_DOWN:
2643 direction = View.FOCUS_DOWN;
2644 break;
2645 }
2646
2647 if (direction != 0) {
2648
2649 View focused = mView != null ? mView.findFocus() : null;
2650 if (focused != null) {
2651 View v = focused.focusSearch(direction);
2652 boolean focusPassed = false;
2653 if (v != null && v != focused) {
2654 // do the math the get the interesting rect
2655 // of previous focused into the coord system of
2656 // newly focused view
2657 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002658 if (mView instanceof ViewGroup) {
2659 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2660 focused, mTempRect);
2661 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2662 v, mTempRect);
2663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 focusPassed = v.requestFocus(direction, mTempRect);
2665 }
2666
2667 if (!focusPassed) {
2668 mView.dispatchUnhandledMove(focused, direction);
2669 } else {
2670 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2671 }
2672 }
2673 }
2674 }
2675 }
2676
2677 } finally {
2678 if (sendDone) {
2679 if (LOCAL_LOGV) Log.v(
2680 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002681 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
2683 // Let the exception fall through -- the looper will catch
2684 // it and take care of the bad app for us.
2685 }
2686 }
2687
2688 private AudioManager getAudioManager() {
2689 if (mView == null) {
2690 throw new IllegalStateException("getAudioManager called when there is no mView");
2691 }
2692 if (mAudioManager == null) {
2693 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2694 }
2695 return mAudioManager;
2696 }
2697
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002698 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2699 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002700
2701 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002702 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002703 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002704 restore = true;
2705 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002706 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002707 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002708 if (params != null) {
2709 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002710 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002711 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002712 int relayoutResult = sWindowSession.relayout(
2713 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002714 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2715 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002716 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002717 mPendingContentInsets, mPendingVisibleInsets,
2718 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002719 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002720 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002721 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002722
2723 if (mTranslator != null) {
2724 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2725 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2726 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002727 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002728 return relayoutResult;
2729 }
Romain Guy8506ab42009-06-11 17:35:47 -07002730
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002731 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 * {@inheritDoc}
2733 */
2734 public void playSoundEffect(int effectId) {
2735 checkThread();
2736
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002737 try {
2738 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002740 switch (effectId) {
2741 case SoundEffectConstants.CLICK:
2742 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2743 return;
2744 case SoundEffectConstants.NAVIGATION_DOWN:
2745 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2746 return;
2747 case SoundEffectConstants.NAVIGATION_LEFT:
2748 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2749 return;
2750 case SoundEffectConstants.NAVIGATION_RIGHT:
2751 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2752 return;
2753 case SoundEffectConstants.NAVIGATION_UP:
2754 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2755 return;
2756 default:
2757 throw new IllegalArgumentException("unknown effect id " + effectId +
2758 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2759 }
2760 } catch (IllegalStateException e) {
2761 // Exception thrown by getAudioManager() when mView is null
2762 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2763 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 }
2765 }
2766
2767 /**
2768 * {@inheritDoc}
2769 */
2770 public boolean performHapticFeedback(int effectId, boolean always) {
2771 try {
2772 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2773 } catch (RemoteException e) {
2774 return false;
2775 }
2776 }
2777
2778 /**
2779 * {@inheritDoc}
2780 */
2781 public View focusSearch(View focused, int direction) {
2782 checkThread();
2783 if (!(mView instanceof ViewGroup)) {
2784 return null;
2785 }
2786 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2787 }
2788
2789 public void debug() {
2790 mView.debug();
2791 }
2792
2793 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002794 if (immediate) {
2795 doDie();
2796 } else {
2797 sendEmptyMessage(DIE);
2798 }
2799 }
2800
2801 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 checkThread();
2803 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2804 synchronized (this) {
2805 if (mAdded && !mFirst) {
2806 int viewVisibility = mView.getVisibility();
2807 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2808 if (mWindowAttributesChanged || viewVisibilityChanged) {
2809 // If layout params have been changed, first give them
2810 // to the window manager to make sure it has the correct
2811 // animation info.
2812 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002813 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2814 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 sWindowSession.finishDrawing(mWindow);
2816 }
2817 } catch (RemoteException e) {
2818 }
2819 }
2820
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002821 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 }
2823 if (mAdded) {
2824 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002825 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827 }
2828 }
2829
2830 public void dispatchFinishedEvent(int seq, boolean handled) {
2831 Message msg = obtainMessage(FINISHED_EVENT);
2832 msg.arg1 = seq;
2833 msg.arg2 = handled ? 1 : 0;
2834 sendMessage(msg);
2835 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002838 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2840 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2841 + " visibleInsets=" + visibleInsets.toShortString()
2842 + " reportDraw=" + reportDraw);
2843 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002844 if (mTranslator != null) {
2845 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2846 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2847 w *= mTranslator.applicationInvertedScale;
2848 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002849 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002850 msg.arg1 = w;
2851 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002852 ResizedInfo ri = new ResizedInfo();
2853 ri.coveredInsets = new Rect(coveredInsets);
2854 ri.visibleInsets = new Rect(visibleInsets);
2855 ri.newConfig = newConfig;
2856 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 sendMessage(msg);
2858 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002859
2860 private Runnable mFinishedCallback;
2861
2862 private final InputHandler mInputHandler = new InputHandler() {
2863 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2864 mFinishedCallback = finishedCallback;
2865
2866 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2867 //noinspection ConstantConditions
2868 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2869 if (Config.LOGD) Log.d("keydisp",
2870 "===================================================");
2871 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2872 debug();
2873
2874 if (Config.LOGD) Log.d("keydisp",
2875 "===================================================");
2876 }
2877 }
2878
2879 Message msg = obtainMessage(DISPATCH_KEY);
2880 msg.obj = event;
2881
2882 if (LOCAL_LOGV) Log.v(
2883 "ViewRoot", "sending key " + event + " to " + mView);
2884
2885 sendMessageAtTime(msg, event.getEventTime());
2886 }
2887
2888 public void handleTouch(MotionEvent event, Runnable finishedCallback) {
2889 finishedCallback.run();
2890
2891 Message msg = obtainMessage(DISPATCH_POINTER);
2892 msg.obj = event;
2893 msg.arg1 = 0;
2894 sendMessageAtTime(msg, event.getEventTime());
2895 }
2896
2897 public void handleTrackball(MotionEvent event, Runnable finishedCallback) {
2898 finishedCallback.run();
2899
2900 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2901 msg.obj = event;
2902 msg.arg1 = 0;
2903 sendMessageAtTime(msg, event.getEventTime());
2904 }
2905 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906
2907 public void dispatchKey(KeyEvent event) {
2908 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2909 //noinspection ConstantConditions
2910 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2911 if (Config.LOGD) Log.d("keydisp",
2912 "===================================================");
2913 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2914 debug();
2915
2916 if (Config.LOGD) Log.d("keydisp",
2917 "===================================================");
2918 }
2919 }
2920
2921 Message msg = obtainMessage(DISPATCH_KEY);
2922 msg.obj = event;
2923
2924 if (LOCAL_LOGV) Log.v(
2925 "ViewRoot", "sending key " + event + " to " + mView);
2926
2927 sendMessageAtTime(msg, event.getEventTime());
2928 }
2929
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002930 public void dispatchPointer(MotionEvent event, long eventTime,
2931 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 Message msg = obtainMessage(DISPATCH_POINTER);
2933 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002934 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 sendMessageAtTime(msg, eventTime);
2936 }
2937
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002938 public void dispatchTrackball(MotionEvent event, long eventTime,
2939 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2941 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002942 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 sendMessageAtTime(msg, eventTime);
2944 }
2945
2946 public void dispatchAppVisibility(boolean visible) {
2947 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2948 msg.arg1 = visible ? 1 : 0;
2949 sendMessage(msg);
2950 }
2951
2952 public void dispatchGetNewSurface() {
2953 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2954 sendMessage(msg);
2955 }
2956
2957 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2958 Message msg = Message.obtain();
2959 msg.what = WINDOW_FOCUS_CHANGED;
2960 msg.arg1 = hasFocus ? 1 : 0;
2961 msg.arg2 = inTouchMode ? 1 : 0;
2962 sendMessage(msg);
2963 }
2964
Dianne Hackbornffa42482009-09-23 22:20:11 -07002965 public void dispatchCloseSystemDialogs(String reason) {
2966 Message msg = Message.obtain();
2967 msg.what = CLOSE_SYSTEM_DIALOGS;
2968 msg.obj = reason;
2969 sendMessage(msg);
2970 }
2971
svetoslavganov75986cf2009-05-14 22:28:01 -07002972 /**
2973 * The window is getting focus so if there is anything focused/selected
2974 * send an {@link AccessibilityEvent} to announce that.
2975 */
2976 private void sendAccessibilityEvents() {
2977 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2978 return;
2979 }
2980 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2981 View focusedView = mView.findFocus();
2982 if (focusedView != null && focusedView != mView) {
2983 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2984 }
2985 }
2986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 public boolean showContextMenuForChild(View originalView) {
2988 return false;
2989 }
2990
2991 public void createContextMenu(ContextMenu menu) {
2992 }
2993
2994 public void childDrawableStateChanged(View child) {
2995 }
2996
2997 protected Rect getWindowFrame() {
2998 return mWinFrame;
2999 }
3000
3001 void checkThread() {
3002 if (mThread != Thread.currentThread()) {
3003 throw new CalledFromWrongThreadException(
3004 "Only the original thread that created a view hierarchy can touch its views.");
3005 }
3006 }
3007
3008 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3009 // ViewRoot never intercepts touch event, so this can be a no-op
3010 }
3011
3012 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3013 boolean immediate) {
3014 return scrollToRectOrFocus(rectangle, immediate);
3015 }
Romain Guy8506ab42009-06-11 17:35:47 -07003016
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003017 class TakenSurfaceHolder extends BaseSurfaceHolder {
3018 @Override
3019 public boolean onAllowLockCanvas() {
3020 return mDrawingAllowed;
3021 }
3022
3023 @Override
3024 public void onRelayoutContainer() {
3025 // Not currently interesting -- from changing between fixed and layout size.
3026 }
3027
3028 public void setFormat(int format) {
3029 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3030 }
3031
3032 public void setType(int type) {
3033 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3034 }
3035
3036 @Override
3037 public void onUpdateSurface() {
3038 // We take care of format and type changes on our own.
3039 throw new IllegalStateException("Shouldn't be here");
3040 }
3041
3042 public boolean isCreating() {
3043 return mIsCreating;
3044 }
3045
3046 @Override
3047 public void setFixedSize(int width, int height) {
3048 throw new UnsupportedOperationException(
3049 "Currently only support sizing from layout");
3050 }
3051
3052 public void setKeepScreenOn(boolean screenOn) {
3053 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3054 }
3055 }
3056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 static class InputMethodCallback extends IInputMethodCallback.Stub {
3058 private WeakReference<ViewRoot> mViewRoot;
3059
3060 public InputMethodCallback(ViewRoot viewRoot) {
3061 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3062 }
Romain Guy8506ab42009-06-11 17:35:47 -07003063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 public void finishedEvent(int seq, boolean handled) {
3065 final ViewRoot viewRoot = mViewRoot.get();
3066 if (viewRoot != null) {
3067 viewRoot.dispatchFinishedEvent(seq, handled);
3068 }
3069 }
3070
3071 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3072 // Stub -- not for use in the client.
3073 }
3074 }
Romain Guy8506ab42009-06-11 17:35:47 -07003075
Jeff Brown46b9ac02010-04-22 18:58:52 -07003076 class EventCompletion extends Handler {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003077 final IWindow mWindow;
3078 final KeyEvent mKeyEvent;
3079 final boolean mIsPointer;
3080 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07003081
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003082 EventCompletion(Looper looper, IWindow window, KeyEvent key,
3083 boolean isPointer, MotionEvent motion) {
3084 super(looper);
3085 mWindow = window;
3086 mKeyEvent = key;
3087 mIsPointer = isPointer;
3088 mMotionEvent = motion;
3089 sendEmptyMessage(0);
3090 }
Romain Guy8506ab42009-06-11 17:35:47 -07003091
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003092 @Override
3093 public void handleMessage(Message msg) {
3094 if (mKeyEvent != null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003095 finishKeyEvent(mKeyEvent);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003096 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003097 boolean didFinish;
3098 MotionEvent event = mMotionEvent;
3099 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003100 event = getPendingPointerMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003101 didFinish = true;
3102 } else {
3103 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
3104 }
3105 if (!didFinish) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003106 finishMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003107 }
3108 } else {
3109 MotionEvent event = mMotionEvent;
3110 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003111 event = getPendingTrackballMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003112 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003113 finishMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003114 }
3115 }
3116 }
3117 }
Romain Guy8506ab42009-06-11 17:35:47 -07003118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003120 private final WeakReference<ViewRoot> mViewRoot;
3121 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003123 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003125 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
3127
3128 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003129 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 final ViewRoot viewRoot = mViewRoot.get();
3131 if (viewRoot != null) {
3132 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003133 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 }
3135 }
3136
3137 public void dispatchKey(KeyEvent event) {
3138 final ViewRoot viewRoot = mViewRoot.get();
3139 if (viewRoot != null) {
3140 viewRoot.dispatchKey(event);
3141 } else {
3142 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
Jeff Brown46b9ac02010-04-22 18:58:52 -07003143 viewRoot.new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 }
3145 }
3146
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003147 public void dispatchPointer(MotionEvent event, long eventTime,
3148 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07003150 if (viewRoot != null) {
3151 if (MEASURE_LATENCY) {
3152 // Note: eventTime is in milliseconds
3153 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
3154 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003155 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003156 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003157 viewRoot.new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 }
3159 }
3160
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003161 public void dispatchTrackball(MotionEvent event, long eventTime,
3162 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 final ViewRoot viewRoot = mViewRoot.get();
3164 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003165 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003166 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003167 viewRoot.new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 }
3169 }
3170
3171 public void dispatchAppVisibility(boolean visible) {
3172 final ViewRoot viewRoot = mViewRoot.get();
3173 if (viewRoot != null) {
3174 viewRoot.dispatchAppVisibility(visible);
3175 }
3176 }
3177
3178 public void dispatchGetNewSurface() {
3179 final ViewRoot viewRoot = mViewRoot.get();
3180 if (viewRoot != null) {
3181 viewRoot.dispatchGetNewSurface();
3182 }
3183 }
3184
3185 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3186 final ViewRoot viewRoot = mViewRoot.get();
3187 if (viewRoot != null) {
3188 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3189 }
3190 }
3191
3192 private static int checkCallingPermission(String permission) {
3193 if (!Process.supportsProcesses()) {
3194 return PackageManager.PERMISSION_GRANTED;
3195 }
3196
3197 try {
3198 return ActivityManagerNative.getDefault().checkPermission(
3199 permission, Binder.getCallingPid(), Binder.getCallingUid());
3200 } catch (RemoteException e) {
3201 return PackageManager.PERMISSION_DENIED;
3202 }
3203 }
3204
3205 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3206 final ViewRoot viewRoot = mViewRoot.get();
3207 if (viewRoot != null) {
3208 final View view = viewRoot.mView;
3209 if (view != null) {
3210 if (checkCallingPermission(Manifest.permission.DUMP) !=
3211 PackageManager.PERMISSION_GRANTED) {
3212 throw new SecurityException("Insufficient permissions to invoke"
3213 + " executeCommand() from pid=" + Binder.getCallingPid()
3214 + ", uid=" + Binder.getCallingUid());
3215 }
3216
3217 OutputStream clientStream = null;
3218 try {
3219 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3220 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3221 } catch (IOException e) {
3222 e.printStackTrace();
3223 } finally {
3224 if (clientStream != null) {
3225 try {
3226 clientStream.close();
3227 } catch (IOException e) {
3228 e.printStackTrace();
3229 }
3230 }
3231 }
3232 }
3233 }
3234 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003235
Dianne Hackbornffa42482009-09-23 22:20:11 -07003236 public void closeSystemDialogs(String reason) {
3237 final ViewRoot viewRoot = mViewRoot.get();
3238 if (viewRoot != null) {
3239 viewRoot.dispatchCloseSystemDialogs(reason);
3240 }
3241 }
3242
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003243 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3244 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003245 if (sync) {
3246 try {
3247 sWindowSession.wallpaperOffsetsComplete(asBinder());
3248 } catch (RemoteException e) {
3249 }
3250 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003251 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003252
3253 public void dispatchWallpaperCommand(String action, int x, int y,
3254 int z, Bundle extras, boolean sync) {
3255 if (sync) {
3256 try {
3257 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3258 } catch (RemoteException e) {
3259 }
3260 }
3261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263
3264 /**
3265 * Maintains state information for a single trackball axis, generating
3266 * discrete (DPAD) movements based on raw trackball motion.
3267 */
3268 static final class TrackballAxis {
3269 /**
3270 * The maximum amount of acceleration we will apply.
3271 */
3272 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 /**
3275 * The maximum amount of time (in milliseconds) between events in order
3276 * for us to consider the user to be doing fast trackball movements,
3277 * and thus apply an acceleration.
3278 */
3279 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 /**
3282 * Scaling factor to the time (in milliseconds) between events to how
3283 * much to multiple/divide the current acceleration. When movement
3284 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3285 * FAST_MOVE_TIME it divides it.
3286 */
3287 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 float position;
3290 float absPosition;
3291 float acceleration = 1;
3292 long lastMoveTime = 0;
3293 int step;
3294 int dir;
3295 int nonAccelMovement;
3296
3297 void reset(int _step) {
3298 position = 0;
3299 acceleration = 1;
3300 lastMoveTime = 0;
3301 step = _step;
3302 dir = 0;
3303 }
3304
3305 /**
3306 * Add trackball movement into the state. If the direction of movement
3307 * has been reversed, the state is reset before adding the
3308 * movement (so that you don't have to compensate for any previously
3309 * collected movement before see the result of the movement in the
3310 * new direction).
3311 *
3312 * @return Returns the absolute value of the amount of movement
3313 * collected so far.
3314 */
3315 float collect(float off, long time, String axis) {
3316 long normTime;
3317 if (off > 0) {
3318 normTime = (long)(off * FAST_MOVE_TIME);
3319 if (dir < 0) {
3320 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3321 position = 0;
3322 step = 0;
3323 acceleration = 1;
3324 lastMoveTime = 0;
3325 }
3326 dir = 1;
3327 } else if (off < 0) {
3328 normTime = (long)((-off) * FAST_MOVE_TIME);
3329 if (dir > 0) {
3330 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3331 position = 0;
3332 step = 0;
3333 acceleration = 1;
3334 lastMoveTime = 0;
3335 }
3336 dir = -1;
3337 } else {
3338 normTime = 0;
3339 }
Romain Guy8506ab42009-06-11 17:35:47 -07003340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 // The number of milliseconds between each movement that is
3342 // considered "normal" and will not result in any acceleration
3343 // or deceleration, scaled by the offset we have here.
3344 if (normTime > 0) {
3345 long delta = time - lastMoveTime;
3346 lastMoveTime = time;
3347 float acc = acceleration;
3348 if (delta < normTime) {
3349 // The user is scrolling rapidly, so increase acceleration.
3350 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3351 if (scale > 1) acc *= scale;
3352 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3353 + off + " normTime=" + normTime + " delta=" + delta
3354 + " scale=" + scale + " acc=" + acc);
3355 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3356 } else {
3357 // The user is scrolling slowly, so decrease acceleration.
3358 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3359 if (scale > 1) acc /= scale;
3360 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3361 + off + " normTime=" + normTime + " delta=" + delta
3362 + " scale=" + scale + " acc=" + acc);
3363 acceleration = acc > 1 ? acc : 1;
3364 }
3365 }
3366 position += off;
3367 return (absPosition = Math.abs(position));
3368 }
3369
3370 /**
3371 * Generate the number of discrete movement events appropriate for
3372 * the currently collected trackball movement.
3373 *
3374 * @param precision The minimum movement required to generate the
3375 * first discrete movement.
3376 *
3377 * @return Returns the number of discrete movements, either positive
3378 * or negative, or 0 if there is not enough trackball movement yet
3379 * for a discrete movement.
3380 */
3381 int generate(float precision) {
3382 int movement = 0;
3383 nonAccelMovement = 0;
3384 do {
3385 final int dir = position >= 0 ? 1 : -1;
3386 switch (step) {
3387 // If we are going to execute the first step, then we want
3388 // to do this as soon as possible instead of waiting for
3389 // a full movement, in order to make things look responsive.
3390 case 0:
3391 if (absPosition < precision) {
3392 return movement;
3393 }
3394 movement += dir;
3395 nonAccelMovement += dir;
3396 step = 1;
3397 break;
3398 // If we have generated the first movement, then we need
3399 // to wait for the second complete trackball motion before
3400 // generating the second discrete movement.
3401 case 1:
3402 if (absPosition < 2) {
3403 return movement;
3404 }
3405 movement += dir;
3406 nonAccelMovement += dir;
3407 position += dir > 0 ? -2 : 2;
3408 absPosition = Math.abs(position);
3409 step = 2;
3410 break;
3411 // After the first two, we generate discrete movements
3412 // consistently with the trackball, applying an acceleration
3413 // if the trackball is moving quickly. This is a simple
3414 // acceleration on top of what we already compute based
3415 // on how quickly the wheel is being turned, to apply
3416 // a longer increasing acceleration to continuous movement
3417 // in one direction.
3418 default:
3419 if (absPosition < 1) {
3420 return movement;
3421 }
3422 movement += dir;
3423 position += dir >= 0 ? -1 : 1;
3424 absPosition = Math.abs(position);
3425 float acc = acceleration;
3426 acc *= 1.1f;
3427 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3428 break;
3429 }
3430 } while (true);
3431 }
3432 }
3433
3434 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3435 public CalledFromWrongThreadException(String msg) {
3436 super(msg);
3437 }
3438 }
3439
3440 private SurfaceHolder mHolder = new SurfaceHolder() {
3441 // we only need a SurfaceHolder for opengl. it would be nice
3442 // to implement everything else though, especially the callback
3443 // support (opengl doesn't make use of it right now, but eventually
3444 // will).
3445 public Surface getSurface() {
3446 return mSurface;
3447 }
3448
3449 public boolean isCreating() {
3450 return false;
3451 }
3452
3453 public void addCallback(Callback callback) {
3454 }
3455
3456 public void removeCallback(Callback callback) {
3457 }
3458
3459 public void setFixedSize(int width, int height) {
3460 }
3461
3462 public void setSizeFromLayout() {
3463 }
3464
3465 public void setFormat(int format) {
3466 }
3467
3468 public void setType(int type) {
3469 }
3470
3471 public void setKeepScreenOn(boolean screenOn) {
3472 }
3473
3474 public Canvas lockCanvas() {
3475 return null;
3476 }
3477
3478 public Canvas lockCanvas(Rect dirty) {
3479 return null;
3480 }
3481
3482 public void unlockCanvasAndPost(Canvas canvas) {
3483 }
3484 public Rect getSurfaceFrame() {
3485 return null;
3486 }
3487 };
3488
3489 static RunQueue getRunQueue() {
3490 RunQueue rq = sRunQueues.get();
3491 if (rq != null) {
3492 return rq;
3493 }
3494 rq = new RunQueue();
3495 sRunQueues.set(rq);
3496 return rq;
3497 }
Romain Guy8506ab42009-06-11 17:35:47 -07003498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 /**
3500 * @hide
3501 */
3502 static final class RunQueue {
3503 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3504
3505 void post(Runnable action) {
3506 postDelayed(action, 0);
3507 }
3508
3509 void postDelayed(Runnable action, long delayMillis) {
3510 HandlerAction handlerAction = new HandlerAction();
3511 handlerAction.action = action;
3512 handlerAction.delay = delayMillis;
3513
3514 synchronized (mActions) {
3515 mActions.add(handlerAction);
3516 }
3517 }
3518
3519 void removeCallbacks(Runnable action) {
3520 final HandlerAction handlerAction = new HandlerAction();
3521 handlerAction.action = action;
3522
3523 synchronized (mActions) {
3524 final ArrayList<HandlerAction> actions = mActions;
3525
3526 while (actions.remove(handlerAction)) {
3527 // Keep going
3528 }
3529 }
3530 }
3531
3532 void executeActions(Handler handler) {
3533 synchronized (mActions) {
3534 final ArrayList<HandlerAction> actions = mActions;
3535 final int count = actions.size();
3536
3537 for (int i = 0; i < count; i++) {
3538 final HandlerAction handlerAction = actions.get(i);
3539 handler.postDelayed(handlerAction.action, handlerAction.delay);
3540 }
3541
Romain Guy15df6702009-08-17 20:17:30 -07003542 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 }
3544 }
3545
3546 private static class HandlerAction {
3547 Runnable action;
3548 long delay;
3549
3550 @Override
3551 public boolean equals(Object o) {
3552 if (this == o) return true;
3553 if (o == null || getClass() != o.getClass()) return false;
3554
3555 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 return !(action != null ? !action.equals(that.action) : that.action != null);
3557
3558 }
3559
3560 @Override
3561 public int hashCode() {
3562 int result = action != null ? action.hashCode() : 0;
3563 result = 31 * result + (int) (delay ^ (delay >>> 32));
3564 return result;
3565 }
3566 }
3567 }
3568
3569 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3570
3571 // inform skia to just abandon its texture cache IDs
3572 // doesn't call glDeleteTextures
3573 private static native void nativeAbandonGlCaches();
3574}