blob: fb45971b046c719f52e787efc1baa338d00f5939 [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();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700455 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700456 }
457 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700458 Resources resources = mView.getContext().getResources();
459 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700460 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700461
462 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700463 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
464 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700465 }
466
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700467 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700468 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700469 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700470 attrs.backup();
471 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700472 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700473 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
474
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700475 if (!compatibilityInfo.supportsScreen()) {
476 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
477 }
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 mSoftInputMode = attrs.softInputMode;
480 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700482 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700483 mAttachInfo.mApplicationScale =
484 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 if (panelParentView != null) {
486 mAttachInfo.mPanelParentWindowToken
487 = panelParentView.getApplicationWindowToken();
488 }
489 mAdded = true;
490 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 // Schedule the first layout -before- adding to the window
493 // manager, to make sure we do the relayout before receiving
494 // any other events from the system.
495 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700496 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700498 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700499 getHostVisibility(), mAttachInfo.mContentInsets,
500 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 } catch (RemoteException e) {
502 mAdded = false;
503 mView = null;
504 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700505 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 unscheduleTraversals();
507 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700508 } finally {
509 if (restore) {
510 attrs.restore();
511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700513
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700514 if (mTranslator != null) {
515 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 mPendingContentInsets.set(mAttachInfo.mContentInsets);
518 mPendingVisibleInsets.set(0, 0, 0, 0);
519 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
520 if (res < WindowManagerImpl.ADD_OKAY) {
521 mView = null;
522 mAttachInfo.mRootView = null;
523 mAdded = false;
524 unscheduleTraversals();
525 switch (res) {
526 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
527 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
528 throw new WindowManagerImpl.BadTokenException(
529 "Unable to add window -- token " + attrs.token
530 + " is not valid; is your activity running?");
531 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
532 throw new WindowManagerImpl.BadTokenException(
533 "Unable to add window -- token " + attrs.token
534 + " is not for an application");
535 case WindowManagerImpl.ADD_APP_EXITING:
536 throw new WindowManagerImpl.BadTokenException(
537 "Unable to add window -- app for token " + attrs.token
538 + " is exiting");
539 case WindowManagerImpl.ADD_DUPLICATE_ADD:
540 throw new WindowManagerImpl.BadTokenException(
541 "Unable to add window -- window " + mWindow
542 + " has already been added");
543 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
544 // Silently ignore -- we would have just removed it
545 // right away, anyway.
546 return;
547 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
548 throw new WindowManagerImpl.BadTokenException(
549 "Unable to add window " + mWindow +
550 " -- another window of this type already exists");
551 case WindowManagerImpl.ADD_PERMISSION_DENIED:
552 throw new WindowManagerImpl.BadTokenException(
553 "Unable to add window " + mWindow +
554 " -- permission denied for this window type");
555 }
556 throw new RuntimeException(
557 "Unable to add window -- unknown error code " + res);
558 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700559
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700560 if (view instanceof RootViewSurfaceTaker) {
561 mInputQueueCallback =
562 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
563 }
564 if (mInputQueueCallback != null) {
565 mInputQueue = new InputQueue(mInputChannel);
566 mInputQueueCallback.onInputQueueCreated(mInputQueue);
567 } else {
568 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
569 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700570 }
571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 view.assignParent(this);
573 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
574 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
575 }
576 }
577 }
578
579 public View getView() {
580 return mView;
581 }
582
583 final WindowLeaked getLocation() {
584 return mLocation;
585 }
586
587 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
588 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700589 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700590 // preserve compatible window flag if exists.
591 int compatibleWindowFlag =
592 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700594 mWindowAttributes.flags |= compatibleWindowFlag;
595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 if (newView) {
597 mSoftInputMode = attrs.softInputMode;
598 requestLayout();
599 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700600 // Don't lose the mode we last auto-computed.
601 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
602 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
603 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
604 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
605 | (oldSoftInputMode
606 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 mWindowAttributesChanged = true;
609 scheduleTraversals();
610 }
611 }
612
613 void handleAppVisibility(boolean visible) {
614 if (mAppVisible != visible) {
615 mAppVisible = visible;
616 scheduleTraversals();
617 }
618 }
619
620 void handleGetNewSurface() {
621 mNewSurfaceNeeded = true;
622 mFullRedrawNeeded = true;
623 scheduleTraversals();
624 }
625
626 /**
627 * {@inheritDoc}
628 */
629 public void requestLayout() {
630 checkThread();
631 mLayoutRequested = true;
632 scheduleTraversals();
633 }
634
635 /**
636 * {@inheritDoc}
637 */
638 public boolean isLayoutRequested() {
639 return mLayoutRequested;
640 }
641
642 public void invalidateChild(View child, Rect dirty) {
643 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700644 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
645 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700647 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700648 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700649 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700650 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700651 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700652 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700653 }
Romain Guy1e095972009-07-07 11:22:45 -0700654 if (mAttachInfo.mScalingRequired) {
655 dirty.inset(-1, -1);
656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 }
658 mDirty.union(dirty);
659 if (!mWillDrawSoon) {
660 scheduleTraversals();
661 }
662 }
663
664 public ViewParent getParent() {
665 return null;
666 }
667
668 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
669 invalidateChild(null, dirty);
670 return null;
671 }
672
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700673 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 if (child != mView) {
675 throw new RuntimeException("child is not mine, honest!");
676 }
677 // Note: don't apply scroll offset, because we want to know its
678 // visibility in the virtual canvas being given to the view hierarchy.
679 return r.intersect(0, 0, mWidth, mHeight);
680 }
681
682 public void bringChildToFront(View child) {
683 }
684
685 public void scheduleTraversals() {
686 if (!mTraversalScheduled) {
687 mTraversalScheduled = true;
688 sendEmptyMessage(DO_TRAVERSAL);
689 }
690 }
691
692 public void unscheduleTraversals() {
693 if (mTraversalScheduled) {
694 mTraversalScheduled = false;
695 removeMessages(DO_TRAVERSAL);
696 }
697 }
698
699 int getHostVisibility() {
700 return mAppVisible ? mView.getVisibility() : View.GONE;
701 }
Romain Guy8506ab42009-06-11 17:35:47 -0700702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 private void performTraversals() {
704 // cache mView since it is used so much below...
705 final View host = mView;
706
707 if (DBG) {
708 System.out.println("======================================");
709 System.out.println("performTraversals");
710 host.debug();
711 }
712
713 if (host == null || !mAdded)
714 return;
715
716 mTraversalScheduled = false;
717 mWillDrawSoon = true;
718 boolean windowResizesToFitContent = false;
719 boolean fullRedrawNeeded = mFullRedrawNeeded;
720 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700721 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 WindowManager.LayoutParams lp = mWindowAttributes;
723
724 int desiredWindowWidth;
725 int desiredWindowHeight;
726 int childWidthMeasureSpec;
727 int childHeightMeasureSpec;
728
729 final View.AttachInfo attachInfo = mAttachInfo;
730
731 final int viewVisibility = getHostVisibility();
732 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
733 || mNewSurfaceNeeded;
734
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700735 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 WindowManager.LayoutParams params = null;
738 if (mWindowAttributesChanged) {
739 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700740 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 params = lp;
742 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700743 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 if (mFirst) {
745 fullRedrawNeeded = true;
746 mLayoutRequested = true;
747
Romain Guy8506ab42009-06-11 17:35:47 -0700748 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700749 mView.getContext().getResources().getDisplayMetrics();
750 desiredWindowWidth = packageMetrics.widthPixels;
751 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
753 // For the very first time, tell the view hierarchy that it
754 // is attached to the window. Note that at this point the surface
755 // object is not initialized to its backing store, but soon it
756 // will be (assuming the window is visible).
757 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700758 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 attachInfo.mHasWindowFocus = false;
760 attachInfo.mWindowVisibility = viewVisibility;
761 attachInfo.mRecomputeGlobalAttributes = false;
762 attachInfo.mKeepScreenOn = false;
763 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700764 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700769 desiredWindowWidth = frame.width();
770 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
772 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700773 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 fullRedrawNeeded = true;
775 mLayoutRequested = true;
776 windowResizesToFitContent = true;
777 }
778 }
779
780 if (viewVisibilityChanged) {
781 attachInfo.mWindowVisibility = viewVisibility;
782 host.dispatchWindowVisibilityChanged(viewVisibility);
783 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
784 if (mUseGL) {
785 destroyGL();
786 }
787 }
788 if (viewVisibility == View.GONE) {
789 // After making a window gone, we will count it as being
790 // shown for the first time the next time it gets focus.
791 mHasHadWindowFocus = false;
792 }
793 }
794
795 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700798 // Execute enqueued actions on every layout in case a view that was detached
799 // enqueued an action after being detached
800 getRunQueue().executeActions(attachInfo.mHandler);
801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 if (mFirst) {
803 host.fitSystemWindows(mAttachInfo.mContentInsets);
804 // make sure touch mode code executes by setting cached value
805 // to opposite of the added touch mode.
806 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700807 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 } else {
809 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
810 mAttachInfo.mContentInsets.set(mPendingContentInsets);
811 host.fitSystemWindows(mAttachInfo.mContentInsets);
812 insetsChanged = true;
813 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
814 + mAttachInfo.mContentInsets);
815 }
816 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
817 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
818 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
819 + mAttachInfo.mVisibleInsets);
820 }
821 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
822 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
823 windowResizesToFitContent = true;
824
Romain Guy8506ab42009-06-11 17:35:47 -0700825 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700826 mView.getContext().getResources().getDisplayMetrics();
827 desiredWindowWidth = packageMetrics.widthPixels;
828 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830 }
831
832 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
833 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
834
835 // Ask host how big it wants to be
836 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
837 "Measuring " + host + " in display " + desiredWindowWidth
838 + "x" + desiredWindowHeight + "...");
839 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
840
841 if (DBG) {
842 System.out.println("======================================");
843 System.out.println("performTraversals -- after measure");
844 host.debug();
845 }
846 }
847
848 if (attachInfo.mRecomputeGlobalAttributes) {
849 //Log.i(TAG, "Computing screen on!");
850 attachInfo.mRecomputeGlobalAttributes = false;
851 boolean oldVal = attachInfo.mKeepScreenOn;
852 attachInfo.mKeepScreenOn = false;
853 host.dispatchCollectViewAttributes(0);
854 if (attachInfo.mKeepScreenOn != oldVal) {
855 params = lp;
856 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
857 }
858 }
859
860 if (mFirst || attachInfo.mViewVisibilityChanged) {
861 attachInfo.mViewVisibilityChanged = false;
862 int resizeMode = mSoftInputMode &
863 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
864 // If we are in auto resize mode, then we need to determine
865 // what mode to use now.
866 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
867 final int N = attachInfo.mScrollContainers.size();
868 for (int i=0; i<N; i++) {
869 if (attachInfo.mScrollContainers.get(i).isShown()) {
870 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
871 }
872 }
873 if (resizeMode == 0) {
874 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
875 }
876 if ((lp.softInputMode &
877 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
878 lp.softInputMode = (lp.softInputMode &
879 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
880 resizeMode;
881 params = lp;
882 }
883 }
884 }
Romain Guy8506ab42009-06-11 17:35:47 -0700885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
887 if (!PixelFormat.formatHasAlpha(params.format)) {
888 params.format = PixelFormat.TRANSLUCENT;
889 }
890 }
891
892 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700893 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
894 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
895 frame.width() < desiredWindowWidth && frame.width() != mWidth)
896 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
897 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898
899 final boolean computesInternalInsets =
900 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
901 boolean insetsPending = false;
902 int relayoutResult = 0;
903 if (mFirst || windowShouldResize || insetsChanged
904 || viewVisibilityChanged || params != null) {
905
906 if (viewVisibility == View.VISIBLE) {
907 // If this window is giving internal insets to the window
908 // manager, and it is being added or changing its visibility,
909 // then we want to first give the window manager "fake"
910 // insets to cause it to effectively ignore the content of
911 // the window during layout. This avoids it briefly causing
912 // other windows to resize/move based on the raw frame of the
913 // window, waiting until we can finish laying out this window
914 // and get back to the window manager with the ultimately
915 // computed insets.
916 insetsPending = computesInternalInsets
917 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
920 if (params == null) {
921 params = mWindowAttributes;
922 }
923 mGlWanted = true;
924 }
925 }
926
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700927 if (mSurfaceHolder != null) {
928 mSurfaceHolder.mSurfaceLock.lock();
929 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700930 }
931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 boolean initialized = false;
933 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700934 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700935 boolean hadSurface = mSurface.isValid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 int fl = 0;
938 if (params != null) {
939 fl = params.flags;
940 if (attachInfo.mKeepScreenOn) {
941 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
942 }
943 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700944 if (DEBUG_LAYOUT) {
945 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
946 host.mMeasuredHeight + ", params=" + params);
947 }
948 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 if (params != null) {
951 params.flags = fl;
952 }
953
954 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
955 + " content=" + mPendingContentInsets.toShortString()
956 + " visible=" + mPendingVisibleInsets.toShortString()
957 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700958
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700959 if (mPendingConfiguration.seq != 0) {
960 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
961 + mPendingConfiguration);
962 updateConfiguration(mPendingConfiguration, !mFirst);
963 mPendingConfiguration.seq = 0;
964 }
965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 contentInsetsChanged = !mPendingContentInsets.equals(
967 mAttachInfo.mContentInsets);
968 visibleInsetsChanged = !mPendingVisibleInsets.equals(
969 mAttachInfo.mVisibleInsets);
970 if (contentInsetsChanged) {
971 mAttachInfo.mContentInsets.set(mPendingContentInsets);
972 host.fitSystemWindows(mAttachInfo.mContentInsets);
973 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
974 + mAttachInfo.mContentInsets);
975 }
976 if (visibleInsetsChanged) {
977 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
978 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
979 + mAttachInfo.mVisibleInsets);
980 }
981
982 if (!hadSurface) {
983 if (mSurface.isValid()) {
984 // If we are creating a new surface, then we need to
985 // completely redraw it. Also, when we get to the
986 // point of drawing it we will hold off and schedule
987 // a new traversal instead. This is so we can tell the
988 // window manager about all of the windows being displayed
989 // before actually drawing them, so it can display then
990 // all at once.
991 newSurface = true;
992 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700993 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 if (mGlWanted && !mUseGL) {
996 initializeGL();
997 initialized = mGlCanvas != null;
998 }
999 }
1000 } else if (!mSurface.isValid()) {
1001 // If the surface has been removed, then reset the scroll
1002 // positions.
1003 mLastScrolledFocus = null;
1004 mScrollY = mCurScrollY = 0;
1005 if (mScroller != null) {
1006 mScroller.abortAnimation();
1007 }
1008 }
1009 } catch (RemoteException e) {
1010 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001013 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014
1015 attachInfo.mWindowLeft = frame.left;
1016 attachInfo.mWindowTop = frame.top;
1017
1018 // !!FIXME!! This next section handles the case where we did not get the
1019 // window size we asked for. We should avoid this by getting a maximum size from
1020 // the window session beforehand.
1021 mWidth = frame.width();
1022 mHeight = frame.height();
1023
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001024 if (mSurfaceHolder != null) {
1025 // The app owns the surface; tell it about what is going on.
1026 if (mSurface.isValid()) {
1027 // XXX .copyFrom() doesn't work!
1028 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1029 mSurfaceHolder.mSurface = mSurface;
1030 }
1031 mSurfaceHolder.mSurfaceLock.unlock();
1032 if (mSurface.isValid()) {
1033 if (!hadSurface) {
1034 mSurfaceHolder.ungetCallbacks();
1035
1036 mIsCreating = true;
1037 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1038 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1039 if (callbacks != null) {
1040 for (SurfaceHolder.Callback c : callbacks) {
1041 c.surfaceCreated(mSurfaceHolder);
1042 }
1043 }
1044 surfaceChanged = true;
1045 }
1046 if (surfaceChanged) {
1047 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1048 lp.format, mWidth, mHeight);
1049 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1050 if (callbacks != null) {
1051 for (SurfaceHolder.Callback c : callbacks) {
1052 c.surfaceChanged(mSurfaceHolder, lp.format,
1053 mWidth, mHeight);
1054 }
1055 }
1056 }
1057 mIsCreating = false;
1058 } else if (hadSurface) {
1059 mSurfaceHolder.ungetCallbacks();
1060 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1061 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1062 if (callbacks != null) {
1063 for (SurfaceHolder.Callback c : callbacks) {
1064 c.surfaceDestroyed(mSurfaceHolder);
1065 }
1066 }
1067 mSurfaceHolder.mSurfaceLock.lock();
1068 // Make surface invalid.
1069 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1070 mSurfaceHolder.mSurface = new Surface();
1071 mSurfaceHolder.mSurfaceLock.unlock();
1072 }
1073 }
1074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001076 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
1077 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
1079
1080 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001081 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1083 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1084 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1085 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1086
1087 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1088 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1089 + " mHeight=" + mHeight
1090 + " measuredHeight" + host.mMeasuredHeight
1091 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 // Ask host how big it wants to be
1094 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1095
1096 // Implementation of weights from WindowManager.LayoutParams
1097 // We just grow the dimensions as needed and re-measure if
1098 // needs be
1099 int width = host.mMeasuredWidth;
1100 int height = host.mMeasuredHeight;
1101 boolean measureAgain = false;
1102
1103 if (lp.horizontalWeight > 0.0f) {
1104 width += (int) ((mWidth - width) * lp.horizontalWeight);
1105 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1106 MeasureSpec.EXACTLY);
1107 measureAgain = true;
1108 }
1109 if (lp.verticalWeight > 0.0f) {
1110 height += (int) ((mHeight - height) * lp.verticalWeight);
1111 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1112 MeasureSpec.EXACTLY);
1113 measureAgain = true;
1114 }
1115
1116 if (measureAgain) {
1117 if (DEBUG_LAYOUT) Log.v(TAG,
1118 "And hey let's measure once more: width=" + width
1119 + " height=" + height);
1120 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1121 }
1122
1123 mLayoutRequested = true;
1124 }
1125 }
1126
1127 final boolean didLayout = mLayoutRequested;
1128 boolean triggerGlobalLayoutListener = didLayout
1129 || attachInfo.mRecomputeGlobalAttributes;
1130 if (didLayout) {
1131 mLayoutRequested = false;
1132 mScrollMayChange = true;
1133 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1134 "ViewRoot", "Laying out " + host + " to (" +
1135 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001136 long startTime = 0L;
1137 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 startTime = SystemClock.elapsedRealtime();
1139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1141
Romain Guy13922e02009-05-12 17:56:14 -07001142 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1143 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1144 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1145 + "please refer to the logs with the tag "
1146 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1147 }
1148 }
1149
1150 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1152 }
1153
1154 // By this point all views have been sized and positionned
1155 // We can compute the transparent area
1156
1157 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1158 // start out transparent
1159 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1160 host.getLocationInWindow(mTmpLocation);
1161 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1162 mTmpLocation[0] + host.mRight - host.mLeft,
1163 mTmpLocation[1] + host.mBottom - host.mTop);
1164
1165 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001166 if (mTranslator != null) {
1167 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1168 }
1169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1171 mPreviousTransparentRegion.set(mTransparentRegion);
1172 // reconfigure window manager
1173 try {
1174 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1175 } catch (RemoteException e) {
1176 }
1177 }
1178 }
1179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 if (DBG) {
1181 System.out.println("======================================");
1182 System.out.println("performTraversals -- after setFrame");
1183 host.debug();
1184 }
1185 }
1186
1187 if (triggerGlobalLayoutListener) {
1188 attachInfo.mRecomputeGlobalAttributes = false;
1189 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1190 }
1191
1192 if (computesInternalInsets) {
1193 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1194 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1195 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1196 givenContent.left = givenContent.top = givenContent.right
1197 = givenContent.bottom = givenVisible.left = givenVisible.top
1198 = givenVisible.right = givenVisible.bottom = 0;
1199 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001200 Rect contentInsets = insets.contentInsets;
1201 Rect visibleInsets = insets.visibleInsets;
1202 if (mTranslator != null) {
1203 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1204 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1207 mLastGivenInsets.set(insets);
1208 try {
1209 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001210 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 } catch (RemoteException e) {
1212 }
1213 }
1214 }
Romain Guy8506ab42009-06-11 17:35:47 -07001215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 if (mFirst) {
1217 // handle first focus request
1218 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1219 + mView.hasFocus());
1220 if (mView != null) {
1221 if (!mView.hasFocus()) {
1222 mView.requestFocus(View.FOCUS_FORWARD);
1223 mFocusedView = mRealFocusedView = mView.findFocus();
1224 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1225 + mFocusedView);
1226 } else {
1227 mRealFocusedView = mView.findFocus();
1228 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1229 + mRealFocusedView);
1230 }
1231 }
1232 }
1233
1234 mFirst = false;
1235 mWillDrawSoon = false;
1236 mNewSurfaceNeeded = false;
1237 mViewVisibility = viewVisibility;
1238
1239 if (mAttachInfo.mHasWindowFocus) {
1240 final boolean imTarget = WindowManager.LayoutParams
1241 .mayUseInputMethod(mWindowAttributes.flags);
1242 if (imTarget != mLastWasImTarget) {
1243 mLastWasImTarget = imTarget;
1244 InputMethodManager imm = InputMethodManager.peekInstance();
1245 if (imm != null && imTarget) {
1246 imm.startGettingWindowFocus(mView);
1247 imm.onWindowFocus(mView, mView.findFocus(),
1248 mWindowAttributes.softInputMode,
1249 !mHasHadWindowFocus, mWindowAttributes.flags);
1250 }
1251 }
1252 }
Romain Guy8506ab42009-06-11 17:35:47 -07001253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1255
1256 if (!cancelDraw && !newSurface) {
1257 mFullRedrawNeeded = false;
1258 draw(fullRedrawNeeded);
1259
1260 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1261 || mReportNextDraw) {
1262 if (LOCAL_LOGV) {
1263 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1264 }
1265 mReportNextDraw = false;
1266 try {
1267 sWindowSession.finishDrawing(mWindow);
1268 } catch (RemoteException e) {
1269 }
1270 }
1271 } else {
1272 // We were supposed to report when we are done drawing. Since we canceled the
1273 // draw, remember it here.
1274 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1275 mReportNextDraw = true;
1276 }
1277 if (fullRedrawNeeded) {
1278 mFullRedrawNeeded = true;
1279 }
1280 // Try again
1281 scheduleTraversals();
1282 }
1283 }
1284
1285 public void requestTransparentRegion(View child) {
1286 // the test below should not fail unless someone is messing with us
1287 checkThread();
1288 if (mView == child) {
1289 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1290 // Need to make sure we re-evaluate the window attributes next
1291 // time around, to ensure the window has the correct format.
1292 mWindowAttributesChanged = true;
1293 }
1294 }
1295
1296 /**
1297 * Figures out the measure spec for the root view in a window based on it's
1298 * layout params.
1299 *
1300 * @param windowSize
1301 * The available width or height of the window
1302 *
1303 * @param rootDimension
1304 * The layout params for one dimension (width or height) of the
1305 * window.
1306 *
1307 * @return The measure spec to use to measure the root view.
1308 */
1309 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1310 int measureSpec;
1311 switch (rootDimension) {
1312
Romain Guy980a9382010-01-08 15:06:28 -08001313 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 // Window can't resize. Force root view to be windowSize.
1315 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1316 break;
1317 case ViewGroup.LayoutParams.WRAP_CONTENT:
1318 // Window can resize. Set max size for root view.
1319 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1320 break;
1321 default:
1322 // Window wants to be an exact size. Force root view to be that size.
1323 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1324 break;
1325 }
1326 return measureSpec;
1327 }
1328
1329 private void draw(boolean fullRedrawNeeded) {
1330 Surface surface = mSurface;
1331 if (surface == null || !surface.isValid()) {
1332 return;
1333 }
1334
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001335 if (!sFirstDrawComplete) {
1336 synchronized (sFirstDrawHandlers) {
1337 sFirstDrawComplete = true;
1338 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1339 post(sFirstDrawHandlers.get(i));
1340 }
1341 }
1342 }
1343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 scrollToRectOrFocus(null, false);
1345
1346 if (mAttachInfo.mViewScrollChanged) {
1347 mAttachInfo.mViewScrollChanged = false;
1348 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1349 }
Romain Guy8506ab42009-06-11 17:35:47 -07001350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001352 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 if (scrolling) {
1354 yoff = mScroller.getCurrY();
1355 } else {
1356 yoff = mScrollY;
1357 }
1358 if (mCurScrollY != yoff) {
1359 mCurScrollY = yoff;
1360 fullRedrawNeeded = true;
1361 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001362 float appScale = mAttachInfo.mApplicationScale;
1363 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364
1365 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001366 if (mSurfaceHolder != null) {
1367 // The app owns the surface, we won't draw.
1368 dirty.setEmpty();
1369 return;
1370 }
1371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 if (mUseGL) {
1373 if (!dirty.isEmpty()) {
1374 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001375 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 mGL.glDisable(GL_SCISSOR_TEST);
1377 mGL.glClearColor(0, 0, 0, 0);
1378 mGL.glClear(GL_COLOR_BUFFER_BIT);
1379 mGL.glEnable(GL_SCISSOR_TEST);
1380
1381 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001382 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001384
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001385 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1386 try {
1387 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001388 if (mTranslator != null) {
1389 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001390 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001391 canvas.setScreenDensity(scalingRequired
1392 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001393 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001394 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1395 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1396 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001397 } finally {
1398 canvas.restoreToCount(saveCount);
1399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400
Romain Guy5bcdff42009-05-14 21:27:18 -07001401 mAttachInfo.mIgnoreDirtyState = false;
1402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1404 checkEglErrors();
1405
Mike Reedfd716532009-10-12 14:42:56 -04001406 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 int now = (int)SystemClock.elapsedRealtime();
1408 if (sDrawTime != 0) {
1409 nativeShowFPS(canvas, now - sDrawTime);
1410 }
1411 sDrawTime = now;
1412 }
1413 }
1414 }
1415 if (scrolling) {
1416 mFullRedrawNeeded = true;
1417 scheduleTraversals();
1418 }
1419 return;
1420 }
1421
Romain Guy5bcdff42009-05-14 21:27:18 -07001422 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001423 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001424 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426
1427 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1428 Log.v("ViewRoot", "Draw " + mView + "/"
1429 + mWindowAttributes.getTitle()
1430 + ": dirty={" + dirty.left + "," + dirty.top
1431 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001432 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1433 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001436 if (!dirty.isEmpty() || mIsAnimating) {
1437 Canvas canvas;
1438 try {
1439 int left = dirty.left;
1440 int top = dirty.top;
1441 int right = dirty.right;
1442 int bottom = dirty.bottom;
1443 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001444
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001445 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1446 bottom != dirty.bottom) {
1447 mAttachInfo.mIgnoreDirtyState = true;
1448 }
1449
1450 // TODO: Do this in native
1451 canvas.setDensity(mDensity);
1452 } catch (Surface.OutOfResourcesException e) {
1453 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1454 // TODO: we should ask the window manager to do something!
1455 // for now we just do nothing
1456 return;
1457 } catch (IllegalArgumentException e) {
1458 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1459 // TODO: we should ask the window manager to do something!
1460 // for now we just do nothing
1461 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001462 }
1463
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001464 try {
1465 if (!dirty.isEmpty() || mIsAnimating) {
1466 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001468 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1469 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1470 + canvas.getWidth() + ", h=" + canvas.getHeight());
1471 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001474 if (Config.DEBUG && ViewDebug.profileDrawing) {
1475 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001477
1478 // If this bitmap's format includes an alpha channel, we
1479 // need to clear it before drawing so that the child will
1480 // properly re-composite its drawing on a transparent
1481 // background. This automatically respects the clip/dirty region
1482 // or
1483 // If we are applying an offset, we need to clear the area
1484 // where the offset doesn't appear to avoid having garbage
1485 // left in the blank areas.
1486 if (!canvas.isOpaque() || yoff != 0) {
1487 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1488 }
1489
1490 dirty.setEmpty();
1491 mIsAnimating = false;
1492 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1493 mView.mPrivateFlags |= View.DRAWN;
1494
1495 if (DEBUG_DRAW) {
1496 Context cxt = mView.getContext();
1497 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1498 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1499 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1500 }
1501 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1502 try {
1503 canvas.translate(0, -yoff);
1504 if (mTranslator != null) {
1505 mTranslator.translateCanvas(canvas);
1506 }
1507 canvas.setScreenDensity(scalingRequired
1508 ? DisplayMetrics.DENSITY_DEVICE : 0);
1509 mView.draw(canvas);
1510 } finally {
1511 mAttachInfo.mIgnoreDirtyState = false;
1512 canvas.restoreToCount(saveCount);
1513 }
1514
1515 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1516 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1517 }
1518
1519 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1520 int now = (int)SystemClock.elapsedRealtime();
1521 if (sDrawTime != 0) {
1522 nativeShowFPS(canvas, now - sDrawTime);
1523 }
1524 sDrawTime = now;
1525 }
1526
1527 if (Config.DEBUG && ViewDebug.profileDrawing) {
1528 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001532 } finally {
1533 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
1536
1537 if (LOCAL_LOGV) {
1538 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1539 }
Romain Guy8506ab42009-06-11 17:35:47 -07001540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 if (scrolling) {
1542 mFullRedrawNeeded = true;
1543 scheduleTraversals();
1544 }
1545 }
1546
1547 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1548 final View.AttachInfo attachInfo = mAttachInfo;
1549 final Rect ci = attachInfo.mContentInsets;
1550 final Rect vi = attachInfo.mVisibleInsets;
1551 int scrollY = 0;
1552 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 if (vi.left > ci.left || vi.top > ci.top
1555 || vi.right > ci.right || vi.bottom > ci.bottom) {
1556 // We'll assume that we aren't going to change the scroll
1557 // offset, since we want to avoid that unless it is actually
1558 // going to make the focus visible... otherwise we scroll
1559 // all over the place.
1560 scrollY = mScrollY;
1561 // We can be called for two different situations: during a draw,
1562 // to update the scroll position if the focus has changed (in which
1563 // case 'rectangle' is null), or in response to a
1564 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1565 // is non-null and we just want to scroll to whatever that
1566 // rectangle is).
1567 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001568
1569 // When in touch mode, focus points to the previously focused view,
1570 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001571 // line checks whether the view is still in our hierarchy.
1572 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001573 mRealFocusedView = null;
1574 return false;
1575 }
1576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 if (focus != mLastScrolledFocus) {
1578 // If the focus has changed, then ignore any requests to scroll
1579 // to a rectangle; first we want to make sure the entire focus
1580 // view is visible.
1581 rectangle = null;
1582 }
1583 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1584 + " rectangle=" + rectangle + " ci=" + ci
1585 + " vi=" + vi);
1586 if (focus == mLastScrolledFocus && !mScrollMayChange
1587 && rectangle == null) {
1588 // Optimization: if the focus hasn't changed since last
1589 // time, and no layout has happened, then just leave things
1590 // as they are.
1591 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1592 + mScrollY + " vi=" + vi.toShortString());
1593 } else if (focus != null) {
1594 // We need to determine if the currently focused view is
1595 // within the visible part of the window and, if not, apply
1596 // a pan so it can be seen.
1597 mLastScrolledFocus = focus;
1598 mScrollMayChange = false;
1599 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1600 // Try to find the rectangle from the focus view.
1601 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1602 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1603 + mView.getWidth() + " h=" + mView.getHeight()
1604 + " ci=" + ci.toShortString()
1605 + " vi=" + vi.toShortString());
1606 if (rectangle == null) {
1607 focus.getFocusedRect(mTempRect);
1608 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1609 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001610 if (mView instanceof ViewGroup) {
1611 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1612 focus, mTempRect);
1613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1615 "Focus in window: focusRect="
1616 + mTempRect.toShortString()
1617 + " visRect=" + mVisRect.toShortString());
1618 } else {
1619 mTempRect.set(rectangle);
1620 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1621 "Request scroll to rect: "
1622 + mTempRect.toShortString()
1623 + " visRect=" + mVisRect.toShortString());
1624 }
1625 if (mTempRect.intersect(mVisRect)) {
1626 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1627 "Focus window visible rect: "
1628 + mTempRect.toShortString());
1629 if (mTempRect.height() >
1630 (mView.getHeight()-vi.top-vi.bottom)) {
1631 // If the focus simply is not going to fit, then
1632 // best is probably just to leave things as-is.
1633 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1634 "Too tall; leaving scrollY=" + scrollY);
1635 } else if ((mTempRect.top-scrollY) < vi.top) {
1636 scrollY -= vi.top - (mTempRect.top-scrollY);
1637 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1638 "Top covered; scrollY=" + scrollY);
1639 } else if ((mTempRect.bottom-scrollY)
1640 > (mView.getHeight()-vi.bottom)) {
1641 scrollY += (mTempRect.bottom-scrollY)
1642 - (mView.getHeight()-vi.bottom);
1643 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1644 "Bottom covered; scrollY=" + scrollY);
1645 }
1646 handled = true;
1647 }
1648 }
1649 }
1650 }
Romain Guy8506ab42009-06-11 17:35:47 -07001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if (scrollY != mScrollY) {
1653 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1654 + mScrollY + " , new=" + scrollY);
1655 if (!immediate) {
1656 if (mScroller == null) {
1657 mScroller = new Scroller(mView.getContext());
1658 }
1659 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1660 } else if (mScroller != null) {
1661 mScroller.abortAnimation();
1662 }
1663 mScrollY = scrollY;
1664 }
Romain Guy8506ab42009-06-11 17:35:47 -07001665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 return handled;
1667 }
Romain Guy8506ab42009-06-11 17:35:47 -07001668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 public void requestChildFocus(View child, View focused) {
1670 checkThread();
1671 if (mFocusedView != focused) {
1672 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1673 scheduleTraversals();
1674 }
1675 mFocusedView = mRealFocusedView = focused;
1676 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1677 + mFocusedView);
1678 }
1679
1680 public void clearChildFocus(View child) {
1681 checkThread();
1682
1683 View oldFocus = mFocusedView;
1684
1685 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1686 mFocusedView = mRealFocusedView = null;
1687 if (mView != null && !mView.hasFocus()) {
1688 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1689 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1690 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1691 }
1692 } else if (oldFocus != null) {
1693 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1694 }
1695 }
1696
1697
1698 public void focusableViewAvailable(View v) {
1699 checkThread();
1700
1701 if (mView != null && !mView.hasFocus()) {
1702 v.requestFocus();
1703 } else {
1704 // the one case where will transfer focus away from the current one
1705 // is if the current view is a view group that prefers to give focus
1706 // to its children first AND the view is a descendant of it.
1707 mFocusedView = mView.findFocus();
1708 boolean descendantsHaveDibsOnFocus =
1709 (mFocusedView instanceof ViewGroup) &&
1710 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1711 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1712 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1713 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1714 v.requestFocus();
1715 }
1716 }
1717 }
1718
1719 public void recomputeViewAttributes(View child) {
1720 checkThread();
1721 if (mView == child) {
1722 mAttachInfo.mRecomputeGlobalAttributes = true;
1723 if (!mWillDrawSoon) {
1724 scheduleTraversals();
1725 }
1726 }
1727 }
1728
1729 void dispatchDetachedFromWindow() {
1730 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1731
1732 if (mView != null) {
1733 mView.dispatchDetachedFromWindow();
1734 }
1735
1736 mView = null;
1737 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001738 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739
1740 if (mUseGL) {
1741 destroyGL();
1742 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001743 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001745 if (mInputChannel != null) {
1746 if (mInputQueueCallback != null) {
1747 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1748 mInputQueueCallback = null;
1749 } else {
1750 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001751 }
1752 }
1753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 try {
1755 sWindowSession.remove(mWindow);
1756 } catch (RemoteException e) {
1757 }
Jeff Brown349703e2010-06-22 01:27:15 -07001758
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001759 // Dispose the input channel after removing the window so the Window Manager
1760 // doesn't interpret the input channel being closed as an abnormal termination.
1761 if (mInputChannel != null) {
1762 mInputChannel.dispose();
1763 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
Romain Guy8506ab42009-06-11 17:35:47 -07001766
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001767 void updateConfiguration(Configuration config, boolean force) {
1768 if (DEBUG_CONFIGURATION) Log.v(TAG,
1769 "Applying new config to window "
1770 + mWindowAttributes.getTitle()
1771 + ": " + config);
1772 synchronized (sConfigCallbacks) {
1773 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1774 sConfigCallbacks.get(i).onConfigurationChanged(config);
1775 }
1776 }
1777 if (mView != null) {
1778 // At this point the resources have been updated to
1779 // have the most recent config, whatever that is. Use
1780 // the on in them which may be newer.
1781 if (mView != null) {
1782 config = mView.getResources().getConfiguration();
1783 }
1784 if (force || mLastConfiguration.diff(config) != 0) {
1785 mLastConfiguration.setTo(config);
1786 mView.dispatchConfigurationChanged(config);
1787 }
1788 }
1789 }
1790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 /**
1792 * Return true if child is an ancestor of parent, (or equal to the parent).
1793 */
1794 private static boolean isViewDescendantOf(View child, View parent) {
1795 if (child == parent) {
1796 return true;
1797 }
1798
1799 final ViewParent theParent = child.getParent();
1800 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1801 }
1802
Romain Guycdb86672010-03-18 18:54:50 -07001803 private static void forceLayout(View view) {
1804 view.forceLayout();
1805 if (view instanceof ViewGroup) {
1806 ViewGroup group = (ViewGroup) view;
1807 final int count = group.getChildCount();
1808 for (int i = 0; i < count; i++) {
1809 forceLayout(group.getChildAt(i));
1810 }
1811 }
1812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813
1814 public final static int DO_TRAVERSAL = 1000;
1815 public final static int DIE = 1001;
1816 public final static int RESIZED = 1002;
1817 public final static int RESIZED_REPORT = 1003;
1818 public final static int WINDOW_FOCUS_CHANGED = 1004;
1819 public final static int DISPATCH_KEY = 1005;
1820 public final static int DISPATCH_POINTER = 1006;
1821 public final static int DISPATCH_TRACKBALL = 1007;
1822 public final static int DISPATCH_APP_VISIBILITY = 1008;
1823 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1824 public final static int FINISHED_EVENT = 1010;
1825 public final static int DISPATCH_KEY_FROM_IME = 1011;
1826 public final static int FINISH_INPUT_CONNECTION = 1012;
1827 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001828 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829
1830 @Override
1831 public void handleMessage(Message msg) {
1832 switch (msg.what) {
1833 case View.AttachInfo.INVALIDATE_MSG:
1834 ((View) msg.obj).invalidate();
1835 break;
1836 case View.AttachInfo.INVALIDATE_RECT_MSG:
1837 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1838 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1839 info.release();
1840 break;
1841 case DO_TRAVERSAL:
1842 if (mProfile) {
1843 Debug.startMethodTracing("ViewRoot");
1844 }
1845
1846 performTraversals();
1847
1848 if (mProfile) {
1849 Debug.stopMethodTracing();
1850 mProfile = false;
1851 }
1852 break;
1853 case FINISHED_EVENT:
1854 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1855 break;
1856 case DISPATCH_KEY:
1857 if (LOCAL_LOGV) Log.v(
1858 "ViewRoot", "Dispatching key "
1859 + msg.obj + " to " + mView);
1860 deliverKeyEvent((KeyEvent)msg.obj, true);
1861 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001862 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001863 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001865 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001867 event.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001870 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001871 case DISPATCH_TRACKBALL: {
1872 MotionEvent event = (MotionEvent) msg.obj;
1873 try {
1874 deliverTrackballEvent(event);
1875 } finally {
1876 event.recycle();
1877 }
1878 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 case DISPATCH_APP_VISIBILITY:
1880 handleAppVisibility(msg.arg1 != 0);
1881 break;
1882 case DISPATCH_GET_NEW_SURFACE:
1883 handleGetNewSurface();
1884 break;
1885 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001886 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001889 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001890 && mPendingVisibleInsets.equals(ri.visibleInsets)
1891 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 break;
1893 }
1894 // fall through...
1895 case RESIZED_REPORT:
1896 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001897 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1898 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001899 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 mWinFrame.left = 0;
1902 mWinFrame.right = msg.arg1;
1903 mWinFrame.top = 0;
1904 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001905 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1906 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 if (msg.what == RESIZED_REPORT) {
1908 mReportNextDraw = true;
1909 }
Romain Guycdb86672010-03-18 18:54:50 -07001910
1911 if (mView != null) {
1912 forceLayout(mView);
1913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 requestLayout();
1915 }
1916 break;
1917 case WINDOW_FOCUS_CHANGED: {
1918 if (mAdded) {
1919 boolean hasWindowFocus = msg.arg1 != 0;
1920 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1921 if (hasWindowFocus) {
1922 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001923 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924
1925 if (mGlWanted) {
1926 checkEglErrors();
1927 // we lost the gl context, so recreate it.
1928 if (mGlWanted && !mUseGL) {
1929 initializeGL();
1930 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001931 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001932 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001933 (int) (mWidth * appScale + 0.5f),
1934 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
1936 }
1937 }
1938 }
Romain Guy8506ab42009-06-11 17:35:47 -07001939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 mLastWasImTarget = WindowManager.LayoutParams
1941 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 InputMethodManager imm = InputMethodManager.peekInstance();
1944 if (mView != null) {
1945 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1946 imm.startGettingWindowFocus(mView);
1947 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001948 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 mView.dispatchWindowFocusChanged(hasWindowFocus);
1950 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 // Note: must be done after the focus change callbacks,
1953 // so all of the view state is set up correctly.
1954 if (hasWindowFocus) {
1955 if (imm != null && mLastWasImTarget) {
1956 imm.onWindowFocus(mView, mView.findFocus(),
1957 mWindowAttributes.softInputMode,
1958 !mHasHadWindowFocus, mWindowAttributes.flags);
1959 }
1960 // Clear the forward bit. We can just do this directly, since
1961 // the window manager doesn't care about it.
1962 mWindowAttributes.softInputMode &=
1963 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1964 ((WindowManager.LayoutParams)mView.getLayoutParams())
1965 .softInputMode &=
1966 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1967 mHasHadWindowFocus = true;
1968 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001969
1970 if (hasWindowFocus && mView != null) {
1971 sendAccessibilityEvents();
1972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974 } break;
1975 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001976 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001978 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 if (LOCAL_LOGV) Log.v(
1980 "ViewRoot", "Dispatching key "
1981 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001982 KeyEvent event = (KeyEvent)msg.obj;
1983 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1984 // The IME is trying to say this event is from the
1985 // system! Bad bad bad!
1986 event = KeyEvent.changeFlags(event,
1987 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001990 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 case FINISH_INPUT_CONNECTION: {
1992 InputMethodManager imm = InputMethodManager.peekInstance();
1993 if (imm != null) {
1994 imm.reportFinishInputConnection((InputConnection)msg.obj);
1995 }
1996 } break;
1997 case CHECK_FOCUS: {
1998 InputMethodManager imm = InputMethodManager.peekInstance();
1999 if (imm != null) {
2000 imm.checkFocus();
2001 }
2002 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002003 case CLOSE_SYSTEM_DIALOGS: {
2004 if (mView != null) {
2005 mView.onCloseSystemDialogs((String)msg.obj);
2006 }
2007 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002010
2011 private void finishKeyEvent(KeyEvent event) {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002012 if (mFinishedCallback != null) {
2013 mFinishedCallback.run();
2014 mFinishedCallback = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002015 }
2016 }
2017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 /**
2019 * Something in the current window tells us we need to change the touch mode. For
2020 * example, we are not in touch mode, and the user touches the screen.
2021 *
2022 * If the touch mode has changed, tell the window manager, and handle it locally.
2023 *
2024 * @param inTouchMode Whether we want to be in touch mode.
2025 * @return True if the touch mode changed and focus changed was changed as a result
2026 */
2027 boolean ensureTouchMode(boolean inTouchMode) {
2028 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2029 + "touch mode is " + mAttachInfo.mInTouchMode);
2030 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2031
2032 // tell the window manager
2033 try {
2034 sWindowSession.setInTouchMode(inTouchMode);
2035 } catch (RemoteException e) {
2036 throw new RuntimeException(e);
2037 }
2038
2039 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002040 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042
2043 /**
2044 * Ensure that the touch mode for this window is set, and if it is changing,
2045 * take the appropriate action.
2046 * @param inTouchMode Whether we want to be in touch mode.
2047 * @return True if the touch mode changed and focus changed was changed as a result
2048 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002049 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2051 + "touch mode is " + mAttachInfo.mInTouchMode);
2052
2053 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2054
2055 mAttachInfo.mInTouchMode = inTouchMode;
2056 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2057
Romain Guy2d4cff62010-04-09 15:39:00 -07002058 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060
2061 private boolean enterTouchMode() {
2062 if (mView != null) {
2063 if (mView.hasFocus()) {
2064 // note: not relying on mFocusedView here because this could
2065 // be when the window is first being added, and mFocused isn't
2066 // set yet.
2067 final View focused = mView.findFocus();
2068 if (focused != null && !focused.isFocusableInTouchMode()) {
2069
2070 final ViewGroup ancestorToTakeFocus =
2071 findAncestorToTakeFocusInTouchMode(focused);
2072 if (ancestorToTakeFocus != null) {
2073 // there is an ancestor that wants focus after its descendants that
2074 // is focusable in touch mode.. give it focus
2075 return ancestorToTakeFocus.requestFocus();
2076 } else {
2077 // nothing appropriate to have focus in touch mode, clear it out
2078 mView.unFocus();
2079 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2080 mFocusedView = null;
2081 return true;
2082 }
2083 }
2084 }
2085 }
2086 return false;
2087 }
2088
2089
2090 /**
2091 * Find an ancestor of focused that wants focus after its descendants and is
2092 * focusable in touch mode.
2093 * @param focused The currently focused view.
2094 * @return An appropriate view, or null if no such view exists.
2095 */
2096 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2097 ViewParent parent = focused.getParent();
2098 while (parent instanceof ViewGroup) {
2099 final ViewGroup vgParent = (ViewGroup) parent;
2100 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2101 && vgParent.isFocusableInTouchMode()) {
2102 return vgParent;
2103 }
2104 if (vgParent.isRootNamespace()) {
2105 return null;
2106 } else {
2107 parent = vgParent.getParent();
2108 }
2109 }
2110 return null;
2111 }
2112
2113 private boolean leaveTouchMode() {
2114 if (mView != null) {
2115 if (mView.hasFocus()) {
2116 // i learned the hard way to not trust mFocusedView :)
2117 mFocusedView = mView.findFocus();
2118 if (!(mFocusedView instanceof ViewGroup)) {
2119 // some view has focus, let it keep it
2120 return false;
2121 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2122 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2123 // some view group has focus, and doesn't prefer its children
2124 // over itself for focus, so let them keep it.
2125 return false;
2126 }
2127 }
2128
2129 // find the best view to give focus to in this brave new non-touch-mode
2130 // world
2131 final View focused = focusSearch(null, View.FOCUS_DOWN);
2132 if (focused != null) {
2133 return focused.requestFocus(View.FOCUS_DOWN);
2134 }
2135 }
2136 return false;
2137 }
2138
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002139 private void deliverPointerEvent(MotionEvent event) {
2140 if (mTranslator != null) {
2141 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002143
2144 boolean handled;
2145 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002147 // enter touch mode on the down
2148 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2149 if (isDown) {
2150 ensureTouchMode(true);
2151 }
2152 if(Config.LOGV) {
2153 captureMotionLog("captureDispatchPointer", event);
2154 }
2155 if (mCurScrollY != 0) {
2156 event.offsetLocation(0, mCurScrollY);
2157 }
2158 if (MEASURE_LATENCY) {
2159 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2160 }
2161 handled = mView.dispatchTouchEvent(event);
2162 if (MEASURE_LATENCY) {
2163 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2164 }
2165 if (!handled && isDown) {
2166 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2167
2168 final int edgeFlags = event.getEdgeFlags();
2169 int direction = View.FOCUS_UP;
2170 int x = (int)event.getX();
2171 int y = (int)event.getY();
2172 final int[] deltas = new int[2];
2173
2174 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2175 direction = View.FOCUS_DOWN;
2176 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2177 deltas[0] = edgeSlop;
2178 x += edgeSlop;
2179 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2180 deltas[0] = -edgeSlop;
2181 x -= edgeSlop;
2182 }
2183 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2184 direction = View.FOCUS_UP;
2185 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2186 deltas[0] = edgeSlop;
2187 x += edgeSlop;
2188 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2189 deltas[0] = -edgeSlop;
2190 x -= edgeSlop;
2191 }
2192 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2193 direction = View.FOCUS_RIGHT;
2194 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2195 direction = View.FOCUS_LEFT;
2196 }
2197
2198 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2199 View nearest = FocusFinder.getInstance().findNearestTouchable(
2200 ((ViewGroup) mView), x, y, direction, deltas);
2201 if (nearest != null) {
2202 event.offsetLocation(deltas[0], deltas[1]);
2203 event.setEdgeFlags(0);
2204 mView.dispatchTouchEvent(event);
2205 }
2206 }
2207 }
2208 }
2209 }
2210
2211 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2213
2214 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002215 if (mView != null && mAdded) {
2216 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 // If we reach this, we delivered a trackball event to mView and
2219 // mView consumed it. Because we will not translate the trackball
2220 // event into a key event, touch mode will not exit, so we exit
2221 // touch mode here.
2222 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 return;
2224 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002225
2226 // Otherwise we could do something here, like changing the focus
2227 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 }
2229
2230 final TrackballAxis x = mTrackballAxisX;
2231 final TrackballAxis y = mTrackballAxisY;
2232
2233 long curTime = SystemClock.uptimeMillis();
2234 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2235 // It has been too long since the last movement,
2236 // so restart at the beginning.
2237 x.reset(0);
2238 y.reset(0);
2239 mLastTrackballTime = curTime;
2240 }
2241
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002242 final int action = event.getAction();
2243 final int metastate = event.getMetaState();
2244 switch (action) {
2245 case MotionEvent.ACTION_DOWN:
2246 x.reset(2);
2247 y.reset(2);
2248 deliverKeyEvent(new KeyEvent(curTime, curTime,
2249 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2250 0, metastate), false);
2251 break;
2252 case MotionEvent.ACTION_UP:
2253 x.reset(2);
2254 y.reset(2);
2255 deliverKeyEvent(new KeyEvent(curTime, curTime,
2256 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2257 0, metastate), false);
2258 break;
2259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002261 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2262 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2263 + " move=" + event.getX()
2264 + " / Y=" + y.position + " step="
2265 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2266 + " move=" + event.getY());
2267 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2268 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002270 // Generate DPAD events based on the trackball movement.
2271 // We pick the axis that has moved the most as the direction of
2272 // the DPAD. When we generate DPAD events for one axis, then the
2273 // other axis is reset -- we don't want to perform DPAD jumps due
2274 // to slight movements in the trackball when making major movements
2275 // along the other axis.
2276 int keycode = 0;
2277 int movement = 0;
2278 float accel = 1;
2279 if (xOff > yOff) {
2280 movement = x.generate((2/event.getXPrecision()));
2281 if (movement != 0) {
2282 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2283 : KeyEvent.KEYCODE_DPAD_LEFT;
2284 accel = x.acceleration;
2285 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002287 } else if (yOff > 0) {
2288 movement = y.generate((2/event.getYPrecision()));
2289 if (movement != 0) {
2290 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2291 : KeyEvent.KEYCODE_DPAD_UP;
2292 accel = y.acceleration;
2293 x.reset(2);
2294 }
2295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002297 if (keycode != 0) {
2298 if (movement < 0) movement = -movement;
2299 int accelMovement = (int)(movement * accel);
2300 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2301 + " accelMovement=" + accelMovement
2302 + " accel=" + accel);
2303 if (accelMovement > movement) {
2304 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2305 + keycode);
2306 movement--;
2307 deliverKeyEvent(new KeyEvent(curTime, curTime,
2308 KeyEvent.ACTION_MULTIPLE, keycode,
2309 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002311 while (movement > 0) {
2312 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2313 + keycode);
2314 movement--;
2315 curTime = SystemClock.uptimeMillis();
2316 deliverKeyEvent(new KeyEvent(curTime, curTime,
2317 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2318 deliverKeyEvent(new KeyEvent(curTime, curTime,
2319 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002321 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
2323 }
2324
2325 /**
2326 * @param keyCode The key code
2327 * @return True if the key is directional.
2328 */
2329 static boolean isDirectional(int keyCode) {
2330 switch (keyCode) {
2331 case KeyEvent.KEYCODE_DPAD_LEFT:
2332 case KeyEvent.KEYCODE_DPAD_RIGHT:
2333 case KeyEvent.KEYCODE_DPAD_UP:
2334 case KeyEvent.KEYCODE_DPAD_DOWN:
2335 return true;
2336 }
2337 return false;
2338 }
2339
2340 /**
2341 * Returns true if this key is a keyboard key.
2342 * @param keyEvent The key event.
2343 * @return whether this key is a keyboard key.
2344 */
2345 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2346 final int convertedKey = keyEvent.getUnicodeChar();
2347 return convertedKey > 0;
2348 }
2349
2350
2351
2352 /**
2353 * See if the key event means we should leave touch mode (and leave touch
2354 * mode if so).
2355 * @param event The key event.
2356 * @return Whether this key event should be consumed (meaning the act of
2357 * leaving touch mode alone is considered the event).
2358 */
2359 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002360 final int action = event.getAction();
2361 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 return false;
2363 }
2364 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2365 return false;
2366 }
2367
2368 // only relevant if we are in touch mode
2369 if (!mAttachInfo.mInTouchMode) {
2370 return false;
2371 }
2372
2373 // if something like an edit text has focus and the user is typing,
2374 // leave touch mode
2375 //
2376 // note: the condition of not being a keyboard key is kind of a hacky
2377 // approximation of whether we think the focused view will want the
2378 // key; if we knew for sure whether the focused view would consume
2379 // the event, that would be better.
2380 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2381 mFocusedView = mView.findFocus();
2382 if ((mFocusedView instanceof ViewGroup)
2383 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2384 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2385 // something has focus, but is holding it weakly as a container
2386 return false;
2387 }
2388 if (ensureTouchMode(false)) {
2389 throw new IllegalStateException("should not have changed focus "
2390 + "when leaving touch mode while a view has focus.");
2391 }
2392 return false;
2393 }
2394
2395 if (isDirectional(event.getKeyCode())) {
2396 // no view has focus, so we leave touch mode (and find something
2397 // to give focus to). the event is consumed if we were able to
2398 // find something to give focus to.
2399 return ensureTouchMode(false);
2400 }
2401 return false;
2402 }
2403
2404 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002405 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 */
2407 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002408 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 if (ev == null ||
2410 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2411 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 }
Romain Guy8506ab42009-06-11 17:35:47 -07002413
2414 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 sb.append(ev.getDownTime()).append(',');
2416 sb.append(ev.getEventTime()).append(',');
2417 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002418 sb.append(ev.getX()).append(',');
2419 sb.append(ev.getY()).append(',');
2420 sb.append(ev.getPressure()).append(',');
2421 sb.append(ev.getSize()).append(',');
2422 sb.append(ev.getMetaState()).append(',');
2423 sb.append(ev.getXPrecision()).append(',');
2424 sb.append(ev.getYPrecision()).append(',');
2425 sb.append(ev.getDeviceId()).append(',');
2426 sb.append(ev.getEdgeFlags());
2427 Log.d(TAG, sb.toString());
2428 }
2429 /**
2430 * log motion events
2431 */
2432 private static void captureKeyLog(String subTag, KeyEvent ev) {
2433 //check dynamic switch
2434 if (ev == null ||
2435 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2436 return;
2437 }
2438 StringBuilder sb = new StringBuilder(subTag + ": ");
2439 sb.append(ev.getDownTime()).append(',');
2440 sb.append(ev.getEventTime()).append(',');
2441 sb.append(ev.getAction()).append(',');
2442 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 sb.append(ev.getRepeatCount()).append(',');
2444 sb.append(ev.getMetaState()).append(',');
2445 sb.append(ev.getDeviceId()).append(',');
2446 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002447 Log.d(TAG, sb.toString());
2448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449
2450 int enqueuePendingEvent(Object event, boolean sendDone) {
2451 int seq = mPendingEventSeq+1;
2452 if (seq < 0) seq = 0;
2453 mPendingEventSeq = seq;
2454 mPendingEvents.put(seq, event);
2455 return sendDone ? seq : -seq;
2456 }
2457
2458 Object retrievePendingEvent(int seq) {
2459 if (seq < 0) seq = -seq;
2460 Object event = mPendingEvents.get(seq);
2461 if (event != null) {
2462 mPendingEvents.remove(seq);
2463 }
2464 return event;
2465 }
Romain Guy8506ab42009-06-11 17:35:47 -07002466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2468 // If mView is null, we just consume the key event because it doesn't
2469 // make sense to do anything else with it.
2470 boolean handled = mView != null
2471 ? mView.dispatchKeyEventPreIme(event) : true;
2472 if (handled) {
2473 if (sendDone) {
2474 if (LOCAL_LOGV) Log.v(
2475 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002476 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 }
2478 return;
2479 }
2480 // If it is possible for this window to interact with the input
2481 // method window, then we want to first dispatch our key events
2482 // to the input method.
2483 if (mLastWasImTarget) {
2484 InputMethodManager imm = InputMethodManager.peekInstance();
2485 if (imm != null && mView != null) {
2486 int seq = enqueuePendingEvent(event, sendDone);
2487 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2488 + seq + " event=" + event);
2489 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2490 mInputMethodCallback);
2491 return;
2492 }
2493 }
2494 deliverKeyEventToViewHierarchy(event, sendDone);
2495 }
2496
2497 void handleFinishedEvent(int seq, boolean handled) {
2498 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2499 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2500 + " handled=" + handled + " event=" + event);
2501 if (event != null) {
2502 final boolean sendDone = seq >= 0;
2503 if (!handled) {
2504 deliverKeyEventToViewHierarchy(event, sendDone);
2505 return;
2506 } else if (sendDone) {
2507 if (LOCAL_LOGV) Log.v(
2508 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002509 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 } else {
2511 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2512 + " handled=" + handled + " ev=" + event
2513 + ") neither delivering nor finishing key");
2514 }
2515 }
2516 }
Romain Guy8506ab42009-06-11 17:35:47 -07002517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2519 try {
2520 if (mView != null && mAdded) {
2521 final int action = event.getAction();
2522 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2523
2524 if (checkForLeavingTouchModeAndConsume(event)) {
2525 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002526 }
2527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 if (Config.LOGV) {
2529 captureKeyLog("captureDispatchKeyEvent", event);
2530 }
2531 boolean keyHandled = mView.dispatchKeyEvent(event);
2532
2533 if (!keyHandled && isDown) {
2534 int direction = 0;
2535 switch (event.getKeyCode()) {
2536 case KeyEvent.KEYCODE_DPAD_LEFT:
2537 direction = View.FOCUS_LEFT;
2538 break;
2539 case KeyEvent.KEYCODE_DPAD_RIGHT:
2540 direction = View.FOCUS_RIGHT;
2541 break;
2542 case KeyEvent.KEYCODE_DPAD_UP:
2543 direction = View.FOCUS_UP;
2544 break;
2545 case KeyEvent.KEYCODE_DPAD_DOWN:
2546 direction = View.FOCUS_DOWN;
2547 break;
2548 }
2549
2550 if (direction != 0) {
2551
2552 View focused = mView != null ? mView.findFocus() : null;
2553 if (focused != null) {
2554 View v = focused.focusSearch(direction);
2555 boolean focusPassed = false;
2556 if (v != null && v != focused) {
2557 // do the math the get the interesting rect
2558 // of previous focused into the coord system of
2559 // newly focused view
2560 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002561 if (mView instanceof ViewGroup) {
2562 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2563 focused, mTempRect);
2564 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2565 v, mTempRect);
2566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 focusPassed = v.requestFocus(direction, mTempRect);
2568 }
2569
2570 if (!focusPassed) {
2571 mView.dispatchUnhandledMove(focused, direction);
2572 } else {
2573 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2574 }
2575 }
2576 }
2577 }
2578 }
2579
2580 } finally {
2581 if (sendDone) {
2582 if (LOCAL_LOGV) Log.v(
2583 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002584 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 }
2586 // Let the exception fall through -- the looper will catch
2587 // it and take care of the bad app for us.
2588 }
2589 }
2590
2591 private AudioManager getAudioManager() {
2592 if (mView == null) {
2593 throw new IllegalStateException("getAudioManager called when there is no mView");
2594 }
2595 if (mAudioManager == null) {
2596 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2597 }
2598 return mAudioManager;
2599 }
2600
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002601 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2602 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002603
2604 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002605 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002606 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002607 restore = true;
2608 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002609 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002610 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002611 if (params != null) {
2612 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002613 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002614 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002615 int relayoutResult = sWindowSession.relayout(
2616 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002617 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2618 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002619 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002620 mPendingContentInsets, mPendingVisibleInsets,
2621 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002622 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002623 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002624 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002625
2626 if (mTranslator != null) {
2627 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2628 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2629 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002630 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002631 return relayoutResult;
2632 }
Romain Guy8506ab42009-06-11 17:35:47 -07002633
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002634 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 * {@inheritDoc}
2636 */
2637 public void playSoundEffect(int effectId) {
2638 checkThread();
2639
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002640 try {
2641 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002643 switch (effectId) {
2644 case SoundEffectConstants.CLICK:
2645 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2646 return;
2647 case SoundEffectConstants.NAVIGATION_DOWN:
2648 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2649 return;
2650 case SoundEffectConstants.NAVIGATION_LEFT:
2651 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2652 return;
2653 case SoundEffectConstants.NAVIGATION_RIGHT:
2654 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2655 return;
2656 case SoundEffectConstants.NAVIGATION_UP:
2657 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2658 return;
2659 default:
2660 throw new IllegalArgumentException("unknown effect id " + effectId +
2661 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2662 }
2663 } catch (IllegalStateException e) {
2664 // Exception thrown by getAudioManager() when mView is null
2665 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2666 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 }
2668 }
2669
2670 /**
2671 * {@inheritDoc}
2672 */
2673 public boolean performHapticFeedback(int effectId, boolean always) {
2674 try {
2675 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2676 } catch (RemoteException e) {
2677 return false;
2678 }
2679 }
2680
2681 /**
2682 * {@inheritDoc}
2683 */
2684 public View focusSearch(View focused, int direction) {
2685 checkThread();
2686 if (!(mView instanceof ViewGroup)) {
2687 return null;
2688 }
2689 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2690 }
2691
2692 public void debug() {
2693 mView.debug();
2694 }
2695
2696 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002697 if (immediate) {
2698 doDie();
2699 } else {
2700 sendEmptyMessage(DIE);
2701 }
2702 }
2703
2704 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 checkThread();
2706 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2707 synchronized (this) {
2708 if (mAdded && !mFirst) {
2709 int viewVisibility = mView.getVisibility();
2710 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2711 if (mWindowAttributesChanged || viewVisibilityChanged) {
2712 // If layout params have been changed, first give them
2713 // to the window manager to make sure it has the correct
2714 // animation info.
2715 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002716 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2717 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 sWindowSession.finishDrawing(mWindow);
2719 }
2720 } catch (RemoteException e) {
2721 }
2722 }
2723
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002724 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 }
2726 if (mAdded) {
2727 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002728 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
2730 }
2731 }
2732
2733 public void dispatchFinishedEvent(int seq, boolean handled) {
2734 Message msg = obtainMessage(FINISHED_EVENT);
2735 msg.arg1 = seq;
2736 msg.arg2 = handled ? 1 : 0;
2737 sendMessage(msg);
2738 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002741 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2743 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2744 + " visibleInsets=" + visibleInsets.toShortString()
2745 + " reportDraw=" + reportDraw);
2746 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002747 if (mTranslator != null) {
2748 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2749 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2750 w *= mTranslator.applicationInvertedScale;
2751 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002752 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002753 msg.arg1 = w;
2754 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002755 ResizedInfo ri = new ResizedInfo();
2756 ri.coveredInsets = new Rect(coveredInsets);
2757 ri.visibleInsets = new Rect(visibleInsets);
2758 ri.newConfig = newConfig;
2759 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 sendMessage(msg);
2761 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002762
2763 private Runnable mFinishedCallback;
2764
2765 private final InputHandler mInputHandler = new InputHandler() {
2766 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2767 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002768
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002769 dispatchKey(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002770 }
2771
2772 public void handleTouch(MotionEvent event, Runnable finishedCallback) {
2773 finishedCallback.run();
2774
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002775 dispatchPointer(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002776 }
2777
2778 public void handleTrackball(MotionEvent event, Runnable finishedCallback) {
2779 finishedCallback.run();
2780
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002781 dispatchTrackball(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002782 }
2783 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784
2785 public void dispatchKey(KeyEvent event) {
2786 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2787 //noinspection ConstantConditions
2788 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2789 if (Config.LOGD) Log.d("keydisp",
2790 "===================================================");
2791 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2792 debug();
2793
2794 if (Config.LOGD) Log.d("keydisp",
2795 "===================================================");
2796 }
2797 }
2798
2799 Message msg = obtainMessage(DISPATCH_KEY);
2800 msg.obj = event;
2801
2802 if (LOCAL_LOGV) Log.v(
2803 "ViewRoot", "sending key " + event + " to " + mView);
2804
2805 sendMessageAtTime(msg, event.getEventTime());
2806 }
2807
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002808 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 Message msg = obtainMessage(DISPATCH_POINTER);
2810 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002811 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
2813
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002814 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2816 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002817 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 public void dispatchAppVisibility(boolean visible) {
2821 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2822 msg.arg1 = visible ? 1 : 0;
2823 sendMessage(msg);
2824 }
2825
2826 public void dispatchGetNewSurface() {
2827 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2828 sendMessage(msg);
2829 }
2830
2831 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2832 Message msg = Message.obtain();
2833 msg.what = WINDOW_FOCUS_CHANGED;
2834 msg.arg1 = hasFocus ? 1 : 0;
2835 msg.arg2 = inTouchMode ? 1 : 0;
2836 sendMessage(msg);
2837 }
2838
Dianne Hackbornffa42482009-09-23 22:20:11 -07002839 public void dispatchCloseSystemDialogs(String reason) {
2840 Message msg = Message.obtain();
2841 msg.what = CLOSE_SYSTEM_DIALOGS;
2842 msg.obj = reason;
2843 sendMessage(msg);
2844 }
2845
svetoslavganov75986cf2009-05-14 22:28:01 -07002846 /**
2847 * The window is getting focus so if there is anything focused/selected
2848 * send an {@link AccessibilityEvent} to announce that.
2849 */
2850 private void sendAccessibilityEvents() {
2851 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2852 return;
2853 }
2854 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2855 View focusedView = mView.findFocus();
2856 if (focusedView != null && focusedView != mView) {
2857 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2858 }
2859 }
2860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 public boolean showContextMenuForChild(View originalView) {
2862 return false;
2863 }
2864
2865 public void createContextMenu(ContextMenu menu) {
2866 }
2867
2868 public void childDrawableStateChanged(View child) {
2869 }
2870
2871 protected Rect getWindowFrame() {
2872 return mWinFrame;
2873 }
2874
2875 void checkThread() {
2876 if (mThread != Thread.currentThread()) {
2877 throw new CalledFromWrongThreadException(
2878 "Only the original thread that created a view hierarchy can touch its views.");
2879 }
2880 }
2881
2882 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2883 // ViewRoot never intercepts touch event, so this can be a no-op
2884 }
2885
2886 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2887 boolean immediate) {
2888 return scrollToRectOrFocus(rectangle, immediate);
2889 }
Romain Guy8506ab42009-06-11 17:35:47 -07002890
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002891 class TakenSurfaceHolder extends BaseSurfaceHolder {
2892 @Override
2893 public boolean onAllowLockCanvas() {
2894 return mDrawingAllowed;
2895 }
2896
2897 @Override
2898 public void onRelayoutContainer() {
2899 // Not currently interesting -- from changing between fixed and layout size.
2900 }
2901
2902 public void setFormat(int format) {
2903 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2904 }
2905
2906 public void setType(int type) {
2907 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2908 }
2909
2910 @Override
2911 public void onUpdateSurface() {
2912 // We take care of format and type changes on our own.
2913 throw new IllegalStateException("Shouldn't be here");
2914 }
2915
2916 public boolean isCreating() {
2917 return mIsCreating;
2918 }
2919
2920 @Override
2921 public void setFixedSize(int width, int height) {
2922 throw new UnsupportedOperationException(
2923 "Currently only support sizing from layout");
2924 }
2925
2926 public void setKeepScreenOn(boolean screenOn) {
2927 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2928 }
2929 }
2930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 static class InputMethodCallback extends IInputMethodCallback.Stub {
2932 private WeakReference<ViewRoot> mViewRoot;
2933
2934 public InputMethodCallback(ViewRoot viewRoot) {
2935 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2936 }
Romain Guy8506ab42009-06-11 17:35:47 -07002937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 public void finishedEvent(int seq, boolean handled) {
2939 final ViewRoot viewRoot = mViewRoot.get();
2940 if (viewRoot != null) {
2941 viewRoot.dispatchFinishedEvent(seq, handled);
2942 }
2943 }
2944
2945 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2946 // Stub -- not for use in the client.
2947 }
2948 }
Romain Guy8506ab42009-06-11 17:35:47 -07002949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002951 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002953 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2955 }
2956
2957 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002958 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 final ViewRoot viewRoot = mViewRoot.get();
2960 if (viewRoot != null) {
2961 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002962 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 }
2964 }
2965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 public void dispatchAppVisibility(boolean visible) {
2967 final ViewRoot viewRoot = mViewRoot.get();
2968 if (viewRoot != null) {
2969 viewRoot.dispatchAppVisibility(visible);
2970 }
2971 }
2972
2973 public void dispatchGetNewSurface() {
2974 final ViewRoot viewRoot = mViewRoot.get();
2975 if (viewRoot != null) {
2976 viewRoot.dispatchGetNewSurface();
2977 }
2978 }
2979
2980 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2981 final ViewRoot viewRoot = mViewRoot.get();
2982 if (viewRoot != null) {
2983 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2984 }
2985 }
2986
2987 private static int checkCallingPermission(String permission) {
2988 if (!Process.supportsProcesses()) {
2989 return PackageManager.PERMISSION_GRANTED;
2990 }
2991
2992 try {
2993 return ActivityManagerNative.getDefault().checkPermission(
2994 permission, Binder.getCallingPid(), Binder.getCallingUid());
2995 } catch (RemoteException e) {
2996 return PackageManager.PERMISSION_DENIED;
2997 }
2998 }
2999
3000 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3001 final ViewRoot viewRoot = mViewRoot.get();
3002 if (viewRoot != null) {
3003 final View view = viewRoot.mView;
3004 if (view != null) {
3005 if (checkCallingPermission(Manifest.permission.DUMP) !=
3006 PackageManager.PERMISSION_GRANTED) {
3007 throw new SecurityException("Insufficient permissions to invoke"
3008 + " executeCommand() from pid=" + Binder.getCallingPid()
3009 + ", uid=" + Binder.getCallingUid());
3010 }
3011
3012 OutputStream clientStream = null;
3013 try {
3014 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3015 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3016 } catch (IOException e) {
3017 e.printStackTrace();
3018 } finally {
3019 if (clientStream != null) {
3020 try {
3021 clientStream.close();
3022 } catch (IOException e) {
3023 e.printStackTrace();
3024 }
3025 }
3026 }
3027 }
3028 }
3029 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003030
Dianne Hackbornffa42482009-09-23 22:20:11 -07003031 public void closeSystemDialogs(String reason) {
3032 final ViewRoot viewRoot = mViewRoot.get();
3033 if (viewRoot != null) {
3034 viewRoot.dispatchCloseSystemDialogs(reason);
3035 }
3036 }
3037
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003038 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3039 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003040 if (sync) {
3041 try {
3042 sWindowSession.wallpaperOffsetsComplete(asBinder());
3043 } catch (RemoteException e) {
3044 }
3045 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003046 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003047
3048 public void dispatchWallpaperCommand(String action, int x, int y,
3049 int z, Bundle extras, boolean sync) {
3050 if (sync) {
3051 try {
3052 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3053 } catch (RemoteException e) {
3054 }
3055 }
3056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 }
3058
3059 /**
3060 * Maintains state information for a single trackball axis, generating
3061 * discrete (DPAD) movements based on raw trackball motion.
3062 */
3063 static final class TrackballAxis {
3064 /**
3065 * The maximum amount of acceleration we will apply.
3066 */
3067 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 /**
3070 * The maximum amount of time (in milliseconds) between events in order
3071 * for us to consider the user to be doing fast trackball movements,
3072 * and thus apply an acceleration.
3073 */
3074 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 /**
3077 * Scaling factor to the time (in milliseconds) between events to how
3078 * much to multiple/divide the current acceleration. When movement
3079 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3080 * FAST_MOVE_TIME it divides it.
3081 */
3082 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 float position;
3085 float absPosition;
3086 float acceleration = 1;
3087 long lastMoveTime = 0;
3088 int step;
3089 int dir;
3090 int nonAccelMovement;
3091
3092 void reset(int _step) {
3093 position = 0;
3094 acceleration = 1;
3095 lastMoveTime = 0;
3096 step = _step;
3097 dir = 0;
3098 }
3099
3100 /**
3101 * Add trackball movement into the state. If the direction of movement
3102 * has been reversed, the state is reset before adding the
3103 * movement (so that you don't have to compensate for any previously
3104 * collected movement before see the result of the movement in the
3105 * new direction).
3106 *
3107 * @return Returns the absolute value of the amount of movement
3108 * collected so far.
3109 */
3110 float collect(float off, long time, String axis) {
3111 long normTime;
3112 if (off > 0) {
3113 normTime = (long)(off * FAST_MOVE_TIME);
3114 if (dir < 0) {
3115 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3116 position = 0;
3117 step = 0;
3118 acceleration = 1;
3119 lastMoveTime = 0;
3120 }
3121 dir = 1;
3122 } else if (off < 0) {
3123 normTime = (long)((-off) * FAST_MOVE_TIME);
3124 if (dir > 0) {
3125 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3126 position = 0;
3127 step = 0;
3128 acceleration = 1;
3129 lastMoveTime = 0;
3130 }
3131 dir = -1;
3132 } else {
3133 normTime = 0;
3134 }
Romain Guy8506ab42009-06-11 17:35:47 -07003135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 // The number of milliseconds between each movement that is
3137 // considered "normal" and will not result in any acceleration
3138 // or deceleration, scaled by the offset we have here.
3139 if (normTime > 0) {
3140 long delta = time - lastMoveTime;
3141 lastMoveTime = time;
3142 float acc = acceleration;
3143 if (delta < normTime) {
3144 // The user is scrolling rapidly, so increase acceleration.
3145 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3146 if (scale > 1) acc *= scale;
3147 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3148 + off + " normTime=" + normTime + " delta=" + delta
3149 + " scale=" + scale + " acc=" + acc);
3150 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3151 } else {
3152 // The user is scrolling slowly, so decrease acceleration.
3153 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3154 if (scale > 1) acc /= scale;
3155 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3156 + off + " normTime=" + normTime + " delta=" + delta
3157 + " scale=" + scale + " acc=" + acc);
3158 acceleration = acc > 1 ? acc : 1;
3159 }
3160 }
3161 position += off;
3162 return (absPosition = Math.abs(position));
3163 }
3164
3165 /**
3166 * Generate the number of discrete movement events appropriate for
3167 * the currently collected trackball movement.
3168 *
3169 * @param precision The minimum movement required to generate the
3170 * first discrete movement.
3171 *
3172 * @return Returns the number of discrete movements, either positive
3173 * or negative, or 0 if there is not enough trackball movement yet
3174 * for a discrete movement.
3175 */
3176 int generate(float precision) {
3177 int movement = 0;
3178 nonAccelMovement = 0;
3179 do {
3180 final int dir = position >= 0 ? 1 : -1;
3181 switch (step) {
3182 // If we are going to execute the first step, then we want
3183 // to do this as soon as possible instead of waiting for
3184 // a full movement, in order to make things look responsive.
3185 case 0:
3186 if (absPosition < precision) {
3187 return movement;
3188 }
3189 movement += dir;
3190 nonAccelMovement += dir;
3191 step = 1;
3192 break;
3193 // If we have generated the first movement, then we need
3194 // to wait for the second complete trackball motion before
3195 // generating the second discrete movement.
3196 case 1:
3197 if (absPosition < 2) {
3198 return movement;
3199 }
3200 movement += dir;
3201 nonAccelMovement += dir;
3202 position += dir > 0 ? -2 : 2;
3203 absPosition = Math.abs(position);
3204 step = 2;
3205 break;
3206 // After the first two, we generate discrete movements
3207 // consistently with the trackball, applying an acceleration
3208 // if the trackball is moving quickly. This is a simple
3209 // acceleration on top of what we already compute based
3210 // on how quickly the wheel is being turned, to apply
3211 // a longer increasing acceleration to continuous movement
3212 // in one direction.
3213 default:
3214 if (absPosition < 1) {
3215 return movement;
3216 }
3217 movement += dir;
3218 position += dir >= 0 ? -1 : 1;
3219 absPosition = Math.abs(position);
3220 float acc = acceleration;
3221 acc *= 1.1f;
3222 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3223 break;
3224 }
3225 } while (true);
3226 }
3227 }
3228
3229 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3230 public CalledFromWrongThreadException(String msg) {
3231 super(msg);
3232 }
3233 }
3234
3235 private SurfaceHolder mHolder = new SurfaceHolder() {
3236 // we only need a SurfaceHolder for opengl. it would be nice
3237 // to implement everything else though, especially the callback
3238 // support (opengl doesn't make use of it right now, but eventually
3239 // will).
3240 public Surface getSurface() {
3241 return mSurface;
3242 }
3243
3244 public boolean isCreating() {
3245 return false;
3246 }
3247
3248 public void addCallback(Callback callback) {
3249 }
3250
3251 public void removeCallback(Callback callback) {
3252 }
3253
3254 public void setFixedSize(int width, int height) {
3255 }
3256
3257 public void setSizeFromLayout() {
3258 }
3259
3260 public void setFormat(int format) {
3261 }
3262
3263 public void setType(int type) {
3264 }
3265
3266 public void setKeepScreenOn(boolean screenOn) {
3267 }
3268
3269 public Canvas lockCanvas() {
3270 return null;
3271 }
3272
3273 public Canvas lockCanvas(Rect dirty) {
3274 return null;
3275 }
3276
3277 public void unlockCanvasAndPost(Canvas canvas) {
3278 }
3279 public Rect getSurfaceFrame() {
3280 return null;
3281 }
3282 };
3283
3284 static RunQueue getRunQueue() {
3285 RunQueue rq = sRunQueues.get();
3286 if (rq != null) {
3287 return rq;
3288 }
3289 rq = new RunQueue();
3290 sRunQueues.set(rq);
3291 return rq;
3292 }
Romain Guy8506ab42009-06-11 17:35:47 -07003293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 /**
3295 * @hide
3296 */
3297 static final class RunQueue {
3298 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3299
3300 void post(Runnable action) {
3301 postDelayed(action, 0);
3302 }
3303
3304 void postDelayed(Runnable action, long delayMillis) {
3305 HandlerAction handlerAction = new HandlerAction();
3306 handlerAction.action = action;
3307 handlerAction.delay = delayMillis;
3308
3309 synchronized (mActions) {
3310 mActions.add(handlerAction);
3311 }
3312 }
3313
3314 void removeCallbacks(Runnable action) {
3315 final HandlerAction handlerAction = new HandlerAction();
3316 handlerAction.action = action;
3317
3318 synchronized (mActions) {
3319 final ArrayList<HandlerAction> actions = mActions;
3320
3321 while (actions.remove(handlerAction)) {
3322 // Keep going
3323 }
3324 }
3325 }
3326
3327 void executeActions(Handler handler) {
3328 synchronized (mActions) {
3329 final ArrayList<HandlerAction> actions = mActions;
3330 final int count = actions.size();
3331
3332 for (int i = 0; i < count; i++) {
3333 final HandlerAction handlerAction = actions.get(i);
3334 handler.postDelayed(handlerAction.action, handlerAction.delay);
3335 }
3336
Romain Guy15df6702009-08-17 20:17:30 -07003337 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
3339 }
3340
3341 private static class HandlerAction {
3342 Runnable action;
3343 long delay;
3344
3345 @Override
3346 public boolean equals(Object o) {
3347 if (this == o) return true;
3348 if (o == null || getClass() != o.getClass()) return false;
3349
3350 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 return !(action != null ? !action.equals(that.action) : that.action != null);
3352
3353 }
3354
3355 @Override
3356 public int hashCode() {
3357 int result = action != null ? action.hashCode() : 0;
3358 result = 31 * result + (int) (delay ^ (delay >>> 32));
3359 return result;
3360 }
3361 }
3362 }
3363
3364 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3365
3366 // inform skia to just abandon its texture cache IDs
3367 // doesn't call glDeleteTextures
3368 private static native void nativeAbandonGlCaches();
3369}