blob: e980b17b4d82ad47a273bfdd22aca8439b85b78e [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
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700559 if (view instanceof RootViewSurfaceTaker) {
560 mInputQueueCallback =
561 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
562 }
563 if (mInputQueueCallback != null) {
564 mInputQueue = new InputQueue(mInputChannel);
565 mInputQueueCallback.onInputQueueCreated(mInputQueue);
566 } else {
567 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
568 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700569 }
570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 view.assignParent(this);
572 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
573 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
574 }
575 }
576 }
577
578 public View getView() {
579 return mView;
580 }
581
582 final WindowLeaked getLocation() {
583 return mLocation;
584 }
585
586 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
587 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700588 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700589 // preserve compatible window flag if exists.
590 int compatibleWindowFlag =
591 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700593 mWindowAttributes.flags |= compatibleWindowFlag;
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 if (newView) {
596 mSoftInputMode = attrs.softInputMode;
597 requestLayout();
598 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700599 // Don't lose the mode we last auto-computed.
600 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
601 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
602 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
603 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
604 | (oldSoftInputMode
605 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 mWindowAttributesChanged = true;
608 scheduleTraversals();
609 }
610 }
611
612 void handleAppVisibility(boolean visible) {
613 if (mAppVisible != visible) {
614 mAppVisible = visible;
615 scheduleTraversals();
616 }
617 }
618
619 void handleGetNewSurface() {
620 mNewSurfaceNeeded = true;
621 mFullRedrawNeeded = true;
622 scheduleTraversals();
623 }
624
625 /**
626 * {@inheritDoc}
627 */
628 public void requestLayout() {
629 checkThread();
630 mLayoutRequested = true;
631 scheduleTraversals();
632 }
633
634 /**
635 * {@inheritDoc}
636 */
637 public boolean isLayoutRequested() {
638 return mLayoutRequested;
639 }
640
641 public void invalidateChild(View child, Rect dirty) {
642 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700643 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
644 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700646 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700647 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700648 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700649 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700650 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700651 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700652 }
Romain Guy1e095972009-07-07 11:22:45 -0700653 if (mAttachInfo.mScalingRequired) {
654 dirty.inset(-1, -1);
655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 }
657 mDirty.union(dirty);
658 if (!mWillDrawSoon) {
659 scheduleTraversals();
660 }
661 }
662
663 public ViewParent getParent() {
664 return null;
665 }
666
667 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
668 invalidateChild(null, dirty);
669 return null;
670 }
671
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700672 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 if (child != mView) {
674 throw new RuntimeException("child is not mine, honest!");
675 }
676 // Note: don't apply scroll offset, because we want to know its
677 // visibility in the virtual canvas being given to the view hierarchy.
678 return r.intersect(0, 0, mWidth, mHeight);
679 }
680
681 public void bringChildToFront(View child) {
682 }
683
684 public void scheduleTraversals() {
685 if (!mTraversalScheduled) {
686 mTraversalScheduled = true;
687 sendEmptyMessage(DO_TRAVERSAL);
688 }
689 }
690
691 public void unscheduleTraversals() {
692 if (mTraversalScheduled) {
693 mTraversalScheduled = false;
694 removeMessages(DO_TRAVERSAL);
695 }
696 }
697
698 int getHostVisibility() {
699 return mAppVisible ? mView.getVisibility() : View.GONE;
700 }
Romain Guy8506ab42009-06-11 17:35:47 -0700701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 private void performTraversals() {
703 // cache mView since it is used so much below...
704 final View host = mView;
705
706 if (DBG) {
707 System.out.println("======================================");
708 System.out.println("performTraversals");
709 host.debug();
710 }
711
712 if (host == null || !mAdded)
713 return;
714
715 mTraversalScheduled = false;
716 mWillDrawSoon = true;
717 boolean windowResizesToFitContent = false;
718 boolean fullRedrawNeeded = mFullRedrawNeeded;
719 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700720 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 WindowManager.LayoutParams lp = mWindowAttributes;
722
723 int desiredWindowWidth;
724 int desiredWindowHeight;
725 int childWidthMeasureSpec;
726 int childHeightMeasureSpec;
727
728 final View.AttachInfo attachInfo = mAttachInfo;
729
730 final int viewVisibility = getHostVisibility();
731 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
732 || mNewSurfaceNeeded;
733
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700734 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 WindowManager.LayoutParams params = null;
737 if (mWindowAttributesChanged) {
738 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700739 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 params = lp;
741 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700742 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 if (mFirst) {
744 fullRedrawNeeded = true;
745 mLayoutRequested = true;
746
Romain Guy8506ab42009-06-11 17:35:47 -0700747 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700748 mView.getContext().getResources().getDisplayMetrics();
749 desiredWindowWidth = packageMetrics.widthPixels;
750 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
752 // For the very first time, tell the view hierarchy that it
753 // is attached to the window. Note that at this point the surface
754 // object is not initialized to its backing store, but soon it
755 // will be (assuming the window is visible).
756 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700757 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 attachInfo.mHasWindowFocus = false;
759 attachInfo.mWindowVisibility = viewVisibility;
760 attachInfo.mRecomputeGlobalAttributes = false;
761 attachInfo.mKeepScreenOn = false;
762 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700763 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700768 desiredWindowWidth = frame.width();
769 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
771 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700772 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 fullRedrawNeeded = true;
774 mLayoutRequested = true;
775 windowResizesToFitContent = true;
776 }
777 }
778
779 if (viewVisibilityChanged) {
780 attachInfo.mWindowVisibility = viewVisibility;
781 host.dispatchWindowVisibilityChanged(viewVisibility);
782 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
783 if (mUseGL) {
784 destroyGL();
785 }
786 }
787 if (viewVisibility == View.GONE) {
788 // After making a window gone, we will count it as being
789 // shown for the first time the next time it gets focus.
790 mHasHadWindowFocus = false;
791 }
792 }
793
794 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700797 // Execute enqueued actions on every layout in case a view that was detached
798 // enqueued an action after being detached
799 getRunQueue().executeActions(attachInfo.mHandler);
800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 if (mFirst) {
802 host.fitSystemWindows(mAttachInfo.mContentInsets);
803 // make sure touch mode code executes by setting cached value
804 // to opposite of the added touch mode.
805 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700806 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 } else {
808 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
809 mAttachInfo.mContentInsets.set(mPendingContentInsets);
810 host.fitSystemWindows(mAttachInfo.mContentInsets);
811 insetsChanged = true;
812 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
813 + mAttachInfo.mContentInsets);
814 }
815 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
816 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
817 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
818 + mAttachInfo.mVisibleInsets);
819 }
820 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
821 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
822 windowResizesToFitContent = true;
823
Romain Guy8506ab42009-06-11 17:35:47 -0700824 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700825 mView.getContext().getResources().getDisplayMetrics();
826 desiredWindowWidth = packageMetrics.widthPixels;
827 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829 }
830
831 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
832 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
833
834 // Ask host how big it wants to be
835 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
836 "Measuring " + host + " in display " + desiredWindowWidth
837 + "x" + desiredWindowHeight + "...");
838 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
839
840 if (DBG) {
841 System.out.println("======================================");
842 System.out.println("performTraversals -- after measure");
843 host.debug();
844 }
845 }
846
847 if (attachInfo.mRecomputeGlobalAttributes) {
848 //Log.i(TAG, "Computing screen on!");
849 attachInfo.mRecomputeGlobalAttributes = false;
850 boolean oldVal = attachInfo.mKeepScreenOn;
851 attachInfo.mKeepScreenOn = false;
852 host.dispatchCollectViewAttributes(0);
853 if (attachInfo.mKeepScreenOn != oldVal) {
854 params = lp;
855 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
856 }
857 }
858
859 if (mFirst || attachInfo.mViewVisibilityChanged) {
860 attachInfo.mViewVisibilityChanged = false;
861 int resizeMode = mSoftInputMode &
862 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
863 // If we are in auto resize mode, then we need to determine
864 // what mode to use now.
865 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
866 final int N = attachInfo.mScrollContainers.size();
867 for (int i=0; i<N; i++) {
868 if (attachInfo.mScrollContainers.get(i).isShown()) {
869 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
870 }
871 }
872 if (resizeMode == 0) {
873 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
874 }
875 if ((lp.softInputMode &
876 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
877 lp.softInputMode = (lp.softInputMode &
878 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
879 resizeMode;
880 params = lp;
881 }
882 }
883 }
Romain Guy8506ab42009-06-11 17:35:47 -0700884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
886 if (!PixelFormat.formatHasAlpha(params.format)) {
887 params.format = PixelFormat.TRANSLUCENT;
888 }
889 }
890
891 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700892 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
893 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
894 frame.width() < desiredWindowWidth && frame.width() != mWidth)
895 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
896 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897
898 final boolean computesInternalInsets =
899 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
900 boolean insetsPending = false;
901 int relayoutResult = 0;
902 if (mFirst || windowShouldResize || insetsChanged
903 || viewVisibilityChanged || params != null) {
904
905 if (viewVisibility == View.VISIBLE) {
906 // If this window is giving internal insets to the window
907 // manager, and it is being added or changing its visibility,
908 // then we want to first give the window manager "fake"
909 // insets to cause it to effectively ignore the content of
910 // the window during layout. This avoids it briefly causing
911 // other windows to resize/move based on the raw frame of the
912 // window, waiting until we can finish laying out this window
913 // and get back to the window manager with the ultimately
914 // computed insets.
915 insetsPending = computesInternalInsets
916 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
919 if (params == null) {
920 params = mWindowAttributes;
921 }
922 mGlWanted = true;
923 }
924 }
925
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700926 if (mSurfaceHolder != null) {
927 mSurfaceHolder.mSurfaceLock.lock();
928 mDrawingAllowed = true;
929 lp.format = mSurfaceHolder.getRequestedFormat();
930 lp.type = mSurfaceHolder.getRequestedType();
931 }
932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 boolean initialized = false;
934 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700935 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700936 boolean hadSurface = mSurface.isValid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 int fl = 0;
939 if (params != null) {
940 fl = params.flags;
941 if (attachInfo.mKeepScreenOn) {
942 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
943 }
944 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700945 if (DEBUG_LAYOUT) {
946 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
947 host.mMeasuredHeight + ", params=" + params);
948 }
949 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 if (params != null) {
952 params.flags = fl;
953 }
954
955 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
956 + " content=" + mPendingContentInsets.toShortString()
957 + " visible=" + mPendingVisibleInsets.toShortString()
958 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700959
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700960 if (mPendingConfiguration.seq != 0) {
961 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
962 + mPendingConfiguration);
963 updateConfiguration(mPendingConfiguration, !mFirst);
964 mPendingConfiguration.seq = 0;
965 }
966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 contentInsetsChanged = !mPendingContentInsets.equals(
968 mAttachInfo.mContentInsets);
969 visibleInsetsChanged = !mPendingVisibleInsets.equals(
970 mAttachInfo.mVisibleInsets);
971 if (contentInsetsChanged) {
972 mAttachInfo.mContentInsets.set(mPendingContentInsets);
973 host.fitSystemWindows(mAttachInfo.mContentInsets);
974 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
975 + mAttachInfo.mContentInsets);
976 }
977 if (visibleInsetsChanged) {
978 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
979 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
980 + mAttachInfo.mVisibleInsets);
981 }
982
983 if (!hadSurface) {
984 if (mSurface.isValid()) {
985 // If we are creating a new surface, then we need to
986 // completely redraw it. Also, when we get to the
987 // point of drawing it we will hold off and schedule
988 // a new traversal instead. This is so we can tell the
989 // window manager about all of the windows being displayed
990 // before actually drawing them, so it can display then
991 // all at once.
992 newSurface = true;
993 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700994 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 if (mGlWanted && !mUseGL) {
997 initializeGL();
998 initialized = mGlCanvas != null;
999 }
1000 }
1001 } else if (!mSurface.isValid()) {
1002 // If the surface has been removed, then reset the scroll
1003 // positions.
1004 mLastScrolledFocus = null;
1005 mScrollY = mCurScrollY = 0;
1006 if (mScroller != null) {
1007 mScroller.abortAnimation();
1008 }
1009 }
1010 } catch (RemoteException e) {
1011 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001014 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015
1016 attachInfo.mWindowLeft = frame.left;
1017 attachInfo.mWindowTop = frame.top;
1018
1019 // !!FIXME!! This next section handles the case where we did not get the
1020 // window size we asked for. We should avoid this by getting a maximum size from
1021 // the window session beforehand.
1022 mWidth = frame.width();
1023 mHeight = frame.height();
1024
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001025 if (mSurfaceHolder != null) {
1026 // The app owns the surface; tell it about what is going on.
1027 if (mSurface.isValid()) {
1028 // XXX .copyFrom() doesn't work!
1029 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1030 mSurfaceHolder.mSurface = mSurface;
1031 }
1032 mSurfaceHolder.mSurfaceLock.unlock();
1033 if (mSurface.isValid()) {
1034 if (!hadSurface) {
1035 mSurfaceHolder.ungetCallbacks();
1036
1037 mIsCreating = true;
1038 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1039 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1040 if (callbacks != null) {
1041 for (SurfaceHolder.Callback c : callbacks) {
1042 c.surfaceCreated(mSurfaceHolder);
1043 }
1044 }
1045 surfaceChanged = true;
1046 }
1047 if (surfaceChanged) {
1048 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1049 lp.format, mWidth, mHeight);
1050 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1051 if (callbacks != null) {
1052 for (SurfaceHolder.Callback c : callbacks) {
1053 c.surfaceChanged(mSurfaceHolder, lp.format,
1054 mWidth, mHeight);
1055 }
1056 }
1057 }
1058 mIsCreating = false;
1059 } else if (hadSurface) {
1060 mSurfaceHolder.ungetCallbacks();
1061 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1062 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1063 if (callbacks != null) {
1064 for (SurfaceHolder.Callback c : callbacks) {
1065 c.surfaceDestroyed(mSurfaceHolder);
1066 }
1067 }
1068 mSurfaceHolder.mSurfaceLock.lock();
1069 // Make surface invalid.
1070 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1071 mSurfaceHolder.mSurface = new Surface();
1072 mSurfaceHolder.mSurfaceLock.unlock();
1073 }
1074 }
1075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001077 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
1078 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
1080
1081 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001082 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1084 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1085 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1086 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1087
1088 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1089 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1090 + " mHeight=" + mHeight
1091 + " measuredHeight" + host.mMeasuredHeight
1092 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 // Ask host how big it wants to be
1095 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1096
1097 // Implementation of weights from WindowManager.LayoutParams
1098 // We just grow the dimensions as needed and re-measure if
1099 // needs be
1100 int width = host.mMeasuredWidth;
1101 int height = host.mMeasuredHeight;
1102 boolean measureAgain = false;
1103
1104 if (lp.horizontalWeight > 0.0f) {
1105 width += (int) ((mWidth - width) * lp.horizontalWeight);
1106 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1107 MeasureSpec.EXACTLY);
1108 measureAgain = true;
1109 }
1110 if (lp.verticalWeight > 0.0f) {
1111 height += (int) ((mHeight - height) * lp.verticalWeight);
1112 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1113 MeasureSpec.EXACTLY);
1114 measureAgain = true;
1115 }
1116
1117 if (measureAgain) {
1118 if (DEBUG_LAYOUT) Log.v(TAG,
1119 "And hey let's measure once more: width=" + width
1120 + " height=" + height);
1121 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1122 }
1123
1124 mLayoutRequested = true;
1125 }
1126 }
1127
1128 final boolean didLayout = mLayoutRequested;
1129 boolean triggerGlobalLayoutListener = didLayout
1130 || attachInfo.mRecomputeGlobalAttributes;
1131 if (didLayout) {
1132 mLayoutRequested = false;
1133 mScrollMayChange = true;
1134 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1135 "ViewRoot", "Laying out " + host + " to (" +
1136 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001137 long startTime = 0L;
1138 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 startTime = SystemClock.elapsedRealtime();
1140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1142
Romain Guy13922e02009-05-12 17:56:14 -07001143 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1144 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1145 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1146 + "please refer to the logs with the tag "
1147 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1148 }
1149 }
1150
1151 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1153 }
1154
1155 // By this point all views have been sized and positionned
1156 // We can compute the transparent area
1157
1158 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1159 // start out transparent
1160 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1161 host.getLocationInWindow(mTmpLocation);
1162 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1163 mTmpLocation[0] + host.mRight - host.mLeft,
1164 mTmpLocation[1] + host.mBottom - host.mTop);
1165
1166 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001167 if (mTranslator != null) {
1168 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1169 }
1170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1172 mPreviousTransparentRegion.set(mTransparentRegion);
1173 // reconfigure window manager
1174 try {
1175 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1176 } catch (RemoteException e) {
1177 }
1178 }
1179 }
1180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 if (DBG) {
1182 System.out.println("======================================");
1183 System.out.println("performTraversals -- after setFrame");
1184 host.debug();
1185 }
1186 }
1187
1188 if (triggerGlobalLayoutListener) {
1189 attachInfo.mRecomputeGlobalAttributes = false;
1190 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1191 }
1192
1193 if (computesInternalInsets) {
1194 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1195 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1196 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1197 givenContent.left = givenContent.top = givenContent.right
1198 = givenContent.bottom = givenVisible.left = givenVisible.top
1199 = givenVisible.right = givenVisible.bottom = 0;
1200 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001201 Rect contentInsets = insets.contentInsets;
1202 Rect visibleInsets = insets.visibleInsets;
1203 if (mTranslator != null) {
1204 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1205 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1208 mLastGivenInsets.set(insets);
1209 try {
1210 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001211 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 } catch (RemoteException e) {
1213 }
1214 }
1215 }
Romain Guy8506ab42009-06-11 17:35:47 -07001216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 if (mFirst) {
1218 // handle first focus request
1219 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1220 + mView.hasFocus());
1221 if (mView != null) {
1222 if (!mView.hasFocus()) {
1223 mView.requestFocus(View.FOCUS_FORWARD);
1224 mFocusedView = mRealFocusedView = mView.findFocus();
1225 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1226 + mFocusedView);
1227 } else {
1228 mRealFocusedView = mView.findFocus();
1229 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1230 + mRealFocusedView);
1231 }
1232 }
1233 }
1234
1235 mFirst = false;
1236 mWillDrawSoon = false;
1237 mNewSurfaceNeeded = false;
1238 mViewVisibility = viewVisibility;
1239
1240 if (mAttachInfo.mHasWindowFocus) {
1241 final boolean imTarget = WindowManager.LayoutParams
1242 .mayUseInputMethod(mWindowAttributes.flags);
1243 if (imTarget != mLastWasImTarget) {
1244 mLastWasImTarget = imTarget;
1245 InputMethodManager imm = InputMethodManager.peekInstance();
1246 if (imm != null && imTarget) {
1247 imm.startGettingWindowFocus(mView);
1248 imm.onWindowFocus(mView, mView.findFocus(),
1249 mWindowAttributes.softInputMode,
1250 !mHasHadWindowFocus, mWindowAttributes.flags);
1251 }
1252 }
1253 }
Romain Guy8506ab42009-06-11 17:35:47 -07001254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1256
1257 if (!cancelDraw && !newSurface) {
1258 mFullRedrawNeeded = false;
1259 draw(fullRedrawNeeded);
1260
1261 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1262 || mReportNextDraw) {
1263 if (LOCAL_LOGV) {
1264 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1265 }
1266 mReportNextDraw = false;
1267 try {
1268 sWindowSession.finishDrawing(mWindow);
1269 } catch (RemoteException e) {
1270 }
1271 }
1272 } else {
1273 // We were supposed to report when we are done drawing. Since we canceled the
1274 // draw, remember it here.
1275 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1276 mReportNextDraw = true;
1277 }
1278 if (fullRedrawNeeded) {
1279 mFullRedrawNeeded = true;
1280 }
1281 // Try again
1282 scheduleTraversals();
1283 }
1284 }
1285
1286 public void requestTransparentRegion(View child) {
1287 // the test below should not fail unless someone is messing with us
1288 checkThread();
1289 if (mView == child) {
1290 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1291 // Need to make sure we re-evaluate the window attributes next
1292 // time around, to ensure the window has the correct format.
1293 mWindowAttributesChanged = true;
1294 }
1295 }
1296
1297 /**
1298 * Figures out the measure spec for the root view in a window based on it's
1299 * layout params.
1300 *
1301 * @param windowSize
1302 * The available width or height of the window
1303 *
1304 * @param rootDimension
1305 * The layout params for one dimension (width or height) of the
1306 * window.
1307 *
1308 * @return The measure spec to use to measure the root view.
1309 */
1310 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1311 int measureSpec;
1312 switch (rootDimension) {
1313
Romain Guy980a9382010-01-08 15:06:28 -08001314 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 // Window can't resize. Force root view to be windowSize.
1316 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1317 break;
1318 case ViewGroup.LayoutParams.WRAP_CONTENT:
1319 // Window can resize. Set max size for root view.
1320 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1321 break;
1322 default:
1323 // Window wants to be an exact size. Force root view to be that size.
1324 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1325 break;
1326 }
1327 return measureSpec;
1328 }
1329
1330 private void draw(boolean fullRedrawNeeded) {
1331 Surface surface = mSurface;
1332 if (surface == null || !surface.isValid()) {
1333 return;
1334 }
1335
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001336 if (!sFirstDrawComplete) {
1337 synchronized (sFirstDrawHandlers) {
1338 sFirstDrawComplete = true;
1339 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1340 post(sFirstDrawHandlers.get(i));
1341 }
1342 }
1343 }
1344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 scrollToRectOrFocus(null, false);
1346
1347 if (mAttachInfo.mViewScrollChanged) {
1348 mAttachInfo.mViewScrollChanged = false;
1349 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1350 }
Romain Guy8506ab42009-06-11 17:35:47 -07001351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001353 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 if (scrolling) {
1355 yoff = mScroller.getCurrY();
1356 } else {
1357 yoff = mScrollY;
1358 }
1359 if (mCurScrollY != yoff) {
1360 mCurScrollY = yoff;
1361 fullRedrawNeeded = true;
1362 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001363 float appScale = mAttachInfo.mApplicationScale;
1364 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365
1366 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001367 if (mSurfaceHolder != null) {
1368 // The app owns the surface, we won't draw.
1369 dirty.setEmpty();
1370 return;
1371 }
1372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 if (mUseGL) {
1374 if (!dirty.isEmpty()) {
1375 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001376 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 mGL.glDisable(GL_SCISSOR_TEST);
1378 mGL.glClearColor(0, 0, 0, 0);
1379 mGL.glClear(GL_COLOR_BUFFER_BIT);
1380 mGL.glEnable(GL_SCISSOR_TEST);
1381
1382 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001383 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001385
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001386 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1387 try {
1388 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001389 if (mTranslator != null) {
1390 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001391 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001392 canvas.setScreenDensity(scalingRequired
1393 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001394 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001395 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1396 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1397 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001398 } finally {
1399 canvas.restoreToCount(saveCount);
1400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401
Romain Guy5bcdff42009-05-14 21:27:18 -07001402 mAttachInfo.mIgnoreDirtyState = false;
1403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1405 checkEglErrors();
1406
Mike Reedfd716532009-10-12 14:42:56 -04001407 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 int now = (int)SystemClock.elapsedRealtime();
1409 if (sDrawTime != 0) {
1410 nativeShowFPS(canvas, now - sDrawTime);
1411 }
1412 sDrawTime = now;
1413 }
1414 }
1415 }
1416 if (scrolling) {
1417 mFullRedrawNeeded = true;
1418 scheduleTraversals();
1419 }
1420 return;
1421 }
1422
Romain Guy5bcdff42009-05-14 21:27:18 -07001423 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001424 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001425 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
1428 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1429 Log.v("ViewRoot", "Draw " + mView + "/"
1430 + mWindowAttributes.getTitle()
1431 + ": dirty={" + dirty.left + "," + dirty.top
1432 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001433 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1434 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001437 if (!dirty.isEmpty() || mIsAnimating) {
1438 Canvas canvas;
1439 try {
1440 int left = dirty.left;
1441 int top = dirty.top;
1442 int right = dirty.right;
1443 int bottom = dirty.bottom;
1444 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001445
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001446 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1447 bottom != dirty.bottom) {
1448 mAttachInfo.mIgnoreDirtyState = true;
1449 }
1450
1451 // TODO: Do this in native
1452 canvas.setDensity(mDensity);
1453 } catch (Surface.OutOfResourcesException e) {
1454 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1455 // TODO: we should ask the window manager to do something!
1456 // for now we just do nothing
1457 return;
1458 } catch (IllegalArgumentException e) {
1459 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1460 // TODO: we should ask the window manager to do something!
1461 // for now we just do nothing
1462 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001463 }
1464
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001465 try {
1466 if (!dirty.isEmpty() || mIsAnimating) {
1467 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001469 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1470 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1471 + canvas.getWidth() + ", h=" + canvas.getHeight());
1472 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001475 if (Config.DEBUG && ViewDebug.profileDrawing) {
1476 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001478
1479 // If this bitmap's format includes an alpha channel, we
1480 // need to clear it before drawing so that the child will
1481 // properly re-composite its drawing on a transparent
1482 // background. This automatically respects the clip/dirty region
1483 // or
1484 // If we are applying an offset, we need to clear the area
1485 // where the offset doesn't appear to avoid having garbage
1486 // left in the blank areas.
1487 if (!canvas.isOpaque() || yoff != 0) {
1488 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1489 }
1490
1491 dirty.setEmpty();
1492 mIsAnimating = false;
1493 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1494 mView.mPrivateFlags |= View.DRAWN;
1495
1496 if (DEBUG_DRAW) {
1497 Context cxt = mView.getContext();
1498 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1499 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1500 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1501 }
1502 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1503 try {
1504 canvas.translate(0, -yoff);
1505 if (mTranslator != null) {
1506 mTranslator.translateCanvas(canvas);
1507 }
1508 canvas.setScreenDensity(scalingRequired
1509 ? DisplayMetrics.DENSITY_DEVICE : 0);
1510 mView.draw(canvas);
1511 } finally {
1512 mAttachInfo.mIgnoreDirtyState = false;
1513 canvas.restoreToCount(saveCount);
1514 }
1515
1516 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1517 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1518 }
1519
1520 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1521 int now = (int)SystemClock.elapsedRealtime();
1522 if (sDrawTime != 0) {
1523 nativeShowFPS(canvas, now - sDrawTime);
1524 }
1525 sDrawTime = now;
1526 }
1527
1528 if (Config.DEBUG && ViewDebug.profileDrawing) {
1529 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
1532
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001533 } finally {
1534 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537
1538 if (LOCAL_LOGV) {
1539 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1540 }
Romain Guy8506ab42009-06-11 17:35:47 -07001541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if (scrolling) {
1543 mFullRedrawNeeded = true;
1544 scheduleTraversals();
1545 }
1546 }
1547
1548 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1549 final View.AttachInfo attachInfo = mAttachInfo;
1550 final Rect ci = attachInfo.mContentInsets;
1551 final Rect vi = attachInfo.mVisibleInsets;
1552 int scrollY = 0;
1553 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 if (vi.left > ci.left || vi.top > ci.top
1556 || vi.right > ci.right || vi.bottom > ci.bottom) {
1557 // We'll assume that we aren't going to change the scroll
1558 // offset, since we want to avoid that unless it is actually
1559 // going to make the focus visible... otherwise we scroll
1560 // all over the place.
1561 scrollY = mScrollY;
1562 // We can be called for two different situations: during a draw,
1563 // to update the scroll position if the focus has changed (in which
1564 // case 'rectangle' is null), or in response to a
1565 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1566 // is non-null and we just want to scroll to whatever that
1567 // rectangle is).
1568 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001569
1570 // When in touch mode, focus points to the previously focused view,
1571 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001572 // line checks whether the view is still in our hierarchy.
1573 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001574 mRealFocusedView = null;
1575 return false;
1576 }
1577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if (focus != mLastScrolledFocus) {
1579 // If the focus has changed, then ignore any requests to scroll
1580 // to a rectangle; first we want to make sure the entire focus
1581 // view is visible.
1582 rectangle = null;
1583 }
1584 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1585 + " rectangle=" + rectangle + " ci=" + ci
1586 + " vi=" + vi);
1587 if (focus == mLastScrolledFocus && !mScrollMayChange
1588 && rectangle == null) {
1589 // Optimization: if the focus hasn't changed since last
1590 // time, and no layout has happened, then just leave things
1591 // as they are.
1592 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1593 + mScrollY + " vi=" + vi.toShortString());
1594 } else if (focus != null) {
1595 // We need to determine if the currently focused view is
1596 // within the visible part of the window and, if not, apply
1597 // a pan so it can be seen.
1598 mLastScrolledFocus = focus;
1599 mScrollMayChange = false;
1600 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1601 // Try to find the rectangle from the focus view.
1602 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1603 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1604 + mView.getWidth() + " h=" + mView.getHeight()
1605 + " ci=" + ci.toShortString()
1606 + " vi=" + vi.toShortString());
1607 if (rectangle == null) {
1608 focus.getFocusedRect(mTempRect);
1609 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1610 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001611 if (mView instanceof ViewGroup) {
1612 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1613 focus, mTempRect);
1614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1616 "Focus in window: focusRect="
1617 + mTempRect.toShortString()
1618 + " visRect=" + mVisRect.toShortString());
1619 } else {
1620 mTempRect.set(rectangle);
1621 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1622 "Request scroll to rect: "
1623 + mTempRect.toShortString()
1624 + " visRect=" + mVisRect.toShortString());
1625 }
1626 if (mTempRect.intersect(mVisRect)) {
1627 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1628 "Focus window visible rect: "
1629 + mTempRect.toShortString());
1630 if (mTempRect.height() >
1631 (mView.getHeight()-vi.top-vi.bottom)) {
1632 // If the focus simply is not going to fit, then
1633 // best is probably just to leave things as-is.
1634 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1635 "Too tall; leaving scrollY=" + scrollY);
1636 } else if ((mTempRect.top-scrollY) < vi.top) {
1637 scrollY -= vi.top - (mTempRect.top-scrollY);
1638 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1639 "Top covered; scrollY=" + scrollY);
1640 } else if ((mTempRect.bottom-scrollY)
1641 > (mView.getHeight()-vi.bottom)) {
1642 scrollY += (mTempRect.bottom-scrollY)
1643 - (mView.getHeight()-vi.bottom);
1644 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1645 "Bottom covered; scrollY=" + scrollY);
1646 }
1647 handled = true;
1648 }
1649 }
1650 }
1651 }
Romain Guy8506ab42009-06-11 17:35:47 -07001652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 if (scrollY != mScrollY) {
1654 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1655 + mScrollY + " , new=" + scrollY);
1656 if (!immediate) {
1657 if (mScroller == null) {
1658 mScroller = new Scroller(mView.getContext());
1659 }
1660 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1661 } else if (mScroller != null) {
1662 mScroller.abortAnimation();
1663 }
1664 mScrollY = scrollY;
1665 }
Romain Guy8506ab42009-06-11 17:35:47 -07001666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 return handled;
1668 }
Romain Guy8506ab42009-06-11 17:35:47 -07001669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 public void requestChildFocus(View child, View focused) {
1671 checkThread();
1672 if (mFocusedView != focused) {
1673 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1674 scheduleTraversals();
1675 }
1676 mFocusedView = mRealFocusedView = focused;
1677 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1678 + mFocusedView);
1679 }
1680
1681 public void clearChildFocus(View child) {
1682 checkThread();
1683
1684 View oldFocus = mFocusedView;
1685
1686 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1687 mFocusedView = mRealFocusedView = null;
1688 if (mView != null && !mView.hasFocus()) {
1689 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1690 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1691 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1692 }
1693 } else if (oldFocus != null) {
1694 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1695 }
1696 }
1697
1698
1699 public void focusableViewAvailable(View v) {
1700 checkThread();
1701
1702 if (mView != null && !mView.hasFocus()) {
1703 v.requestFocus();
1704 } else {
1705 // the one case where will transfer focus away from the current one
1706 // is if the current view is a view group that prefers to give focus
1707 // to its children first AND the view is a descendant of it.
1708 mFocusedView = mView.findFocus();
1709 boolean descendantsHaveDibsOnFocus =
1710 (mFocusedView instanceof ViewGroup) &&
1711 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1712 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1713 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1714 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1715 v.requestFocus();
1716 }
1717 }
1718 }
1719
1720 public void recomputeViewAttributes(View child) {
1721 checkThread();
1722 if (mView == child) {
1723 mAttachInfo.mRecomputeGlobalAttributes = true;
1724 if (!mWillDrawSoon) {
1725 scheduleTraversals();
1726 }
1727 }
1728 }
1729
1730 void dispatchDetachedFromWindow() {
1731 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1732
1733 if (mView != null) {
1734 mView.dispatchDetachedFromWindow();
1735 }
1736
1737 mView = null;
1738 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001739 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740
1741 if (mUseGL) {
1742 destroyGL();
1743 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001744 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001746 if (mInputChannel != null) {
1747 if (mInputQueueCallback != null) {
1748 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1749 mInputQueueCallback = null;
1750 } else {
1751 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001752 }
1753 }
1754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 try {
1756 sWindowSession.remove(mWindow);
1757 } catch (RemoteException e) {
1758 }
Jeff Brown349703e2010-06-22 01:27:15 -07001759
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001760 // Dispose the input channel after removing the window so the Window Manager
1761 // doesn't interpret the input channel being closed as an abnormal termination.
1762 if (mInputChannel != null) {
1763 mInputChannel.dispose();
1764 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
Romain Guy8506ab42009-06-11 17:35:47 -07001767
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001768 void updateConfiguration(Configuration config, boolean force) {
1769 if (DEBUG_CONFIGURATION) Log.v(TAG,
1770 "Applying new config to window "
1771 + mWindowAttributes.getTitle()
1772 + ": " + config);
1773 synchronized (sConfigCallbacks) {
1774 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1775 sConfigCallbacks.get(i).onConfigurationChanged(config);
1776 }
1777 }
1778 if (mView != null) {
1779 // At this point the resources have been updated to
1780 // have the most recent config, whatever that is. Use
1781 // the on in them which may be newer.
1782 if (mView != null) {
1783 config = mView.getResources().getConfiguration();
1784 }
1785 if (force || mLastConfiguration.diff(config) != 0) {
1786 mLastConfiguration.setTo(config);
1787 mView.dispatchConfigurationChanged(config);
1788 }
1789 }
1790 }
1791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 /**
1793 * Return true if child is an ancestor of parent, (or equal to the parent).
1794 */
1795 private static boolean isViewDescendantOf(View child, View parent) {
1796 if (child == parent) {
1797 return true;
1798 }
1799
1800 final ViewParent theParent = child.getParent();
1801 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1802 }
1803
Romain Guycdb86672010-03-18 18:54:50 -07001804 private static void forceLayout(View view) {
1805 view.forceLayout();
1806 if (view instanceof ViewGroup) {
1807 ViewGroup group = (ViewGroup) view;
1808 final int count = group.getChildCount();
1809 for (int i = 0; i < count; i++) {
1810 forceLayout(group.getChildAt(i));
1811 }
1812 }
1813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814
1815 public final static int DO_TRAVERSAL = 1000;
1816 public final static int DIE = 1001;
1817 public final static int RESIZED = 1002;
1818 public final static int RESIZED_REPORT = 1003;
1819 public final static int WINDOW_FOCUS_CHANGED = 1004;
1820 public final static int DISPATCH_KEY = 1005;
1821 public final static int DISPATCH_POINTER = 1006;
1822 public final static int DISPATCH_TRACKBALL = 1007;
1823 public final static int DISPATCH_APP_VISIBILITY = 1008;
1824 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1825 public final static int FINISHED_EVENT = 1010;
1826 public final static int DISPATCH_KEY_FROM_IME = 1011;
1827 public final static int FINISH_INPUT_CONNECTION = 1012;
1828 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001829 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830
1831 @Override
1832 public void handleMessage(Message msg) {
1833 switch (msg.what) {
1834 case View.AttachInfo.INVALIDATE_MSG:
1835 ((View) msg.obj).invalidate();
1836 break;
1837 case View.AttachInfo.INVALIDATE_RECT_MSG:
1838 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1839 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1840 info.release();
1841 break;
1842 case DO_TRAVERSAL:
1843 if (mProfile) {
1844 Debug.startMethodTracing("ViewRoot");
1845 }
1846
1847 performTraversals();
1848
1849 if (mProfile) {
1850 Debug.stopMethodTracing();
1851 mProfile = false;
1852 }
1853 break;
1854 case FINISHED_EVENT:
1855 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1856 break;
1857 case DISPATCH_KEY:
1858 if (LOCAL_LOGV) Log.v(
1859 "ViewRoot", "Dispatching key "
1860 + msg.obj + " to " + mView);
1861 deliverKeyEvent((KeyEvent)msg.obj, true);
1862 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001863 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001864 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001866 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001868 event.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001871 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001872 case DISPATCH_TRACKBALL: {
1873 MotionEvent event = (MotionEvent) msg.obj;
1874 try {
1875 deliverTrackballEvent(event);
1876 } finally {
1877 event.recycle();
1878 }
1879 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 case DISPATCH_APP_VISIBILITY:
1881 handleAppVisibility(msg.arg1 != 0);
1882 break;
1883 case DISPATCH_GET_NEW_SURFACE:
1884 handleGetNewSurface();
1885 break;
1886 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001887 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001890 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001891 && mPendingVisibleInsets.equals(ri.visibleInsets)
1892 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 break;
1894 }
1895 // fall through...
1896 case RESIZED_REPORT:
1897 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001898 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1899 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001900 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 mWinFrame.left = 0;
1903 mWinFrame.right = msg.arg1;
1904 mWinFrame.top = 0;
1905 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001906 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1907 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 if (msg.what == RESIZED_REPORT) {
1909 mReportNextDraw = true;
1910 }
Romain Guycdb86672010-03-18 18:54:50 -07001911
1912 if (mView != null) {
1913 forceLayout(mView);
1914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 requestLayout();
1916 }
1917 break;
1918 case WINDOW_FOCUS_CHANGED: {
1919 if (mAdded) {
1920 boolean hasWindowFocus = msg.arg1 != 0;
1921 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1922 if (hasWindowFocus) {
1923 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001924 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925
1926 if (mGlWanted) {
1927 checkEglErrors();
1928 // we lost the gl context, so recreate it.
1929 if (mGlWanted && !mUseGL) {
1930 initializeGL();
1931 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001932 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001933 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001934 (int) (mWidth * appScale + 0.5f),
1935 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937 }
1938 }
1939 }
Romain Guy8506ab42009-06-11 17:35:47 -07001940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 mLastWasImTarget = WindowManager.LayoutParams
1942 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 InputMethodManager imm = InputMethodManager.peekInstance();
1945 if (mView != null) {
1946 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1947 imm.startGettingWindowFocus(mView);
1948 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001949 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 mView.dispatchWindowFocusChanged(hasWindowFocus);
1951 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 // Note: must be done after the focus change callbacks,
1954 // so all of the view state is set up correctly.
1955 if (hasWindowFocus) {
1956 if (imm != null && mLastWasImTarget) {
1957 imm.onWindowFocus(mView, mView.findFocus(),
1958 mWindowAttributes.softInputMode,
1959 !mHasHadWindowFocus, mWindowAttributes.flags);
1960 }
1961 // Clear the forward bit. We can just do this directly, since
1962 // the window manager doesn't care about it.
1963 mWindowAttributes.softInputMode &=
1964 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1965 ((WindowManager.LayoutParams)mView.getLayoutParams())
1966 .softInputMode &=
1967 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1968 mHasHadWindowFocus = true;
1969 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001970
1971 if (hasWindowFocus && mView != null) {
1972 sendAccessibilityEvents();
1973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
1975 } break;
1976 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001977 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001979 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 if (LOCAL_LOGV) Log.v(
1981 "ViewRoot", "Dispatching key "
1982 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001983 KeyEvent event = (KeyEvent)msg.obj;
1984 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1985 // The IME is trying to say this event is from the
1986 // system! Bad bad bad!
1987 event = KeyEvent.changeFlags(event,
1988 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001991 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 case FINISH_INPUT_CONNECTION: {
1993 InputMethodManager imm = InputMethodManager.peekInstance();
1994 if (imm != null) {
1995 imm.reportFinishInputConnection((InputConnection)msg.obj);
1996 }
1997 } break;
1998 case CHECK_FOCUS: {
1999 InputMethodManager imm = InputMethodManager.peekInstance();
2000 if (imm != null) {
2001 imm.checkFocus();
2002 }
2003 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002004 case CLOSE_SYSTEM_DIALOGS: {
2005 if (mView != null) {
2006 mView.onCloseSystemDialogs((String)msg.obj);
2007 }
2008 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002011
2012 private void finishKeyEvent(KeyEvent event) {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002013 if (mFinishedCallback != null) {
2014 mFinishedCallback.run();
2015 mFinishedCallback = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002016 }
2017 }
2018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 /**
2020 * Something in the current window tells us we need to change the touch mode. For
2021 * example, we are not in touch mode, and the user touches the screen.
2022 *
2023 * If the touch mode has changed, tell the window manager, and handle it locally.
2024 *
2025 * @param inTouchMode Whether we want to be in touch mode.
2026 * @return True if the touch mode changed and focus changed was changed as a result
2027 */
2028 boolean ensureTouchMode(boolean inTouchMode) {
2029 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2030 + "touch mode is " + mAttachInfo.mInTouchMode);
2031 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2032
2033 // tell the window manager
2034 try {
2035 sWindowSession.setInTouchMode(inTouchMode);
2036 } catch (RemoteException e) {
2037 throw new RuntimeException(e);
2038 }
2039
2040 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002041 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 }
2043
2044 /**
2045 * Ensure that the touch mode for this window is set, and if it is changing,
2046 * take the appropriate action.
2047 * @param inTouchMode Whether we want to be in touch mode.
2048 * @return True if the touch mode changed and focus changed was changed as a result
2049 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002050 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2052 + "touch mode is " + mAttachInfo.mInTouchMode);
2053
2054 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2055
2056 mAttachInfo.mInTouchMode = inTouchMode;
2057 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2058
Romain Guy2d4cff62010-04-09 15:39:00 -07002059 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061
2062 private boolean enterTouchMode() {
2063 if (mView != null) {
2064 if (mView.hasFocus()) {
2065 // note: not relying on mFocusedView here because this could
2066 // be when the window is first being added, and mFocused isn't
2067 // set yet.
2068 final View focused = mView.findFocus();
2069 if (focused != null && !focused.isFocusableInTouchMode()) {
2070
2071 final ViewGroup ancestorToTakeFocus =
2072 findAncestorToTakeFocusInTouchMode(focused);
2073 if (ancestorToTakeFocus != null) {
2074 // there is an ancestor that wants focus after its descendants that
2075 // is focusable in touch mode.. give it focus
2076 return ancestorToTakeFocus.requestFocus();
2077 } else {
2078 // nothing appropriate to have focus in touch mode, clear it out
2079 mView.unFocus();
2080 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2081 mFocusedView = null;
2082 return true;
2083 }
2084 }
2085 }
2086 }
2087 return false;
2088 }
2089
2090
2091 /**
2092 * Find an ancestor of focused that wants focus after its descendants and is
2093 * focusable in touch mode.
2094 * @param focused The currently focused view.
2095 * @return An appropriate view, or null if no such view exists.
2096 */
2097 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2098 ViewParent parent = focused.getParent();
2099 while (parent instanceof ViewGroup) {
2100 final ViewGroup vgParent = (ViewGroup) parent;
2101 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2102 && vgParent.isFocusableInTouchMode()) {
2103 return vgParent;
2104 }
2105 if (vgParent.isRootNamespace()) {
2106 return null;
2107 } else {
2108 parent = vgParent.getParent();
2109 }
2110 }
2111 return null;
2112 }
2113
2114 private boolean leaveTouchMode() {
2115 if (mView != null) {
2116 if (mView.hasFocus()) {
2117 // i learned the hard way to not trust mFocusedView :)
2118 mFocusedView = mView.findFocus();
2119 if (!(mFocusedView instanceof ViewGroup)) {
2120 // some view has focus, let it keep it
2121 return false;
2122 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2123 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2124 // some view group has focus, and doesn't prefer its children
2125 // over itself for focus, so let them keep it.
2126 return false;
2127 }
2128 }
2129
2130 // find the best view to give focus to in this brave new non-touch-mode
2131 // world
2132 final View focused = focusSearch(null, View.FOCUS_DOWN);
2133 if (focused != null) {
2134 return focused.requestFocus(View.FOCUS_DOWN);
2135 }
2136 }
2137 return false;
2138 }
2139
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002140 private void deliverPointerEvent(MotionEvent event) {
2141 if (mTranslator != null) {
2142 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002144
2145 boolean handled;
2146 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002148 // enter touch mode on the down
2149 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2150 if (isDown) {
2151 ensureTouchMode(true);
2152 }
2153 if(Config.LOGV) {
2154 captureMotionLog("captureDispatchPointer", event);
2155 }
2156 if (mCurScrollY != 0) {
2157 event.offsetLocation(0, mCurScrollY);
2158 }
2159 if (MEASURE_LATENCY) {
2160 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2161 }
2162 handled = mView.dispatchTouchEvent(event);
2163 if (MEASURE_LATENCY) {
2164 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2165 }
2166 if (!handled && isDown) {
2167 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2168
2169 final int edgeFlags = event.getEdgeFlags();
2170 int direction = View.FOCUS_UP;
2171 int x = (int)event.getX();
2172 int y = (int)event.getY();
2173 final int[] deltas = new int[2];
2174
2175 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2176 direction = View.FOCUS_DOWN;
2177 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2178 deltas[0] = edgeSlop;
2179 x += edgeSlop;
2180 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2181 deltas[0] = -edgeSlop;
2182 x -= edgeSlop;
2183 }
2184 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2185 direction = View.FOCUS_UP;
2186 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2187 deltas[0] = edgeSlop;
2188 x += edgeSlop;
2189 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2190 deltas[0] = -edgeSlop;
2191 x -= edgeSlop;
2192 }
2193 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2194 direction = View.FOCUS_RIGHT;
2195 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2196 direction = View.FOCUS_LEFT;
2197 }
2198
2199 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2200 View nearest = FocusFinder.getInstance().findNearestTouchable(
2201 ((ViewGroup) mView), x, y, direction, deltas);
2202 if (nearest != null) {
2203 event.offsetLocation(deltas[0], deltas[1]);
2204 event.setEdgeFlags(0);
2205 mView.dispatchTouchEvent(event);
2206 }
2207 }
2208 }
2209 }
2210 }
2211
2212 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2214
2215 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002216 if (mView != null && mAdded) {
2217 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 // If we reach this, we delivered a trackball event to mView and
2220 // mView consumed it. Because we will not translate the trackball
2221 // event into a key event, touch mode will not exit, so we exit
2222 // touch mode here.
2223 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 return;
2225 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002226
2227 // Otherwise we could do something here, like changing the focus
2228 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 }
2230
2231 final TrackballAxis x = mTrackballAxisX;
2232 final TrackballAxis y = mTrackballAxisY;
2233
2234 long curTime = SystemClock.uptimeMillis();
2235 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2236 // It has been too long since the last movement,
2237 // so restart at the beginning.
2238 x.reset(0);
2239 y.reset(0);
2240 mLastTrackballTime = curTime;
2241 }
2242
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002243 final int action = event.getAction();
2244 final int metastate = event.getMetaState();
2245 switch (action) {
2246 case MotionEvent.ACTION_DOWN:
2247 x.reset(2);
2248 y.reset(2);
2249 deliverKeyEvent(new KeyEvent(curTime, curTime,
2250 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2251 0, metastate), false);
2252 break;
2253 case MotionEvent.ACTION_UP:
2254 x.reset(2);
2255 y.reset(2);
2256 deliverKeyEvent(new KeyEvent(curTime, curTime,
2257 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2258 0, metastate), false);
2259 break;
2260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002262 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2263 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2264 + " move=" + event.getX()
2265 + " / Y=" + y.position + " step="
2266 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2267 + " move=" + event.getY());
2268 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2269 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002271 // Generate DPAD events based on the trackball movement.
2272 // We pick the axis that has moved the most as the direction of
2273 // the DPAD. When we generate DPAD events for one axis, then the
2274 // other axis is reset -- we don't want to perform DPAD jumps due
2275 // to slight movements in the trackball when making major movements
2276 // along the other axis.
2277 int keycode = 0;
2278 int movement = 0;
2279 float accel = 1;
2280 if (xOff > yOff) {
2281 movement = x.generate((2/event.getXPrecision()));
2282 if (movement != 0) {
2283 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2284 : KeyEvent.KEYCODE_DPAD_LEFT;
2285 accel = x.acceleration;
2286 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002288 } else if (yOff > 0) {
2289 movement = y.generate((2/event.getYPrecision()));
2290 if (movement != 0) {
2291 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2292 : KeyEvent.KEYCODE_DPAD_UP;
2293 accel = y.acceleration;
2294 x.reset(2);
2295 }
2296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002298 if (keycode != 0) {
2299 if (movement < 0) movement = -movement;
2300 int accelMovement = (int)(movement * accel);
2301 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2302 + " accelMovement=" + accelMovement
2303 + " accel=" + accel);
2304 if (accelMovement > movement) {
2305 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2306 + keycode);
2307 movement--;
2308 deliverKeyEvent(new KeyEvent(curTime, curTime,
2309 KeyEvent.ACTION_MULTIPLE, keycode,
2310 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002312 while (movement > 0) {
2313 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2314 + keycode);
2315 movement--;
2316 curTime = SystemClock.uptimeMillis();
2317 deliverKeyEvent(new KeyEvent(curTime, curTime,
2318 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2319 deliverKeyEvent(new KeyEvent(curTime, curTime,
2320 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002322 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
2324 }
2325
2326 /**
2327 * @param keyCode The key code
2328 * @return True if the key is directional.
2329 */
2330 static boolean isDirectional(int keyCode) {
2331 switch (keyCode) {
2332 case KeyEvent.KEYCODE_DPAD_LEFT:
2333 case KeyEvent.KEYCODE_DPAD_RIGHT:
2334 case KeyEvent.KEYCODE_DPAD_UP:
2335 case KeyEvent.KEYCODE_DPAD_DOWN:
2336 return true;
2337 }
2338 return false;
2339 }
2340
2341 /**
2342 * Returns true if this key is a keyboard key.
2343 * @param keyEvent The key event.
2344 * @return whether this key is a keyboard key.
2345 */
2346 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2347 final int convertedKey = keyEvent.getUnicodeChar();
2348 return convertedKey > 0;
2349 }
2350
2351
2352
2353 /**
2354 * See if the key event means we should leave touch mode (and leave touch
2355 * mode if so).
2356 * @param event The key event.
2357 * @return Whether this key event should be consumed (meaning the act of
2358 * leaving touch mode alone is considered the event).
2359 */
2360 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002361 final int action = event.getAction();
2362 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 return false;
2364 }
2365 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2366 return false;
2367 }
2368
2369 // only relevant if we are in touch mode
2370 if (!mAttachInfo.mInTouchMode) {
2371 return false;
2372 }
2373
2374 // if something like an edit text has focus and the user is typing,
2375 // leave touch mode
2376 //
2377 // note: the condition of not being a keyboard key is kind of a hacky
2378 // approximation of whether we think the focused view will want the
2379 // key; if we knew for sure whether the focused view would consume
2380 // the event, that would be better.
2381 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2382 mFocusedView = mView.findFocus();
2383 if ((mFocusedView instanceof ViewGroup)
2384 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2385 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2386 // something has focus, but is holding it weakly as a container
2387 return false;
2388 }
2389 if (ensureTouchMode(false)) {
2390 throw new IllegalStateException("should not have changed focus "
2391 + "when leaving touch mode while a view has focus.");
2392 }
2393 return false;
2394 }
2395
2396 if (isDirectional(event.getKeyCode())) {
2397 // no view has focus, so we leave touch mode (and find something
2398 // to give focus to). the event is consumed if we were able to
2399 // find something to give focus to.
2400 return ensureTouchMode(false);
2401 }
2402 return false;
2403 }
2404
2405 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002406 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 */
2408 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002409 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 if (ev == null ||
2411 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2412 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 }
Romain Guy8506ab42009-06-11 17:35:47 -07002414
2415 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 sb.append(ev.getDownTime()).append(',');
2417 sb.append(ev.getEventTime()).append(',');
2418 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002419 sb.append(ev.getX()).append(',');
2420 sb.append(ev.getY()).append(',');
2421 sb.append(ev.getPressure()).append(',');
2422 sb.append(ev.getSize()).append(',');
2423 sb.append(ev.getMetaState()).append(',');
2424 sb.append(ev.getXPrecision()).append(',');
2425 sb.append(ev.getYPrecision()).append(',');
2426 sb.append(ev.getDeviceId()).append(',');
2427 sb.append(ev.getEdgeFlags());
2428 Log.d(TAG, sb.toString());
2429 }
2430 /**
2431 * log motion events
2432 */
2433 private static void captureKeyLog(String subTag, KeyEvent ev) {
2434 //check dynamic switch
2435 if (ev == null ||
2436 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2437 return;
2438 }
2439 StringBuilder sb = new StringBuilder(subTag + ": ");
2440 sb.append(ev.getDownTime()).append(',');
2441 sb.append(ev.getEventTime()).append(',');
2442 sb.append(ev.getAction()).append(',');
2443 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 sb.append(ev.getRepeatCount()).append(',');
2445 sb.append(ev.getMetaState()).append(',');
2446 sb.append(ev.getDeviceId()).append(',');
2447 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002448 Log.d(TAG, sb.toString());
2449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450
2451 int enqueuePendingEvent(Object event, boolean sendDone) {
2452 int seq = mPendingEventSeq+1;
2453 if (seq < 0) seq = 0;
2454 mPendingEventSeq = seq;
2455 mPendingEvents.put(seq, event);
2456 return sendDone ? seq : -seq;
2457 }
2458
2459 Object retrievePendingEvent(int seq) {
2460 if (seq < 0) seq = -seq;
2461 Object event = mPendingEvents.get(seq);
2462 if (event != null) {
2463 mPendingEvents.remove(seq);
2464 }
2465 return event;
2466 }
Romain Guy8506ab42009-06-11 17:35:47 -07002467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2469 // If mView is null, we just consume the key event because it doesn't
2470 // make sense to do anything else with it.
2471 boolean handled = mView != null
2472 ? mView.dispatchKeyEventPreIme(event) : true;
2473 if (handled) {
2474 if (sendDone) {
2475 if (LOCAL_LOGV) Log.v(
2476 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002477 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 }
2479 return;
2480 }
2481 // If it is possible for this window to interact with the input
2482 // method window, then we want to first dispatch our key events
2483 // to the input method.
2484 if (mLastWasImTarget) {
2485 InputMethodManager imm = InputMethodManager.peekInstance();
2486 if (imm != null && mView != null) {
2487 int seq = enqueuePendingEvent(event, sendDone);
2488 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2489 + seq + " event=" + event);
2490 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2491 mInputMethodCallback);
2492 return;
2493 }
2494 }
2495 deliverKeyEventToViewHierarchy(event, sendDone);
2496 }
2497
2498 void handleFinishedEvent(int seq, boolean handled) {
2499 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2500 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2501 + " handled=" + handled + " event=" + event);
2502 if (event != null) {
2503 final boolean sendDone = seq >= 0;
2504 if (!handled) {
2505 deliverKeyEventToViewHierarchy(event, sendDone);
2506 return;
2507 } else if (sendDone) {
2508 if (LOCAL_LOGV) Log.v(
2509 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002510 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 } else {
2512 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2513 + " handled=" + handled + " ev=" + event
2514 + ") neither delivering nor finishing key");
2515 }
2516 }
2517 }
Romain Guy8506ab42009-06-11 17:35:47 -07002518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2520 try {
2521 if (mView != null && mAdded) {
2522 final int action = event.getAction();
2523 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2524
2525 if (checkForLeavingTouchModeAndConsume(event)) {
2526 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002527 }
2528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 if (Config.LOGV) {
2530 captureKeyLog("captureDispatchKeyEvent", event);
2531 }
2532 boolean keyHandled = mView.dispatchKeyEvent(event);
2533
2534 if (!keyHandled && isDown) {
2535 int direction = 0;
2536 switch (event.getKeyCode()) {
2537 case KeyEvent.KEYCODE_DPAD_LEFT:
2538 direction = View.FOCUS_LEFT;
2539 break;
2540 case KeyEvent.KEYCODE_DPAD_RIGHT:
2541 direction = View.FOCUS_RIGHT;
2542 break;
2543 case KeyEvent.KEYCODE_DPAD_UP:
2544 direction = View.FOCUS_UP;
2545 break;
2546 case KeyEvent.KEYCODE_DPAD_DOWN:
2547 direction = View.FOCUS_DOWN;
2548 break;
2549 }
2550
2551 if (direction != 0) {
2552
2553 View focused = mView != null ? mView.findFocus() : null;
2554 if (focused != null) {
2555 View v = focused.focusSearch(direction);
2556 boolean focusPassed = false;
2557 if (v != null && v != focused) {
2558 // do the math the get the interesting rect
2559 // of previous focused into the coord system of
2560 // newly focused view
2561 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002562 if (mView instanceof ViewGroup) {
2563 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2564 focused, mTempRect);
2565 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2566 v, mTempRect);
2567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 focusPassed = v.requestFocus(direction, mTempRect);
2569 }
2570
2571 if (!focusPassed) {
2572 mView.dispatchUnhandledMove(focused, direction);
2573 } else {
2574 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2575 }
2576 }
2577 }
2578 }
2579 }
2580
2581 } finally {
2582 if (sendDone) {
2583 if (LOCAL_LOGV) Log.v(
2584 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002585 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587 // Let the exception fall through -- the looper will catch
2588 // it and take care of the bad app for us.
2589 }
2590 }
2591
2592 private AudioManager getAudioManager() {
2593 if (mView == null) {
2594 throw new IllegalStateException("getAudioManager called when there is no mView");
2595 }
2596 if (mAudioManager == null) {
2597 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2598 }
2599 return mAudioManager;
2600 }
2601
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002602 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2603 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002604
2605 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002606 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002607 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002608 restore = true;
2609 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002610 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002611 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002612 if (params != null) {
2613 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002614 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002615 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002616 int relayoutResult = sWindowSession.relayout(
2617 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002618 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2619 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002620 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002621 mPendingContentInsets, mPendingVisibleInsets,
2622 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002623 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002624 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002625 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002626
2627 if (mTranslator != null) {
2628 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2629 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2630 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002631 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002632 return relayoutResult;
2633 }
Romain Guy8506ab42009-06-11 17:35:47 -07002634
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002635 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 * {@inheritDoc}
2637 */
2638 public void playSoundEffect(int effectId) {
2639 checkThread();
2640
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002641 try {
2642 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002644 switch (effectId) {
2645 case SoundEffectConstants.CLICK:
2646 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2647 return;
2648 case SoundEffectConstants.NAVIGATION_DOWN:
2649 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2650 return;
2651 case SoundEffectConstants.NAVIGATION_LEFT:
2652 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2653 return;
2654 case SoundEffectConstants.NAVIGATION_RIGHT:
2655 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2656 return;
2657 case SoundEffectConstants.NAVIGATION_UP:
2658 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2659 return;
2660 default:
2661 throw new IllegalArgumentException("unknown effect id " + effectId +
2662 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2663 }
2664 } catch (IllegalStateException e) {
2665 // Exception thrown by getAudioManager() when mView is null
2666 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2667 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 }
2669 }
2670
2671 /**
2672 * {@inheritDoc}
2673 */
2674 public boolean performHapticFeedback(int effectId, boolean always) {
2675 try {
2676 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2677 } catch (RemoteException e) {
2678 return false;
2679 }
2680 }
2681
2682 /**
2683 * {@inheritDoc}
2684 */
2685 public View focusSearch(View focused, int direction) {
2686 checkThread();
2687 if (!(mView instanceof ViewGroup)) {
2688 return null;
2689 }
2690 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2691 }
2692
2693 public void debug() {
2694 mView.debug();
2695 }
2696
2697 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002698 if (immediate) {
2699 doDie();
2700 } else {
2701 sendEmptyMessage(DIE);
2702 }
2703 }
2704
2705 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 checkThread();
2707 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2708 synchronized (this) {
2709 if (mAdded && !mFirst) {
2710 int viewVisibility = mView.getVisibility();
2711 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2712 if (mWindowAttributesChanged || viewVisibilityChanged) {
2713 // If layout params have been changed, first give them
2714 // to the window manager to make sure it has the correct
2715 // animation info.
2716 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002717 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2718 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 sWindowSession.finishDrawing(mWindow);
2720 }
2721 } catch (RemoteException e) {
2722 }
2723 }
2724
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002725 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 }
2727 if (mAdded) {
2728 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002729 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 }
2731 }
2732 }
2733
2734 public void dispatchFinishedEvent(int seq, boolean handled) {
2735 Message msg = obtainMessage(FINISHED_EVENT);
2736 msg.arg1 = seq;
2737 msg.arg2 = handled ? 1 : 0;
2738 sendMessage(msg);
2739 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002742 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2744 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2745 + " visibleInsets=" + visibleInsets.toShortString()
2746 + " reportDraw=" + reportDraw);
2747 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002748 if (mTranslator != null) {
2749 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2750 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2751 w *= mTranslator.applicationInvertedScale;
2752 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002753 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002754 msg.arg1 = w;
2755 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002756 ResizedInfo ri = new ResizedInfo();
2757 ri.coveredInsets = new Rect(coveredInsets);
2758 ri.visibleInsets = new Rect(visibleInsets);
2759 ri.newConfig = newConfig;
2760 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 sendMessage(msg);
2762 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002763
2764 private Runnable mFinishedCallback;
2765
2766 private final InputHandler mInputHandler = new InputHandler() {
2767 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2768 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002769
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002770 dispatchKey(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002771 }
2772
2773 public void handleTouch(MotionEvent event, Runnable finishedCallback) {
2774 finishedCallback.run();
2775
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002776 dispatchPointer(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002777 }
2778
2779 public void handleTrackball(MotionEvent event, Runnable finishedCallback) {
2780 finishedCallback.run();
2781
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002782 dispatchTrackball(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002783 }
2784 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785
2786 public void dispatchKey(KeyEvent event) {
2787 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2788 //noinspection ConstantConditions
2789 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2790 if (Config.LOGD) Log.d("keydisp",
2791 "===================================================");
2792 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2793 debug();
2794
2795 if (Config.LOGD) Log.d("keydisp",
2796 "===================================================");
2797 }
2798 }
2799
2800 Message msg = obtainMessage(DISPATCH_KEY);
2801 msg.obj = event;
2802
2803 if (LOCAL_LOGV) Log.v(
2804 "ViewRoot", "sending key " + event + " to " + mView);
2805
2806 sendMessageAtTime(msg, event.getEventTime());
2807 }
2808
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002809 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 Message msg = obtainMessage(DISPATCH_POINTER);
2811 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002812 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 }
2814
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002815 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2817 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002818 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 public void dispatchAppVisibility(boolean visible) {
2822 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2823 msg.arg1 = visible ? 1 : 0;
2824 sendMessage(msg);
2825 }
2826
2827 public void dispatchGetNewSurface() {
2828 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2829 sendMessage(msg);
2830 }
2831
2832 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2833 Message msg = Message.obtain();
2834 msg.what = WINDOW_FOCUS_CHANGED;
2835 msg.arg1 = hasFocus ? 1 : 0;
2836 msg.arg2 = inTouchMode ? 1 : 0;
2837 sendMessage(msg);
2838 }
2839
Dianne Hackbornffa42482009-09-23 22:20:11 -07002840 public void dispatchCloseSystemDialogs(String reason) {
2841 Message msg = Message.obtain();
2842 msg.what = CLOSE_SYSTEM_DIALOGS;
2843 msg.obj = reason;
2844 sendMessage(msg);
2845 }
2846
svetoslavganov75986cf2009-05-14 22:28:01 -07002847 /**
2848 * The window is getting focus so if there is anything focused/selected
2849 * send an {@link AccessibilityEvent} to announce that.
2850 */
2851 private void sendAccessibilityEvents() {
2852 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2853 return;
2854 }
2855 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2856 View focusedView = mView.findFocus();
2857 if (focusedView != null && focusedView != mView) {
2858 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2859 }
2860 }
2861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 public boolean showContextMenuForChild(View originalView) {
2863 return false;
2864 }
2865
2866 public void createContextMenu(ContextMenu menu) {
2867 }
2868
2869 public void childDrawableStateChanged(View child) {
2870 }
2871
2872 protected Rect getWindowFrame() {
2873 return mWinFrame;
2874 }
2875
2876 void checkThread() {
2877 if (mThread != Thread.currentThread()) {
2878 throw new CalledFromWrongThreadException(
2879 "Only the original thread that created a view hierarchy can touch its views.");
2880 }
2881 }
2882
2883 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2884 // ViewRoot never intercepts touch event, so this can be a no-op
2885 }
2886
2887 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2888 boolean immediate) {
2889 return scrollToRectOrFocus(rectangle, immediate);
2890 }
Romain Guy8506ab42009-06-11 17:35:47 -07002891
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002892 class TakenSurfaceHolder extends BaseSurfaceHolder {
2893 @Override
2894 public boolean onAllowLockCanvas() {
2895 return mDrawingAllowed;
2896 }
2897
2898 @Override
2899 public void onRelayoutContainer() {
2900 // Not currently interesting -- from changing between fixed and layout size.
2901 }
2902
2903 public void setFormat(int format) {
2904 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2905 }
2906
2907 public void setType(int type) {
2908 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2909 }
2910
2911 @Override
2912 public void onUpdateSurface() {
2913 // We take care of format and type changes on our own.
2914 throw new IllegalStateException("Shouldn't be here");
2915 }
2916
2917 public boolean isCreating() {
2918 return mIsCreating;
2919 }
2920
2921 @Override
2922 public void setFixedSize(int width, int height) {
2923 throw new UnsupportedOperationException(
2924 "Currently only support sizing from layout");
2925 }
2926
2927 public void setKeepScreenOn(boolean screenOn) {
2928 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2929 }
2930 }
2931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 static class InputMethodCallback extends IInputMethodCallback.Stub {
2933 private WeakReference<ViewRoot> mViewRoot;
2934
2935 public InputMethodCallback(ViewRoot viewRoot) {
2936 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2937 }
Romain Guy8506ab42009-06-11 17:35:47 -07002938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 public void finishedEvent(int seq, boolean handled) {
2940 final ViewRoot viewRoot = mViewRoot.get();
2941 if (viewRoot != null) {
2942 viewRoot.dispatchFinishedEvent(seq, handled);
2943 }
2944 }
2945
2946 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2947 // Stub -- not for use in the client.
2948 }
2949 }
Romain Guy8506ab42009-06-11 17:35:47 -07002950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002952 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002954 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2956 }
2957
2958 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002959 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 final ViewRoot viewRoot = mViewRoot.get();
2961 if (viewRoot != null) {
2962 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002963 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 }
2965 }
2966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 public void dispatchAppVisibility(boolean visible) {
2968 final ViewRoot viewRoot = mViewRoot.get();
2969 if (viewRoot != null) {
2970 viewRoot.dispatchAppVisibility(visible);
2971 }
2972 }
2973
2974 public void dispatchGetNewSurface() {
2975 final ViewRoot viewRoot = mViewRoot.get();
2976 if (viewRoot != null) {
2977 viewRoot.dispatchGetNewSurface();
2978 }
2979 }
2980
2981 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2982 final ViewRoot viewRoot = mViewRoot.get();
2983 if (viewRoot != null) {
2984 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2985 }
2986 }
2987
2988 private static int checkCallingPermission(String permission) {
2989 if (!Process.supportsProcesses()) {
2990 return PackageManager.PERMISSION_GRANTED;
2991 }
2992
2993 try {
2994 return ActivityManagerNative.getDefault().checkPermission(
2995 permission, Binder.getCallingPid(), Binder.getCallingUid());
2996 } catch (RemoteException e) {
2997 return PackageManager.PERMISSION_DENIED;
2998 }
2999 }
3000
3001 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3002 final ViewRoot viewRoot = mViewRoot.get();
3003 if (viewRoot != null) {
3004 final View view = viewRoot.mView;
3005 if (view != null) {
3006 if (checkCallingPermission(Manifest.permission.DUMP) !=
3007 PackageManager.PERMISSION_GRANTED) {
3008 throw new SecurityException("Insufficient permissions to invoke"
3009 + " executeCommand() from pid=" + Binder.getCallingPid()
3010 + ", uid=" + Binder.getCallingUid());
3011 }
3012
3013 OutputStream clientStream = null;
3014 try {
3015 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3016 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3017 } catch (IOException e) {
3018 e.printStackTrace();
3019 } finally {
3020 if (clientStream != null) {
3021 try {
3022 clientStream.close();
3023 } catch (IOException e) {
3024 e.printStackTrace();
3025 }
3026 }
3027 }
3028 }
3029 }
3030 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003031
Dianne Hackbornffa42482009-09-23 22:20:11 -07003032 public void closeSystemDialogs(String reason) {
3033 final ViewRoot viewRoot = mViewRoot.get();
3034 if (viewRoot != null) {
3035 viewRoot.dispatchCloseSystemDialogs(reason);
3036 }
3037 }
3038
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003039 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3040 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003041 if (sync) {
3042 try {
3043 sWindowSession.wallpaperOffsetsComplete(asBinder());
3044 } catch (RemoteException e) {
3045 }
3046 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003047 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003048
3049 public void dispatchWallpaperCommand(String action, int x, int y,
3050 int z, Bundle extras, boolean sync) {
3051 if (sync) {
3052 try {
3053 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3054 } catch (RemoteException e) {
3055 }
3056 }
3057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 }
3059
3060 /**
3061 * Maintains state information for a single trackball axis, generating
3062 * discrete (DPAD) movements based on raw trackball motion.
3063 */
3064 static final class TrackballAxis {
3065 /**
3066 * The maximum amount of acceleration we will apply.
3067 */
3068 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 /**
3071 * The maximum amount of time (in milliseconds) between events in order
3072 * for us to consider the user to be doing fast trackball movements,
3073 * and thus apply an acceleration.
3074 */
3075 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 /**
3078 * Scaling factor to the time (in milliseconds) between events to how
3079 * much to multiple/divide the current acceleration. When movement
3080 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3081 * FAST_MOVE_TIME it divides it.
3082 */
3083 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 float position;
3086 float absPosition;
3087 float acceleration = 1;
3088 long lastMoveTime = 0;
3089 int step;
3090 int dir;
3091 int nonAccelMovement;
3092
3093 void reset(int _step) {
3094 position = 0;
3095 acceleration = 1;
3096 lastMoveTime = 0;
3097 step = _step;
3098 dir = 0;
3099 }
3100
3101 /**
3102 * Add trackball movement into the state. If the direction of movement
3103 * has been reversed, the state is reset before adding the
3104 * movement (so that you don't have to compensate for any previously
3105 * collected movement before see the result of the movement in the
3106 * new direction).
3107 *
3108 * @return Returns the absolute value of the amount of movement
3109 * collected so far.
3110 */
3111 float collect(float off, long time, String axis) {
3112 long normTime;
3113 if (off > 0) {
3114 normTime = (long)(off * FAST_MOVE_TIME);
3115 if (dir < 0) {
3116 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3117 position = 0;
3118 step = 0;
3119 acceleration = 1;
3120 lastMoveTime = 0;
3121 }
3122 dir = 1;
3123 } else if (off < 0) {
3124 normTime = (long)((-off) * FAST_MOVE_TIME);
3125 if (dir > 0) {
3126 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3127 position = 0;
3128 step = 0;
3129 acceleration = 1;
3130 lastMoveTime = 0;
3131 }
3132 dir = -1;
3133 } else {
3134 normTime = 0;
3135 }
Romain Guy8506ab42009-06-11 17:35:47 -07003136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 // The number of milliseconds between each movement that is
3138 // considered "normal" and will not result in any acceleration
3139 // or deceleration, scaled by the offset we have here.
3140 if (normTime > 0) {
3141 long delta = time - lastMoveTime;
3142 lastMoveTime = time;
3143 float acc = acceleration;
3144 if (delta < normTime) {
3145 // The user is scrolling rapidly, so increase acceleration.
3146 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3147 if (scale > 1) acc *= scale;
3148 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3149 + off + " normTime=" + normTime + " delta=" + delta
3150 + " scale=" + scale + " acc=" + acc);
3151 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3152 } else {
3153 // The user is scrolling slowly, so decrease acceleration.
3154 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3155 if (scale > 1) acc /= scale;
3156 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3157 + off + " normTime=" + normTime + " delta=" + delta
3158 + " scale=" + scale + " acc=" + acc);
3159 acceleration = acc > 1 ? acc : 1;
3160 }
3161 }
3162 position += off;
3163 return (absPosition = Math.abs(position));
3164 }
3165
3166 /**
3167 * Generate the number of discrete movement events appropriate for
3168 * the currently collected trackball movement.
3169 *
3170 * @param precision The minimum movement required to generate the
3171 * first discrete movement.
3172 *
3173 * @return Returns the number of discrete movements, either positive
3174 * or negative, or 0 if there is not enough trackball movement yet
3175 * for a discrete movement.
3176 */
3177 int generate(float precision) {
3178 int movement = 0;
3179 nonAccelMovement = 0;
3180 do {
3181 final int dir = position >= 0 ? 1 : -1;
3182 switch (step) {
3183 // If we are going to execute the first step, then we want
3184 // to do this as soon as possible instead of waiting for
3185 // a full movement, in order to make things look responsive.
3186 case 0:
3187 if (absPosition < precision) {
3188 return movement;
3189 }
3190 movement += dir;
3191 nonAccelMovement += dir;
3192 step = 1;
3193 break;
3194 // If we have generated the first movement, then we need
3195 // to wait for the second complete trackball motion before
3196 // generating the second discrete movement.
3197 case 1:
3198 if (absPosition < 2) {
3199 return movement;
3200 }
3201 movement += dir;
3202 nonAccelMovement += dir;
3203 position += dir > 0 ? -2 : 2;
3204 absPosition = Math.abs(position);
3205 step = 2;
3206 break;
3207 // After the first two, we generate discrete movements
3208 // consistently with the trackball, applying an acceleration
3209 // if the trackball is moving quickly. This is a simple
3210 // acceleration on top of what we already compute based
3211 // on how quickly the wheel is being turned, to apply
3212 // a longer increasing acceleration to continuous movement
3213 // in one direction.
3214 default:
3215 if (absPosition < 1) {
3216 return movement;
3217 }
3218 movement += dir;
3219 position += dir >= 0 ? -1 : 1;
3220 absPosition = Math.abs(position);
3221 float acc = acceleration;
3222 acc *= 1.1f;
3223 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3224 break;
3225 }
3226 } while (true);
3227 }
3228 }
3229
3230 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3231 public CalledFromWrongThreadException(String msg) {
3232 super(msg);
3233 }
3234 }
3235
3236 private SurfaceHolder mHolder = new SurfaceHolder() {
3237 // we only need a SurfaceHolder for opengl. it would be nice
3238 // to implement everything else though, especially the callback
3239 // support (opengl doesn't make use of it right now, but eventually
3240 // will).
3241 public Surface getSurface() {
3242 return mSurface;
3243 }
3244
3245 public boolean isCreating() {
3246 return false;
3247 }
3248
3249 public void addCallback(Callback callback) {
3250 }
3251
3252 public void removeCallback(Callback callback) {
3253 }
3254
3255 public void setFixedSize(int width, int height) {
3256 }
3257
3258 public void setSizeFromLayout() {
3259 }
3260
3261 public void setFormat(int format) {
3262 }
3263
3264 public void setType(int type) {
3265 }
3266
3267 public void setKeepScreenOn(boolean screenOn) {
3268 }
3269
3270 public Canvas lockCanvas() {
3271 return null;
3272 }
3273
3274 public Canvas lockCanvas(Rect dirty) {
3275 return null;
3276 }
3277
3278 public void unlockCanvasAndPost(Canvas canvas) {
3279 }
3280 public Rect getSurfaceFrame() {
3281 return null;
3282 }
3283 };
3284
3285 static RunQueue getRunQueue() {
3286 RunQueue rq = sRunQueues.get();
3287 if (rq != null) {
3288 return rq;
3289 }
3290 rq = new RunQueue();
3291 sRunQueues.set(rq);
3292 return rq;
3293 }
Romain Guy8506ab42009-06-11 17:35:47 -07003294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 /**
3296 * @hide
3297 */
3298 static final class RunQueue {
3299 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3300
3301 void post(Runnable action) {
3302 postDelayed(action, 0);
3303 }
3304
3305 void postDelayed(Runnable action, long delayMillis) {
3306 HandlerAction handlerAction = new HandlerAction();
3307 handlerAction.action = action;
3308 handlerAction.delay = delayMillis;
3309
3310 synchronized (mActions) {
3311 mActions.add(handlerAction);
3312 }
3313 }
3314
3315 void removeCallbacks(Runnable action) {
3316 final HandlerAction handlerAction = new HandlerAction();
3317 handlerAction.action = action;
3318
3319 synchronized (mActions) {
3320 final ArrayList<HandlerAction> actions = mActions;
3321
3322 while (actions.remove(handlerAction)) {
3323 // Keep going
3324 }
3325 }
3326 }
3327
3328 void executeActions(Handler handler) {
3329 synchronized (mActions) {
3330 final ArrayList<HandlerAction> actions = mActions;
3331 final int count = actions.size();
3332
3333 for (int i = 0; i < count; i++) {
3334 final HandlerAction handlerAction = actions.get(i);
3335 handler.postDelayed(handlerAction.action, handlerAction.delay);
3336 }
3337
Romain Guy15df6702009-08-17 20:17:30 -07003338 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 }
3340 }
3341
3342 private static class HandlerAction {
3343 Runnable action;
3344 long delay;
3345
3346 @Override
3347 public boolean equals(Object o) {
3348 if (this == o) return true;
3349 if (o == null || getClass() != o.getClass()) return false;
3350
3351 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 return !(action != null ? !action.equals(that.action) : that.action != null);
3353
3354 }
3355
3356 @Override
3357 public int hashCode() {
3358 int result = action != null ? action.hashCode() : 0;
3359 result = 31 * result + (int) (delay ^ (delay >>> 32));
3360 return result;
3361 }
3362 }
3363 }
3364
3365 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3366
3367 // inform skia to just abandon its texture cache IDs
3368 // doesn't call glDeleteTextures
3369 private static native void nativeAbandonGlCaches();
3370}