blob: 7ce04cfd113fd4cd8594832a4707edfb325ff86a [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 Hackbornd76b67c2010-07-13 17:48:30 -0700140 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700141 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);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700519 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 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) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700772 if (DEBUG_ORIENTATION) Log.v(TAG,
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
Jeff Brownc5ed5912010-07-14 18:48:53 -0700836 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 "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(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001013 TAG, "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(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001134 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 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) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001263 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001266 if (mSurfaceHolder != null && mSurface.isValid()) {
1267 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1268 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1269 if (callbacks != null) {
1270 for (SurfaceHolder.Callback c : callbacks) {
1271 if (c instanceof SurfaceHolder.Callback2) {
1272 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1273 mSurfaceHolder);
1274 }
1275 }
1276 }
1277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 try {
1279 sWindowSession.finishDrawing(mWindow);
1280 } catch (RemoteException e) {
1281 }
1282 }
1283 } else {
1284 // We were supposed to report when we are done drawing. Since we canceled the
1285 // draw, remember it here.
1286 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1287 mReportNextDraw = true;
1288 }
1289 if (fullRedrawNeeded) {
1290 mFullRedrawNeeded = true;
1291 }
1292 // Try again
1293 scheduleTraversals();
1294 }
1295 }
1296
1297 public void requestTransparentRegion(View child) {
1298 // the test below should not fail unless someone is messing with us
1299 checkThread();
1300 if (mView == child) {
1301 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1302 // Need to make sure we re-evaluate the window attributes next
1303 // time around, to ensure the window has the correct format.
1304 mWindowAttributesChanged = true;
1305 }
1306 }
1307
1308 /**
1309 * Figures out the measure spec for the root view in a window based on it's
1310 * layout params.
1311 *
1312 * @param windowSize
1313 * The available width or height of the window
1314 *
1315 * @param rootDimension
1316 * The layout params for one dimension (width or height) of the
1317 * window.
1318 *
1319 * @return The measure spec to use to measure the root view.
1320 */
1321 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1322 int measureSpec;
1323 switch (rootDimension) {
1324
Romain Guy980a9382010-01-08 15:06:28 -08001325 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // Window can't resize. Force root view to be windowSize.
1327 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1328 break;
1329 case ViewGroup.LayoutParams.WRAP_CONTENT:
1330 // Window can resize. Set max size for root view.
1331 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1332 break;
1333 default:
1334 // Window wants to be an exact size. Force root view to be that size.
1335 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1336 break;
1337 }
1338 return measureSpec;
1339 }
1340
1341 private void draw(boolean fullRedrawNeeded) {
1342 Surface surface = mSurface;
1343 if (surface == null || !surface.isValid()) {
1344 return;
1345 }
1346
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001347 if (!sFirstDrawComplete) {
1348 synchronized (sFirstDrawHandlers) {
1349 sFirstDrawComplete = true;
1350 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1351 post(sFirstDrawHandlers.get(i));
1352 }
1353 }
1354 }
1355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 scrollToRectOrFocus(null, false);
1357
1358 if (mAttachInfo.mViewScrollChanged) {
1359 mAttachInfo.mViewScrollChanged = false;
1360 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1361 }
Romain Guy8506ab42009-06-11 17:35:47 -07001362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001364 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 if (scrolling) {
1366 yoff = mScroller.getCurrY();
1367 } else {
1368 yoff = mScrollY;
1369 }
1370 if (mCurScrollY != yoff) {
1371 mCurScrollY = yoff;
1372 fullRedrawNeeded = true;
1373 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001374 float appScale = mAttachInfo.mApplicationScale;
1375 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376
1377 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001378 if (mSurfaceHolder != null) {
1379 // The app owns the surface, we won't draw.
1380 dirty.setEmpty();
1381 return;
1382 }
1383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 if (mUseGL) {
1385 if (!dirty.isEmpty()) {
1386 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001387 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 mGL.glDisable(GL_SCISSOR_TEST);
1389 mGL.glClearColor(0, 0, 0, 0);
1390 mGL.glClear(GL_COLOR_BUFFER_BIT);
1391 mGL.glEnable(GL_SCISSOR_TEST);
1392
1393 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001394 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001396
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001397 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1398 try {
1399 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001400 if (mTranslator != null) {
1401 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001402 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001403 canvas.setScreenDensity(scalingRequired
1404 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001405 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001406 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1407 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1408 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001409 } finally {
1410 canvas.restoreToCount(saveCount);
1411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412
Romain Guy5bcdff42009-05-14 21:27:18 -07001413 mAttachInfo.mIgnoreDirtyState = false;
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1416 checkEglErrors();
1417
Mike Reedfd716532009-10-12 14:42:56 -04001418 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 int now = (int)SystemClock.elapsedRealtime();
1420 if (sDrawTime != 0) {
1421 nativeShowFPS(canvas, now - sDrawTime);
1422 }
1423 sDrawTime = now;
1424 }
1425 }
1426 }
1427 if (scrolling) {
1428 mFullRedrawNeeded = true;
1429 scheduleTraversals();
1430 }
1431 return;
1432 }
1433
Romain Guy5bcdff42009-05-14 21:27:18 -07001434 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001435 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001436 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438
1439 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001440 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 + mWindowAttributes.getTitle()
1442 + ": dirty={" + dirty.left + "," + dirty.top
1443 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001444 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1445 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001448 if (!dirty.isEmpty() || mIsAnimating) {
1449 Canvas canvas;
1450 try {
1451 int left = dirty.left;
1452 int top = dirty.top;
1453 int right = dirty.right;
1454 int bottom = dirty.bottom;
1455 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001456
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001457 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1458 bottom != dirty.bottom) {
1459 mAttachInfo.mIgnoreDirtyState = true;
1460 }
1461
1462 // TODO: Do this in native
1463 canvas.setDensity(mDensity);
1464 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001465 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001466 // TODO: we should ask the window manager to do something!
1467 // for now we just do nothing
1468 return;
1469 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001470 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001471 // TODO: we should ask the window manager to do something!
1472 // for now we just do nothing
1473 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001474 }
1475
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001476 try {
1477 if (!dirty.isEmpty() || mIsAnimating) {
1478 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001480 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001481 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001482 + canvas.getWidth() + ", h=" + canvas.getHeight());
1483 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001486 if (Config.DEBUG && ViewDebug.profileDrawing) {
1487 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001489
1490 // If this bitmap's format includes an alpha channel, we
1491 // need to clear it before drawing so that the child will
1492 // properly re-composite its drawing on a transparent
1493 // background. This automatically respects the clip/dirty region
1494 // or
1495 // If we are applying an offset, we need to clear the area
1496 // where the offset doesn't appear to avoid having garbage
1497 // left in the blank areas.
1498 if (!canvas.isOpaque() || yoff != 0) {
1499 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1500 }
1501
1502 dirty.setEmpty();
1503 mIsAnimating = false;
1504 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1505 mView.mPrivateFlags |= View.DRAWN;
1506
1507 if (DEBUG_DRAW) {
1508 Context cxt = mView.getContext();
1509 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1510 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1511 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1512 }
1513 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1514 try {
1515 canvas.translate(0, -yoff);
1516 if (mTranslator != null) {
1517 mTranslator.translateCanvas(canvas);
1518 }
1519 canvas.setScreenDensity(scalingRequired
1520 ? DisplayMetrics.DENSITY_DEVICE : 0);
1521 mView.draw(canvas);
1522 } finally {
1523 mAttachInfo.mIgnoreDirtyState = false;
1524 canvas.restoreToCount(saveCount);
1525 }
1526
1527 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1528 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1529 }
1530
1531 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1532 int now = (int)SystemClock.elapsedRealtime();
1533 if (sDrawTime != 0) {
1534 nativeShowFPS(canvas, now - sDrawTime);
1535 }
1536 sDrawTime = now;
1537 }
1538
1539 if (Config.DEBUG && ViewDebug.profileDrawing) {
1540 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001544 } finally {
1545 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548
1549 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001550 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
Romain Guy8506ab42009-06-11 17:35:47 -07001552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 if (scrolling) {
1554 mFullRedrawNeeded = true;
1555 scheduleTraversals();
1556 }
1557 }
1558
1559 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1560 final View.AttachInfo attachInfo = mAttachInfo;
1561 final Rect ci = attachInfo.mContentInsets;
1562 final Rect vi = attachInfo.mVisibleInsets;
1563 int scrollY = 0;
1564 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 if (vi.left > ci.left || vi.top > ci.top
1567 || vi.right > ci.right || vi.bottom > ci.bottom) {
1568 // We'll assume that we aren't going to change the scroll
1569 // offset, since we want to avoid that unless it is actually
1570 // going to make the focus visible... otherwise we scroll
1571 // all over the place.
1572 scrollY = mScrollY;
1573 // We can be called for two different situations: during a draw,
1574 // to update the scroll position if the focus has changed (in which
1575 // case 'rectangle' is null), or in response to a
1576 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1577 // is non-null and we just want to scroll to whatever that
1578 // rectangle is).
1579 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001580
1581 // When in touch mode, focus points to the previously focused view,
1582 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001583 // line checks whether the view is still in our hierarchy.
1584 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001585 mRealFocusedView = null;
1586 return false;
1587 }
1588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 if (focus != mLastScrolledFocus) {
1590 // If the focus has changed, then ignore any requests to scroll
1591 // to a rectangle; first we want to make sure the entire focus
1592 // view is visible.
1593 rectangle = null;
1594 }
1595 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1596 + " rectangle=" + rectangle + " ci=" + ci
1597 + " vi=" + vi);
1598 if (focus == mLastScrolledFocus && !mScrollMayChange
1599 && rectangle == null) {
1600 // Optimization: if the focus hasn't changed since last
1601 // time, and no layout has happened, then just leave things
1602 // as they are.
1603 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1604 + mScrollY + " vi=" + vi.toShortString());
1605 } else if (focus != null) {
1606 // We need to determine if the currently focused view is
1607 // within the visible part of the window and, if not, apply
1608 // a pan so it can be seen.
1609 mLastScrolledFocus = focus;
1610 mScrollMayChange = false;
1611 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1612 // Try to find the rectangle from the focus view.
1613 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1614 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1615 + mView.getWidth() + " h=" + mView.getHeight()
1616 + " ci=" + ci.toShortString()
1617 + " vi=" + vi.toShortString());
1618 if (rectangle == null) {
1619 focus.getFocusedRect(mTempRect);
1620 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1621 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001622 if (mView instanceof ViewGroup) {
1623 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1624 focus, mTempRect);
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1627 "Focus in window: focusRect="
1628 + mTempRect.toShortString()
1629 + " visRect=" + mVisRect.toShortString());
1630 } else {
1631 mTempRect.set(rectangle);
1632 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1633 "Request scroll to rect: "
1634 + mTempRect.toShortString()
1635 + " visRect=" + mVisRect.toShortString());
1636 }
1637 if (mTempRect.intersect(mVisRect)) {
1638 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1639 "Focus window visible rect: "
1640 + mTempRect.toShortString());
1641 if (mTempRect.height() >
1642 (mView.getHeight()-vi.top-vi.bottom)) {
1643 // If the focus simply is not going to fit, then
1644 // best is probably just to leave things as-is.
1645 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1646 "Too tall; leaving scrollY=" + scrollY);
1647 } else if ((mTempRect.top-scrollY) < vi.top) {
1648 scrollY -= vi.top - (mTempRect.top-scrollY);
1649 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1650 "Top covered; scrollY=" + scrollY);
1651 } else if ((mTempRect.bottom-scrollY)
1652 > (mView.getHeight()-vi.bottom)) {
1653 scrollY += (mTempRect.bottom-scrollY)
1654 - (mView.getHeight()-vi.bottom);
1655 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1656 "Bottom covered; scrollY=" + scrollY);
1657 }
1658 handled = true;
1659 }
1660 }
1661 }
1662 }
Romain Guy8506ab42009-06-11 17:35:47 -07001663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 if (scrollY != mScrollY) {
1665 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1666 + mScrollY + " , new=" + scrollY);
1667 if (!immediate) {
1668 if (mScroller == null) {
1669 mScroller = new Scroller(mView.getContext());
1670 }
1671 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1672 } else if (mScroller != null) {
1673 mScroller.abortAnimation();
1674 }
1675 mScrollY = scrollY;
1676 }
Romain Guy8506ab42009-06-11 17:35:47 -07001677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 return handled;
1679 }
Romain Guy8506ab42009-06-11 17:35:47 -07001680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 public void requestChildFocus(View child, View focused) {
1682 checkThread();
1683 if (mFocusedView != focused) {
1684 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1685 scheduleTraversals();
1686 }
1687 mFocusedView = mRealFocusedView = focused;
1688 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1689 + mFocusedView);
1690 }
1691
1692 public void clearChildFocus(View child) {
1693 checkThread();
1694
1695 View oldFocus = mFocusedView;
1696
1697 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1698 mFocusedView = mRealFocusedView = null;
1699 if (mView != null && !mView.hasFocus()) {
1700 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1701 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1702 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1703 }
1704 } else if (oldFocus != null) {
1705 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1706 }
1707 }
1708
1709
1710 public void focusableViewAvailable(View v) {
1711 checkThread();
1712
1713 if (mView != null && !mView.hasFocus()) {
1714 v.requestFocus();
1715 } else {
1716 // the one case where will transfer focus away from the current one
1717 // is if the current view is a view group that prefers to give focus
1718 // to its children first AND the view is a descendant of it.
1719 mFocusedView = mView.findFocus();
1720 boolean descendantsHaveDibsOnFocus =
1721 (mFocusedView instanceof ViewGroup) &&
1722 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1723 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1724 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1725 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1726 v.requestFocus();
1727 }
1728 }
1729 }
1730
1731 public void recomputeViewAttributes(View child) {
1732 checkThread();
1733 if (mView == child) {
1734 mAttachInfo.mRecomputeGlobalAttributes = true;
1735 if (!mWillDrawSoon) {
1736 scheduleTraversals();
1737 }
1738 }
1739 }
1740
1741 void dispatchDetachedFromWindow() {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001742 if (Config.LOGV) Log.v(TAG, "Detaching in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743
1744 if (mView != null) {
1745 mView.dispatchDetachedFromWindow();
1746 }
1747
1748 mView = null;
1749 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001750 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751
1752 if (mUseGL) {
1753 destroyGL();
1754 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001755 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001757 if (mInputChannel != null) {
1758 if (mInputQueueCallback != null) {
1759 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1760 mInputQueueCallback = null;
1761 } else {
1762 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001763 }
1764 }
1765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 try {
1767 sWindowSession.remove(mWindow);
1768 } catch (RemoteException e) {
1769 }
Jeff Brown349703e2010-06-22 01:27:15 -07001770
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001771 // Dispose the input channel after removing the window so the Window Manager
1772 // doesn't interpret the input channel being closed as an abnormal termination.
1773 if (mInputChannel != null) {
1774 mInputChannel.dispose();
1775 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Romain Guy8506ab42009-06-11 17:35:47 -07001778
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001779 void updateConfiguration(Configuration config, boolean force) {
1780 if (DEBUG_CONFIGURATION) Log.v(TAG,
1781 "Applying new config to window "
1782 + mWindowAttributes.getTitle()
1783 + ": " + config);
1784 synchronized (sConfigCallbacks) {
1785 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1786 sConfigCallbacks.get(i).onConfigurationChanged(config);
1787 }
1788 }
1789 if (mView != null) {
1790 // At this point the resources have been updated to
1791 // have the most recent config, whatever that is. Use
1792 // the on in them which may be newer.
1793 if (mView != null) {
1794 config = mView.getResources().getConfiguration();
1795 }
1796 if (force || mLastConfiguration.diff(config) != 0) {
1797 mLastConfiguration.setTo(config);
1798 mView.dispatchConfigurationChanged(config);
1799 }
1800 }
1801 }
1802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 /**
1804 * Return true if child is an ancestor of parent, (or equal to the parent).
1805 */
1806 private static boolean isViewDescendantOf(View child, View parent) {
1807 if (child == parent) {
1808 return true;
1809 }
1810
1811 final ViewParent theParent = child.getParent();
1812 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1813 }
1814
Romain Guycdb86672010-03-18 18:54:50 -07001815 private static void forceLayout(View view) {
1816 view.forceLayout();
1817 if (view instanceof ViewGroup) {
1818 ViewGroup group = (ViewGroup) view;
1819 final int count = group.getChildCount();
1820 for (int i = 0; i < count; i++) {
1821 forceLayout(group.getChildAt(i));
1822 }
1823 }
1824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825
1826 public final static int DO_TRAVERSAL = 1000;
1827 public final static int DIE = 1001;
1828 public final static int RESIZED = 1002;
1829 public final static int RESIZED_REPORT = 1003;
1830 public final static int WINDOW_FOCUS_CHANGED = 1004;
1831 public final static int DISPATCH_KEY = 1005;
1832 public final static int DISPATCH_POINTER = 1006;
1833 public final static int DISPATCH_TRACKBALL = 1007;
1834 public final static int DISPATCH_APP_VISIBILITY = 1008;
1835 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1836 public final static int FINISHED_EVENT = 1010;
1837 public final static int DISPATCH_KEY_FROM_IME = 1011;
1838 public final static int FINISH_INPUT_CONNECTION = 1012;
1839 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001840 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841
1842 @Override
1843 public void handleMessage(Message msg) {
1844 switch (msg.what) {
1845 case View.AttachInfo.INVALIDATE_MSG:
1846 ((View) msg.obj).invalidate();
1847 break;
1848 case View.AttachInfo.INVALIDATE_RECT_MSG:
1849 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1850 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1851 info.release();
1852 break;
1853 case DO_TRAVERSAL:
1854 if (mProfile) {
1855 Debug.startMethodTracing("ViewRoot");
1856 }
1857
1858 performTraversals();
1859
1860 if (mProfile) {
1861 Debug.stopMethodTracing();
1862 mProfile = false;
1863 }
1864 break;
1865 case FINISHED_EVENT:
1866 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1867 break;
1868 case DISPATCH_KEY:
1869 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001870 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 + msg.obj + " to " + mView);
1872 deliverKeyEvent((KeyEvent)msg.obj, true);
1873 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001874 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001875 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001877 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001879 event.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001882 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001883 case DISPATCH_TRACKBALL: {
1884 MotionEvent event = (MotionEvent) msg.obj;
1885 try {
1886 deliverTrackballEvent(event);
1887 } finally {
1888 event.recycle();
1889 }
1890 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 case DISPATCH_APP_VISIBILITY:
1892 handleAppVisibility(msg.arg1 != 0);
1893 break;
1894 case DISPATCH_GET_NEW_SURFACE:
1895 handleGetNewSurface();
1896 break;
1897 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001898 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001901 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001902 && mPendingVisibleInsets.equals(ri.visibleInsets)
1903 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 break;
1905 }
1906 // fall through...
1907 case RESIZED_REPORT:
1908 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001909 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1910 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001911 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 mWinFrame.left = 0;
1914 mWinFrame.right = msg.arg1;
1915 mWinFrame.top = 0;
1916 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001917 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1918 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 if (msg.what == RESIZED_REPORT) {
1920 mReportNextDraw = true;
1921 }
Romain Guycdb86672010-03-18 18:54:50 -07001922
1923 if (mView != null) {
1924 forceLayout(mView);
1925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 requestLayout();
1927 }
1928 break;
1929 case WINDOW_FOCUS_CHANGED: {
1930 if (mAdded) {
1931 boolean hasWindowFocus = msg.arg1 != 0;
1932 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1933 if (hasWindowFocus) {
1934 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001935 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936
1937 if (mGlWanted) {
1938 checkEglErrors();
1939 // we lost the gl context, so recreate it.
1940 if (mGlWanted && !mUseGL) {
1941 initializeGL();
1942 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001943 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001944 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001945 (int) (mWidth * appScale + 0.5f),
1946 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
1948 }
1949 }
1950 }
Romain Guy8506ab42009-06-11 17:35:47 -07001951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 mLastWasImTarget = WindowManager.LayoutParams
1953 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 InputMethodManager imm = InputMethodManager.peekInstance();
1956 if (mView != null) {
1957 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1958 imm.startGettingWindowFocus(mView);
1959 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001960 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 mView.dispatchWindowFocusChanged(hasWindowFocus);
1962 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 // Note: must be done after the focus change callbacks,
1965 // so all of the view state is set up correctly.
1966 if (hasWindowFocus) {
1967 if (imm != null && mLastWasImTarget) {
1968 imm.onWindowFocus(mView, mView.findFocus(),
1969 mWindowAttributes.softInputMode,
1970 !mHasHadWindowFocus, mWindowAttributes.flags);
1971 }
1972 // Clear the forward bit. We can just do this directly, since
1973 // the window manager doesn't care about it.
1974 mWindowAttributes.softInputMode &=
1975 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1976 ((WindowManager.LayoutParams)mView.getLayoutParams())
1977 .softInputMode &=
1978 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1979 mHasHadWindowFocus = true;
1980 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001981
1982 if (hasWindowFocus && mView != null) {
1983 sendAccessibilityEvents();
1984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
1986 } break;
1987 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001988 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001990 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001992 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001994 KeyEvent event = (KeyEvent)msg.obj;
1995 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1996 // The IME is trying to say this event is from the
1997 // system! Bad bad bad!
1998 event = KeyEvent.changeFlags(event,
1999 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
2000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002002 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 case FINISH_INPUT_CONNECTION: {
2004 InputMethodManager imm = InputMethodManager.peekInstance();
2005 if (imm != null) {
2006 imm.reportFinishInputConnection((InputConnection)msg.obj);
2007 }
2008 } break;
2009 case CHECK_FOCUS: {
2010 InputMethodManager imm = InputMethodManager.peekInstance();
2011 if (imm != null) {
2012 imm.checkFocus();
2013 }
2014 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002015 case CLOSE_SYSTEM_DIALOGS: {
2016 if (mView != null) {
2017 mView.onCloseSystemDialogs((String)msg.obj);
2018 }
2019 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002022
2023 private void finishKeyEvent(KeyEvent event) {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002024 if (mFinishedCallback != null) {
2025 mFinishedCallback.run();
2026 mFinishedCallback = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002027 }
2028 }
2029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 /**
2031 * Something in the current window tells us we need to change the touch mode. For
2032 * example, we are not in touch mode, and the user touches the screen.
2033 *
2034 * If the touch mode has changed, tell the window manager, and handle it locally.
2035 *
2036 * @param inTouchMode Whether we want to be in touch mode.
2037 * @return True if the touch mode changed and focus changed was changed as a result
2038 */
2039 boolean ensureTouchMode(boolean inTouchMode) {
2040 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2041 + "touch mode is " + mAttachInfo.mInTouchMode);
2042 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2043
2044 // tell the window manager
2045 try {
2046 sWindowSession.setInTouchMode(inTouchMode);
2047 } catch (RemoteException e) {
2048 throw new RuntimeException(e);
2049 }
2050
2051 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002052 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054
2055 /**
2056 * Ensure that the touch mode for this window is set, and if it is changing,
2057 * take the appropriate action.
2058 * @param inTouchMode Whether we want to be in touch mode.
2059 * @return True if the touch mode changed and focus changed was changed as a result
2060 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002061 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2063 + "touch mode is " + mAttachInfo.mInTouchMode);
2064
2065 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2066
2067 mAttachInfo.mInTouchMode = inTouchMode;
2068 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2069
Romain Guy2d4cff62010-04-09 15:39:00 -07002070 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
2073 private boolean enterTouchMode() {
2074 if (mView != null) {
2075 if (mView.hasFocus()) {
2076 // note: not relying on mFocusedView here because this could
2077 // be when the window is first being added, and mFocused isn't
2078 // set yet.
2079 final View focused = mView.findFocus();
2080 if (focused != null && !focused.isFocusableInTouchMode()) {
2081
2082 final ViewGroup ancestorToTakeFocus =
2083 findAncestorToTakeFocusInTouchMode(focused);
2084 if (ancestorToTakeFocus != null) {
2085 // there is an ancestor that wants focus after its descendants that
2086 // is focusable in touch mode.. give it focus
2087 return ancestorToTakeFocus.requestFocus();
2088 } else {
2089 // nothing appropriate to have focus in touch mode, clear it out
2090 mView.unFocus();
2091 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2092 mFocusedView = null;
2093 return true;
2094 }
2095 }
2096 }
2097 }
2098 return false;
2099 }
2100
2101
2102 /**
2103 * Find an ancestor of focused that wants focus after its descendants and is
2104 * focusable in touch mode.
2105 * @param focused The currently focused view.
2106 * @return An appropriate view, or null if no such view exists.
2107 */
2108 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2109 ViewParent parent = focused.getParent();
2110 while (parent instanceof ViewGroup) {
2111 final ViewGroup vgParent = (ViewGroup) parent;
2112 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2113 && vgParent.isFocusableInTouchMode()) {
2114 return vgParent;
2115 }
2116 if (vgParent.isRootNamespace()) {
2117 return null;
2118 } else {
2119 parent = vgParent.getParent();
2120 }
2121 }
2122 return null;
2123 }
2124
2125 private boolean leaveTouchMode() {
2126 if (mView != null) {
2127 if (mView.hasFocus()) {
2128 // i learned the hard way to not trust mFocusedView :)
2129 mFocusedView = mView.findFocus();
2130 if (!(mFocusedView instanceof ViewGroup)) {
2131 // some view has focus, let it keep it
2132 return false;
2133 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2134 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2135 // some view group has focus, and doesn't prefer its children
2136 // over itself for focus, so let them keep it.
2137 return false;
2138 }
2139 }
2140
2141 // find the best view to give focus to in this brave new non-touch-mode
2142 // world
2143 final View focused = focusSearch(null, View.FOCUS_DOWN);
2144 if (focused != null) {
2145 return focused.requestFocus(View.FOCUS_DOWN);
2146 }
2147 }
2148 return false;
2149 }
2150
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002151 private void deliverPointerEvent(MotionEvent event) {
2152 if (mTranslator != null) {
2153 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002155
2156 boolean handled;
2157 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002159 // enter touch mode on the down
2160 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2161 if (isDown) {
2162 ensureTouchMode(true);
2163 }
2164 if(Config.LOGV) {
2165 captureMotionLog("captureDispatchPointer", event);
2166 }
2167 if (mCurScrollY != 0) {
2168 event.offsetLocation(0, mCurScrollY);
2169 }
2170 if (MEASURE_LATENCY) {
2171 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2172 }
2173 handled = mView.dispatchTouchEvent(event);
2174 if (MEASURE_LATENCY) {
2175 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2176 }
2177 if (!handled && isDown) {
2178 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2179
2180 final int edgeFlags = event.getEdgeFlags();
2181 int direction = View.FOCUS_UP;
2182 int x = (int)event.getX();
2183 int y = (int)event.getY();
2184 final int[] deltas = new int[2];
2185
2186 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2187 direction = View.FOCUS_DOWN;
2188 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2189 deltas[0] = edgeSlop;
2190 x += edgeSlop;
2191 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2192 deltas[0] = -edgeSlop;
2193 x -= edgeSlop;
2194 }
2195 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2196 direction = View.FOCUS_UP;
2197 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2198 deltas[0] = edgeSlop;
2199 x += edgeSlop;
2200 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2201 deltas[0] = -edgeSlop;
2202 x -= edgeSlop;
2203 }
2204 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2205 direction = View.FOCUS_RIGHT;
2206 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2207 direction = View.FOCUS_LEFT;
2208 }
2209
2210 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2211 View nearest = FocusFinder.getInstance().findNearestTouchable(
2212 ((ViewGroup) mView), x, y, direction, deltas);
2213 if (nearest != null) {
2214 event.offsetLocation(deltas[0], deltas[1]);
2215 event.setEdgeFlags(0);
2216 mView.dispatchTouchEvent(event);
2217 }
2218 }
2219 }
2220 }
2221 }
2222
2223 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2225
2226 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002227 if (mView != null && mAdded) {
2228 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 // If we reach this, we delivered a trackball event to mView and
2231 // mView consumed it. Because we will not translate the trackball
2232 // event into a key event, touch mode will not exit, so we exit
2233 // touch mode here.
2234 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 return;
2236 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002237
2238 // Otherwise we could do something here, like changing the focus
2239 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
2241
2242 final TrackballAxis x = mTrackballAxisX;
2243 final TrackballAxis y = mTrackballAxisY;
2244
2245 long curTime = SystemClock.uptimeMillis();
2246 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2247 // It has been too long since the last movement,
2248 // so restart at the beginning.
2249 x.reset(0);
2250 y.reset(0);
2251 mLastTrackballTime = curTime;
2252 }
2253
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002254 final int action = event.getAction();
2255 final int metastate = event.getMetaState();
2256 switch (action) {
2257 case MotionEvent.ACTION_DOWN:
2258 x.reset(2);
2259 y.reset(2);
2260 deliverKeyEvent(new KeyEvent(curTime, curTime,
2261 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2262 0, metastate), false);
2263 break;
2264 case MotionEvent.ACTION_UP:
2265 x.reset(2);
2266 y.reset(2);
2267 deliverKeyEvent(new KeyEvent(curTime, curTime,
2268 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2269 0, metastate), false);
2270 break;
2271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002273 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2274 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2275 + " move=" + event.getX()
2276 + " / Y=" + y.position + " step="
2277 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2278 + " move=" + event.getY());
2279 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2280 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002282 // Generate DPAD events based on the trackball movement.
2283 // We pick the axis that has moved the most as the direction of
2284 // the DPAD. When we generate DPAD events for one axis, then the
2285 // other axis is reset -- we don't want to perform DPAD jumps due
2286 // to slight movements in the trackball when making major movements
2287 // along the other axis.
2288 int keycode = 0;
2289 int movement = 0;
2290 float accel = 1;
2291 if (xOff > yOff) {
2292 movement = x.generate((2/event.getXPrecision()));
2293 if (movement != 0) {
2294 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2295 : KeyEvent.KEYCODE_DPAD_LEFT;
2296 accel = x.acceleration;
2297 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002299 } else if (yOff > 0) {
2300 movement = y.generate((2/event.getYPrecision()));
2301 if (movement != 0) {
2302 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2303 : KeyEvent.KEYCODE_DPAD_UP;
2304 accel = y.acceleration;
2305 x.reset(2);
2306 }
2307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002309 if (keycode != 0) {
2310 if (movement < 0) movement = -movement;
2311 int accelMovement = (int)(movement * accel);
2312 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2313 + " accelMovement=" + accelMovement
2314 + " accel=" + accel);
2315 if (accelMovement > movement) {
2316 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2317 + keycode);
2318 movement--;
2319 deliverKeyEvent(new KeyEvent(curTime, curTime,
2320 KeyEvent.ACTION_MULTIPLE, keycode,
2321 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002323 while (movement > 0) {
2324 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2325 + keycode);
2326 movement--;
2327 curTime = SystemClock.uptimeMillis();
2328 deliverKeyEvent(new KeyEvent(curTime, curTime,
2329 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2330 deliverKeyEvent(new KeyEvent(curTime, curTime,
2331 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002333 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 }
2335 }
2336
2337 /**
2338 * @param keyCode The key code
2339 * @return True if the key is directional.
2340 */
2341 static boolean isDirectional(int keyCode) {
2342 switch (keyCode) {
2343 case KeyEvent.KEYCODE_DPAD_LEFT:
2344 case KeyEvent.KEYCODE_DPAD_RIGHT:
2345 case KeyEvent.KEYCODE_DPAD_UP:
2346 case KeyEvent.KEYCODE_DPAD_DOWN:
2347 return true;
2348 }
2349 return false;
2350 }
2351
2352 /**
2353 * Returns true if this key is a keyboard key.
2354 * @param keyEvent The key event.
2355 * @return whether this key is a keyboard key.
2356 */
2357 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2358 final int convertedKey = keyEvent.getUnicodeChar();
2359 return convertedKey > 0;
2360 }
2361
2362
2363
2364 /**
2365 * See if the key event means we should leave touch mode (and leave touch
2366 * mode if so).
2367 * @param event The key event.
2368 * @return Whether this key event should be consumed (meaning the act of
2369 * leaving touch mode alone is considered the event).
2370 */
2371 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002372 final int action = event.getAction();
2373 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 return false;
2375 }
2376 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2377 return false;
2378 }
2379
2380 // only relevant if we are in touch mode
2381 if (!mAttachInfo.mInTouchMode) {
2382 return false;
2383 }
2384
2385 // if something like an edit text has focus and the user is typing,
2386 // leave touch mode
2387 //
2388 // note: the condition of not being a keyboard key is kind of a hacky
2389 // approximation of whether we think the focused view will want the
2390 // key; if we knew for sure whether the focused view would consume
2391 // the event, that would be better.
2392 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2393 mFocusedView = mView.findFocus();
2394 if ((mFocusedView instanceof ViewGroup)
2395 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2396 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2397 // something has focus, but is holding it weakly as a container
2398 return false;
2399 }
2400 if (ensureTouchMode(false)) {
2401 throw new IllegalStateException("should not have changed focus "
2402 + "when leaving touch mode while a view has focus.");
2403 }
2404 return false;
2405 }
2406
2407 if (isDirectional(event.getKeyCode())) {
2408 // no view has focus, so we leave touch mode (and find something
2409 // to give focus to). the event is consumed if we were able to
2410 // find something to give focus to.
2411 return ensureTouchMode(false);
2412 }
2413 return false;
2414 }
2415
2416 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002417 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 */
2419 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002420 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 if (ev == null ||
2422 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2423 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 }
Romain Guy8506ab42009-06-11 17:35:47 -07002425
2426 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 sb.append(ev.getDownTime()).append(',');
2428 sb.append(ev.getEventTime()).append(',');
2429 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002430 sb.append(ev.getX()).append(',');
2431 sb.append(ev.getY()).append(',');
2432 sb.append(ev.getPressure()).append(',');
2433 sb.append(ev.getSize()).append(',');
2434 sb.append(ev.getMetaState()).append(',');
2435 sb.append(ev.getXPrecision()).append(',');
2436 sb.append(ev.getYPrecision()).append(',');
2437 sb.append(ev.getDeviceId()).append(',');
2438 sb.append(ev.getEdgeFlags());
2439 Log.d(TAG, sb.toString());
2440 }
2441 /**
2442 * log motion events
2443 */
2444 private static void captureKeyLog(String subTag, KeyEvent ev) {
2445 //check dynamic switch
2446 if (ev == null ||
2447 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2448 return;
2449 }
2450 StringBuilder sb = new StringBuilder(subTag + ": ");
2451 sb.append(ev.getDownTime()).append(',');
2452 sb.append(ev.getEventTime()).append(',');
2453 sb.append(ev.getAction()).append(',');
2454 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 sb.append(ev.getRepeatCount()).append(',');
2456 sb.append(ev.getMetaState()).append(',');
2457 sb.append(ev.getDeviceId()).append(',');
2458 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002459 Log.d(TAG, sb.toString());
2460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461
2462 int enqueuePendingEvent(Object event, boolean sendDone) {
2463 int seq = mPendingEventSeq+1;
2464 if (seq < 0) seq = 0;
2465 mPendingEventSeq = seq;
2466 mPendingEvents.put(seq, event);
2467 return sendDone ? seq : -seq;
2468 }
2469
2470 Object retrievePendingEvent(int seq) {
2471 if (seq < 0) seq = -seq;
2472 Object event = mPendingEvents.get(seq);
2473 if (event != null) {
2474 mPendingEvents.remove(seq);
2475 }
2476 return event;
2477 }
Romain Guy8506ab42009-06-11 17:35:47 -07002478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2480 // If mView is null, we just consume the key event because it doesn't
2481 // make sense to do anything else with it.
2482 boolean handled = mView != null
2483 ? mView.dispatchKeyEventPreIme(event) : true;
2484 if (handled) {
2485 if (sendDone) {
2486 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002487 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002488 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 }
2490 return;
2491 }
2492 // If it is possible for this window to interact with the input
2493 // method window, then we want to first dispatch our key events
2494 // to the input method.
2495 if (mLastWasImTarget) {
2496 InputMethodManager imm = InputMethodManager.peekInstance();
2497 if (imm != null && mView != null) {
2498 int seq = enqueuePendingEvent(event, sendDone);
2499 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2500 + seq + " event=" + event);
2501 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2502 mInputMethodCallback);
2503 return;
2504 }
2505 }
2506 deliverKeyEventToViewHierarchy(event, sendDone);
2507 }
2508
2509 void handleFinishedEvent(int seq, boolean handled) {
2510 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2511 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2512 + " handled=" + handled + " event=" + event);
2513 if (event != null) {
2514 final boolean sendDone = seq >= 0;
2515 if (!handled) {
2516 deliverKeyEventToViewHierarchy(event, sendDone);
2517 return;
2518 } else if (sendDone) {
2519 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002520 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002521 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002523 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 + " handled=" + handled + " ev=" + event
2525 + ") neither delivering nor finishing key");
2526 }
2527 }
2528 }
Romain Guy8506ab42009-06-11 17:35:47 -07002529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2531 try {
2532 if (mView != null && mAdded) {
2533 final int action = event.getAction();
2534 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2535
2536 if (checkForLeavingTouchModeAndConsume(event)) {
2537 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002538 }
2539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 if (Config.LOGV) {
2541 captureKeyLog("captureDispatchKeyEvent", event);
2542 }
2543 boolean keyHandled = mView.dispatchKeyEvent(event);
2544
2545 if (!keyHandled && isDown) {
2546 int direction = 0;
2547 switch (event.getKeyCode()) {
2548 case KeyEvent.KEYCODE_DPAD_LEFT:
2549 direction = View.FOCUS_LEFT;
2550 break;
2551 case KeyEvent.KEYCODE_DPAD_RIGHT:
2552 direction = View.FOCUS_RIGHT;
2553 break;
2554 case KeyEvent.KEYCODE_DPAD_UP:
2555 direction = View.FOCUS_UP;
2556 break;
2557 case KeyEvent.KEYCODE_DPAD_DOWN:
2558 direction = View.FOCUS_DOWN;
2559 break;
2560 }
2561
2562 if (direction != 0) {
2563
2564 View focused = mView != null ? mView.findFocus() : null;
2565 if (focused != null) {
2566 View v = focused.focusSearch(direction);
2567 boolean focusPassed = false;
2568 if (v != null && v != focused) {
2569 // do the math the get the interesting rect
2570 // of previous focused into the coord system of
2571 // newly focused view
2572 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002573 if (mView instanceof ViewGroup) {
2574 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2575 focused, mTempRect);
2576 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2577 v, mTempRect);
2578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 focusPassed = v.requestFocus(direction, mTempRect);
2580 }
2581
2582 if (!focusPassed) {
2583 mView.dispatchUnhandledMove(focused, direction);
2584 } else {
2585 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2586 }
2587 }
2588 }
2589 }
2590 }
2591
2592 } finally {
2593 if (sendDone) {
2594 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002595 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002596 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 }
2598 // Let the exception fall through -- the looper will catch
2599 // it and take care of the bad app for us.
2600 }
2601 }
2602
2603 private AudioManager getAudioManager() {
2604 if (mView == null) {
2605 throw new IllegalStateException("getAudioManager called when there is no mView");
2606 }
2607 if (mAudioManager == null) {
2608 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2609 }
2610 return mAudioManager;
2611 }
2612
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002613 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2614 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002615
2616 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002617 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002618 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002619 restore = true;
2620 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002621 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002622 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002623 if (params != null) {
2624 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002625 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002626 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002627 int relayoutResult = sWindowSession.relayout(
2628 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002629 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2630 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002631 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002632 mPendingContentInsets, mPendingVisibleInsets,
2633 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002634 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002635 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002636 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002637
2638 if (mTranslator != null) {
2639 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2640 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2641 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002642 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002643 return relayoutResult;
2644 }
Romain Guy8506ab42009-06-11 17:35:47 -07002645
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002646 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 * {@inheritDoc}
2648 */
2649 public void playSoundEffect(int effectId) {
2650 checkThread();
2651
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002652 try {
2653 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002655 switch (effectId) {
2656 case SoundEffectConstants.CLICK:
2657 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2658 return;
2659 case SoundEffectConstants.NAVIGATION_DOWN:
2660 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2661 return;
2662 case SoundEffectConstants.NAVIGATION_LEFT:
2663 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2664 return;
2665 case SoundEffectConstants.NAVIGATION_RIGHT:
2666 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2667 return;
2668 case SoundEffectConstants.NAVIGATION_UP:
2669 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2670 return;
2671 default:
2672 throw new IllegalArgumentException("unknown effect id " + effectId +
2673 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2674 }
2675 } catch (IllegalStateException e) {
2676 // Exception thrown by getAudioManager() when mView is null
2677 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2678 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680 }
2681
2682 /**
2683 * {@inheritDoc}
2684 */
2685 public boolean performHapticFeedback(int effectId, boolean always) {
2686 try {
2687 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2688 } catch (RemoteException e) {
2689 return false;
2690 }
2691 }
2692
2693 /**
2694 * {@inheritDoc}
2695 */
2696 public View focusSearch(View focused, int direction) {
2697 checkThread();
2698 if (!(mView instanceof ViewGroup)) {
2699 return null;
2700 }
2701 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2702 }
2703
2704 public void debug() {
2705 mView.debug();
2706 }
2707
2708 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002709 if (immediate) {
2710 doDie();
2711 } else {
2712 sendEmptyMessage(DIE);
2713 }
2714 }
2715
2716 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 checkThread();
Jeff Brownc5ed5912010-07-14 18:48:53 -07002718 if (Config.LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 synchronized (this) {
2720 if (mAdded && !mFirst) {
2721 int viewVisibility = mView.getVisibility();
2722 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2723 if (mWindowAttributesChanged || viewVisibilityChanged) {
2724 // If layout params have been changed, first give them
2725 // to the window manager to make sure it has the correct
2726 // animation info.
2727 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002728 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2729 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 sWindowSession.finishDrawing(mWindow);
2731 }
2732 } catch (RemoteException e) {
2733 }
2734 }
2735
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002736 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 }
2738 if (mAdded) {
2739 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002740 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 }
2742 }
2743 }
2744
2745 public void dispatchFinishedEvent(int seq, boolean handled) {
2746 Message msg = obtainMessage(FINISHED_EVENT);
2747 msg.arg1 = seq;
2748 msg.arg2 = handled ? 1 : 0;
2749 sendMessage(msg);
2750 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002753 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2755 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2756 + " visibleInsets=" + visibleInsets.toShortString()
2757 + " reportDraw=" + reportDraw);
2758 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002759 if (mTranslator != null) {
2760 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2761 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2762 w *= mTranslator.applicationInvertedScale;
2763 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002764 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002765 msg.arg1 = w;
2766 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002767 ResizedInfo ri = new ResizedInfo();
2768 ri.coveredInsets = new Rect(coveredInsets);
2769 ri.visibleInsets = new Rect(visibleInsets);
2770 ri.newConfig = newConfig;
2771 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 sendMessage(msg);
2773 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002774
2775 private Runnable mFinishedCallback;
2776
2777 private final InputHandler mInputHandler = new InputHandler() {
2778 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2779 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002780
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002781 dispatchKey(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002782 }
2783
Jeff Brownc5ed5912010-07-14 18:48:53 -07002784 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002785 finishedCallback.run();
2786
Jeff Brownc5ed5912010-07-14 18:48:53 -07002787 dispatchMotion(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002788 }
2789 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790
2791 public void dispatchKey(KeyEvent event) {
2792 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2793 //noinspection ConstantConditions
2794 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2795 if (Config.LOGD) Log.d("keydisp",
2796 "===================================================");
2797 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2798 debug();
2799
2800 if (Config.LOGD) Log.d("keydisp",
2801 "===================================================");
2802 }
2803 }
2804
2805 Message msg = obtainMessage(DISPATCH_KEY);
2806 msg.obj = event;
2807
2808 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002809 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810
2811 sendMessageAtTime(msg, event.getEventTime());
2812 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002813
2814 public void dispatchMotion(MotionEvent event) {
2815 int source = event.getSource();
2816 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2817 dispatchPointer(event);
2818 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
2819 dispatchTrackball(event);
2820 } else {
2821 // TODO
2822 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
2823 }
2824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002826 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 Message msg = obtainMessage(DISPATCH_POINTER);
2828 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002829 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 }
2831
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002832 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2834 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002835 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 public void dispatchAppVisibility(boolean visible) {
2839 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2840 msg.arg1 = visible ? 1 : 0;
2841 sendMessage(msg);
2842 }
2843
2844 public void dispatchGetNewSurface() {
2845 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2846 sendMessage(msg);
2847 }
2848
2849 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2850 Message msg = Message.obtain();
2851 msg.what = WINDOW_FOCUS_CHANGED;
2852 msg.arg1 = hasFocus ? 1 : 0;
2853 msg.arg2 = inTouchMode ? 1 : 0;
2854 sendMessage(msg);
2855 }
2856
Dianne Hackbornffa42482009-09-23 22:20:11 -07002857 public void dispatchCloseSystemDialogs(String reason) {
2858 Message msg = Message.obtain();
2859 msg.what = CLOSE_SYSTEM_DIALOGS;
2860 msg.obj = reason;
2861 sendMessage(msg);
2862 }
2863
svetoslavganov75986cf2009-05-14 22:28:01 -07002864 /**
2865 * The window is getting focus so if there is anything focused/selected
2866 * send an {@link AccessibilityEvent} to announce that.
2867 */
2868 private void sendAccessibilityEvents() {
2869 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2870 return;
2871 }
2872 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2873 View focusedView = mView.findFocus();
2874 if (focusedView != null && focusedView != mView) {
2875 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2876 }
2877 }
2878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 public boolean showContextMenuForChild(View originalView) {
2880 return false;
2881 }
2882
2883 public void createContextMenu(ContextMenu menu) {
2884 }
2885
2886 public void childDrawableStateChanged(View child) {
2887 }
2888
2889 protected Rect getWindowFrame() {
2890 return mWinFrame;
2891 }
2892
2893 void checkThread() {
2894 if (mThread != Thread.currentThread()) {
2895 throw new CalledFromWrongThreadException(
2896 "Only the original thread that created a view hierarchy can touch its views.");
2897 }
2898 }
2899
2900 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2901 // ViewRoot never intercepts touch event, so this can be a no-op
2902 }
2903
2904 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2905 boolean immediate) {
2906 return scrollToRectOrFocus(rectangle, immediate);
2907 }
Romain Guy8506ab42009-06-11 17:35:47 -07002908
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002909 class TakenSurfaceHolder extends BaseSurfaceHolder {
2910 @Override
2911 public boolean onAllowLockCanvas() {
2912 return mDrawingAllowed;
2913 }
2914
2915 @Override
2916 public void onRelayoutContainer() {
2917 // Not currently interesting -- from changing between fixed and layout size.
2918 }
2919
2920 public void setFormat(int format) {
2921 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2922 }
2923
2924 public void setType(int type) {
2925 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2926 }
2927
2928 @Override
2929 public void onUpdateSurface() {
2930 // We take care of format and type changes on our own.
2931 throw new IllegalStateException("Shouldn't be here");
2932 }
2933
2934 public boolean isCreating() {
2935 return mIsCreating;
2936 }
2937
2938 @Override
2939 public void setFixedSize(int width, int height) {
2940 throw new UnsupportedOperationException(
2941 "Currently only support sizing from layout");
2942 }
2943
2944 public void setKeepScreenOn(boolean screenOn) {
2945 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2946 }
2947 }
2948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 static class InputMethodCallback extends IInputMethodCallback.Stub {
2950 private WeakReference<ViewRoot> mViewRoot;
2951
2952 public InputMethodCallback(ViewRoot viewRoot) {
2953 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2954 }
Romain Guy8506ab42009-06-11 17:35:47 -07002955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 public void finishedEvent(int seq, boolean handled) {
2957 final ViewRoot viewRoot = mViewRoot.get();
2958 if (viewRoot != null) {
2959 viewRoot.dispatchFinishedEvent(seq, handled);
2960 }
2961 }
2962
2963 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2964 // Stub -- not for use in the client.
2965 }
2966 }
Romain Guy8506ab42009-06-11 17:35:47 -07002967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002969 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002971 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2973 }
2974
2975 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002976 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 final ViewRoot viewRoot = mViewRoot.get();
2978 if (viewRoot != null) {
2979 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002980 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 }
2982 }
2983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 public void dispatchAppVisibility(boolean visible) {
2985 final ViewRoot viewRoot = mViewRoot.get();
2986 if (viewRoot != null) {
2987 viewRoot.dispatchAppVisibility(visible);
2988 }
2989 }
2990
2991 public void dispatchGetNewSurface() {
2992 final ViewRoot viewRoot = mViewRoot.get();
2993 if (viewRoot != null) {
2994 viewRoot.dispatchGetNewSurface();
2995 }
2996 }
2997
2998 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2999 final ViewRoot viewRoot = mViewRoot.get();
3000 if (viewRoot != null) {
3001 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3002 }
3003 }
3004
3005 private static int checkCallingPermission(String permission) {
3006 if (!Process.supportsProcesses()) {
3007 return PackageManager.PERMISSION_GRANTED;
3008 }
3009
3010 try {
3011 return ActivityManagerNative.getDefault().checkPermission(
3012 permission, Binder.getCallingPid(), Binder.getCallingUid());
3013 } catch (RemoteException e) {
3014 return PackageManager.PERMISSION_DENIED;
3015 }
3016 }
3017
3018 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3019 final ViewRoot viewRoot = mViewRoot.get();
3020 if (viewRoot != null) {
3021 final View view = viewRoot.mView;
3022 if (view != null) {
3023 if (checkCallingPermission(Manifest.permission.DUMP) !=
3024 PackageManager.PERMISSION_GRANTED) {
3025 throw new SecurityException("Insufficient permissions to invoke"
3026 + " executeCommand() from pid=" + Binder.getCallingPid()
3027 + ", uid=" + Binder.getCallingUid());
3028 }
3029
3030 OutputStream clientStream = null;
3031 try {
3032 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3033 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3034 } catch (IOException e) {
3035 e.printStackTrace();
3036 } finally {
3037 if (clientStream != null) {
3038 try {
3039 clientStream.close();
3040 } catch (IOException e) {
3041 e.printStackTrace();
3042 }
3043 }
3044 }
3045 }
3046 }
3047 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003048
Dianne Hackbornffa42482009-09-23 22:20:11 -07003049 public void closeSystemDialogs(String reason) {
3050 final ViewRoot viewRoot = mViewRoot.get();
3051 if (viewRoot != null) {
3052 viewRoot.dispatchCloseSystemDialogs(reason);
3053 }
3054 }
3055
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003056 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3057 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003058 if (sync) {
3059 try {
3060 sWindowSession.wallpaperOffsetsComplete(asBinder());
3061 } catch (RemoteException e) {
3062 }
3063 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003064 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003065
3066 public void dispatchWallpaperCommand(String action, int x, int y,
3067 int z, Bundle extras, boolean sync) {
3068 if (sync) {
3069 try {
3070 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3071 } catch (RemoteException e) {
3072 }
3073 }
3074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 }
3076
3077 /**
3078 * Maintains state information for a single trackball axis, generating
3079 * discrete (DPAD) movements based on raw trackball motion.
3080 */
3081 static final class TrackballAxis {
3082 /**
3083 * The maximum amount of acceleration we will apply.
3084 */
3085 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 /**
3088 * The maximum amount of time (in milliseconds) between events in order
3089 * for us to consider the user to be doing fast trackball movements,
3090 * and thus apply an acceleration.
3091 */
3092 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 /**
3095 * Scaling factor to the time (in milliseconds) between events to how
3096 * much to multiple/divide the current acceleration. When movement
3097 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3098 * FAST_MOVE_TIME it divides it.
3099 */
3100 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 float position;
3103 float absPosition;
3104 float acceleration = 1;
3105 long lastMoveTime = 0;
3106 int step;
3107 int dir;
3108 int nonAccelMovement;
3109
3110 void reset(int _step) {
3111 position = 0;
3112 acceleration = 1;
3113 lastMoveTime = 0;
3114 step = _step;
3115 dir = 0;
3116 }
3117
3118 /**
3119 * Add trackball movement into the state. If the direction of movement
3120 * has been reversed, the state is reset before adding the
3121 * movement (so that you don't have to compensate for any previously
3122 * collected movement before see the result of the movement in the
3123 * new direction).
3124 *
3125 * @return Returns the absolute value of the amount of movement
3126 * collected so far.
3127 */
3128 float collect(float off, long time, String axis) {
3129 long normTime;
3130 if (off > 0) {
3131 normTime = (long)(off * FAST_MOVE_TIME);
3132 if (dir < 0) {
3133 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3134 position = 0;
3135 step = 0;
3136 acceleration = 1;
3137 lastMoveTime = 0;
3138 }
3139 dir = 1;
3140 } else if (off < 0) {
3141 normTime = (long)((-off) * FAST_MOVE_TIME);
3142 if (dir > 0) {
3143 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3144 position = 0;
3145 step = 0;
3146 acceleration = 1;
3147 lastMoveTime = 0;
3148 }
3149 dir = -1;
3150 } else {
3151 normTime = 0;
3152 }
Romain Guy8506ab42009-06-11 17:35:47 -07003153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 // The number of milliseconds between each movement that is
3155 // considered "normal" and will not result in any acceleration
3156 // or deceleration, scaled by the offset we have here.
3157 if (normTime > 0) {
3158 long delta = time - lastMoveTime;
3159 lastMoveTime = time;
3160 float acc = acceleration;
3161 if (delta < normTime) {
3162 // The user is scrolling rapidly, so increase acceleration.
3163 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3164 if (scale > 1) acc *= scale;
3165 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3166 + off + " normTime=" + normTime + " delta=" + delta
3167 + " scale=" + scale + " acc=" + acc);
3168 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3169 } else {
3170 // The user is scrolling slowly, so decrease acceleration.
3171 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3172 if (scale > 1) acc /= scale;
3173 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3174 + off + " normTime=" + normTime + " delta=" + delta
3175 + " scale=" + scale + " acc=" + acc);
3176 acceleration = acc > 1 ? acc : 1;
3177 }
3178 }
3179 position += off;
3180 return (absPosition = Math.abs(position));
3181 }
3182
3183 /**
3184 * Generate the number of discrete movement events appropriate for
3185 * the currently collected trackball movement.
3186 *
3187 * @param precision The minimum movement required to generate the
3188 * first discrete movement.
3189 *
3190 * @return Returns the number of discrete movements, either positive
3191 * or negative, or 0 if there is not enough trackball movement yet
3192 * for a discrete movement.
3193 */
3194 int generate(float precision) {
3195 int movement = 0;
3196 nonAccelMovement = 0;
3197 do {
3198 final int dir = position >= 0 ? 1 : -1;
3199 switch (step) {
3200 // If we are going to execute the first step, then we want
3201 // to do this as soon as possible instead of waiting for
3202 // a full movement, in order to make things look responsive.
3203 case 0:
3204 if (absPosition < precision) {
3205 return movement;
3206 }
3207 movement += dir;
3208 nonAccelMovement += dir;
3209 step = 1;
3210 break;
3211 // If we have generated the first movement, then we need
3212 // to wait for the second complete trackball motion before
3213 // generating the second discrete movement.
3214 case 1:
3215 if (absPosition < 2) {
3216 return movement;
3217 }
3218 movement += dir;
3219 nonAccelMovement += dir;
3220 position += dir > 0 ? -2 : 2;
3221 absPosition = Math.abs(position);
3222 step = 2;
3223 break;
3224 // After the first two, we generate discrete movements
3225 // consistently with the trackball, applying an acceleration
3226 // if the trackball is moving quickly. This is a simple
3227 // acceleration on top of what we already compute based
3228 // on how quickly the wheel is being turned, to apply
3229 // a longer increasing acceleration to continuous movement
3230 // in one direction.
3231 default:
3232 if (absPosition < 1) {
3233 return movement;
3234 }
3235 movement += dir;
3236 position += dir >= 0 ? -1 : 1;
3237 absPosition = Math.abs(position);
3238 float acc = acceleration;
3239 acc *= 1.1f;
3240 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3241 break;
3242 }
3243 } while (true);
3244 }
3245 }
3246
3247 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3248 public CalledFromWrongThreadException(String msg) {
3249 super(msg);
3250 }
3251 }
3252
3253 private SurfaceHolder mHolder = new SurfaceHolder() {
3254 // we only need a SurfaceHolder for opengl. it would be nice
3255 // to implement everything else though, especially the callback
3256 // support (opengl doesn't make use of it right now, but eventually
3257 // will).
3258 public Surface getSurface() {
3259 return mSurface;
3260 }
3261
3262 public boolean isCreating() {
3263 return false;
3264 }
3265
3266 public void addCallback(Callback callback) {
3267 }
3268
3269 public void removeCallback(Callback callback) {
3270 }
3271
3272 public void setFixedSize(int width, int height) {
3273 }
3274
3275 public void setSizeFromLayout() {
3276 }
3277
3278 public void setFormat(int format) {
3279 }
3280
3281 public void setType(int type) {
3282 }
3283
3284 public void setKeepScreenOn(boolean screenOn) {
3285 }
3286
3287 public Canvas lockCanvas() {
3288 return null;
3289 }
3290
3291 public Canvas lockCanvas(Rect dirty) {
3292 return null;
3293 }
3294
3295 public void unlockCanvasAndPost(Canvas canvas) {
3296 }
3297 public Rect getSurfaceFrame() {
3298 return null;
3299 }
3300 };
3301
3302 static RunQueue getRunQueue() {
3303 RunQueue rq = sRunQueues.get();
3304 if (rq != null) {
3305 return rq;
3306 }
3307 rq = new RunQueue();
3308 sRunQueues.set(rq);
3309 return rq;
3310 }
Romain Guy8506ab42009-06-11 17:35:47 -07003311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 /**
3313 * @hide
3314 */
3315 static final class RunQueue {
3316 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3317
3318 void post(Runnable action) {
3319 postDelayed(action, 0);
3320 }
3321
3322 void postDelayed(Runnable action, long delayMillis) {
3323 HandlerAction handlerAction = new HandlerAction();
3324 handlerAction.action = action;
3325 handlerAction.delay = delayMillis;
3326
3327 synchronized (mActions) {
3328 mActions.add(handlerAction);
3329 }
3330 }
3331
3332 void removeCallbacks(Runnable action) {
3333 final HandlerAction handlerAction = new HandlerAction();
3334 handlerAction.action = action;
3335
3336 synchronized (mActions) {
3337 final ArrayList<HandlerAction> actions = mActions;
3338
3339 while (actions.remove(handlerAction)) {
3340 // Keep going
3341 }
3342 }
3343 }
3344
3345 void executeActions(Handler handler) {
3346 synchronized (mActions) {
3347 final ArrayList<HandlerAction> actions = mActions;
3348 final int count = actions.size();
3349
3350 for (int i = 0; i < count; i++) {
3351 final HandlerAction handlerAction = actions.get(i);
3352 handler.postDelayed(handlerAction.action, handlerAction.delay);
3353 }
3354
Romain Guy15df6702009-08-17 20:17:30 -07003355 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 }
3357 }
3358
3359 private static class HandlerAction {
3360 Runnable action;
3361 long delay;
3362
3363 @Override
3364 public boolean equals(Object o) {
3365 if (this == o) return true;
3366 if (o == null || getClass() != o.getClass()) return false;
3367
3368 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 return !(action != null ? !action.equals(that.action) : that.action != null);
3370
3371 }
3372
3373 @Override
3374 public int hashCode() {
3375 int result = action != null ? action.hashCode() : 0;
3376 result = 31 * result + (int) (delay ^ (delay >>> 32));
3377 return result;
3378 }
3379 }
3380 }
3381
3382 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3383
3384 // inform skia to just abandon its texture cache IDs
3385 // doesn't call glDeleteTextures
3386 private static native void nativeAbandonGlCaches();
3387}