blob: 9c249ceeab273ca2406bc98daf78f6c1863db49b [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;
55import java.io.IOException;
56import java.io.OutputStream;
57import java.util.ArrayList;
58
59import javax.microedition.khronos.egl.*;
60import javax.microedition.khronos.opengles.*;
61import static javax.microedition.khronos.opengles.GL10.*;
62
63/**
64 * The top of a view hierarchy, implementing the needed protocol between View
65 * and the WindowManager. This is for the most part an internal implementation
66 * detail of {@link WindowManagerImpl}.
67 *
68 * {@hide}
69 */
70@SuppressWarnings({"EmptyCatchBlock"})
71public final class ViewRoot extends Handler implements ViewParent,
72 View.AttachInfo.Callbacks {
73 private static final String TAG = "ViewRoot";
74 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040075 private static final boolean SHOW_FPS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 @SuppressWarnings({"ConstantConditionalExpression"})
77 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
78 /** @noinspection PointlessBooleanExpression*/
79 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
80 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070081 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
83 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
84 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
85 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070086 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 private static final boolean WATCH_POINTER = false;
88
Michael Chan53071d62009-05-13 17:29:48 -070089 private static final boolean MEASURE_LATENCY = false;
90 private static LatencyTimer lt;
91
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 /**
93 * Maximum time we allow the user to roll the trackball enough to generate
94 * a key event, before resetting the counters.
95 */
96 static final int MAX_TRACKBALL_DELAY = 250;
97
98 static long sInstanceCount = 0;
99
100 static IWindowSession sWindowSession;
101
102 static final Object mStaticInit = new Object();
103 static boolean mInitialized = false;
104
105 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
106
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800107 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
108 static boolean sFirstDrawComplete = false;
109
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800110 static final ArrayList<ComponentCallbacks> sConfigCallbacks
111 = new ArrayList<ComponentCallbacks>();
112
Romain Guy8506ab42009-06-11 17:35:47 -0700113 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 long mLastTrackballTime = 0;
116 final TrackballAxis mTrackballAxisX = new TrackballAxis();
117 final TrackballAxis mTrackballAxisY = new TrackballAxis();
118
119 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 final InputMethodCallback mInputMethodCallback;
122 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
123 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 final Thread mThread;
126
127 final WindowLeaked mLocation;
128
129 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
130
131 final W mWindow;
132
133 View mView;
134 View mFocusedView;
135 View mRealFocusedView; // this is not set to null in touch mode
136 int mViewVisibility;
137 boolean mAppVisible = true;
138
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700139 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700140 BaseSurfaceHolder mSurfaceHolder;
141 boolean mIsCreating;
142 boolean mDrawingAllowed;
143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 final Region mTransparentRegion;
145 final Region mPreviousTransparentRegion;
146
147 int mWidth;
148 int mHeight;
149 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700150 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700151
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700152 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
154 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700155 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700156 InputQueue.Callback mInputQueueCallback;
157 InputQueue mInputQueue;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 final Rect mTempRect; // used in the transaction to not thrash the heap.
160 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
162 boolean mTraversalScheduled;
163 boolean mWillDrawSoon;
164 boolean mLayoutRequested;
165 boolean mFirst;
166 boolean mReportNextDraw;
167 boolean mFullRedrawNeeded;
168 boolean mNewSurfaceNeeded;
169 boolean mHasHadWindowFocus;
170 boolean mLastWasImTarget;
171
172 boolean mWindowAttributesChanged = false;
173
174 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700175 // Surface can never be reassigned or cleared (use Surface.clear()).
176 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178 boolean mAdded;
179 boolean mAddedTouchMode;
180
181 /*package*/ int mAddNesting;
182
183 // These are accessed by multiple threads.
184 final Rect mWinFrame; // frame given by window manager.
185
186 final Rect mPendingVisibleInsets = new Rect();
187 final Rect mPendingContentInsets = new Rect();
188 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
189 = new ViewTreeObserver.InternalInsetsInfo();
190
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700191 final Configuration mLastConfiguration = new Configuration();
192 final Configuration mPendingConfiguration = new Configuration();
193
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800194 class ResizedInfo {
195 Rect coveredInsets;
196 Rect visibleInsets;
197 Configuration newConfig;
198 }
199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 boolean mScrollMayChange;
201 int mSoftInputMode;
202 View mLastScrolledFocus;
203 int mScrollY;
204 int mCurScrollY;
205 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 EGL10 mEgl;
208 EGLDisplay mEglDisplay;
209 EGLContext mEglContext;
210 EGLSurface mEglSurface;
211 GL11 mGL;
212 Canvas mGlCanvas;
213 boolean mUseGL;
214 boolean mGlWanted;
215
Romain Guy8506ab42009-06-11 17:35:47 -0700216 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
218 /**
219 * see {@link #playSoundEffect(int)}
220 */
221 AudioManager mAudioManager;
222
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700223 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700224
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700225 public static IWindowSession getWindowSession(Looper mainLooper) {
226 synchronized (mStaticInit) {
227 if (!mInitialized) {
228 try {
229 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
230 sWindowSession = IWindowManager.Stub.asInterface(
231 ServiceManager.getService("window"))
232 .openSession(imm.getClient(), imm.getInputContext());
233 mInitialized = true;
234 } catch (RemoteException e) {
235 }
236 }
237 return sWindowSession;
238 }
239 }
240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 public ViewRoot(Context context) {
242 super();
243
Michael Chan53071d62009-05-13 17:29:48 -0700244 if (MEASURE_LATENCY && lt == null) {
245 lt = new LatencyTimer(100, 1000);
246 }
247
Carl Shapiro82fe5642010-02-24 00:14:23 -0800248 // For debug only
249 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
251 // Initialize the statics when this class is first instantiated. This is
252 // done here instead of in the static block because Zygote does not
253 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700254 getWindowSession(context.getMainLooper());
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 mThread = Thread.currentThread();
257 mLocation = new WindowLeaked(null);
258 mLocation.fillInStackTrace();
259 mWidth = -1;
260 mHeight = -1;
261 mDirty = new Rect();
262 mTempRect = new Rect();
263 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700265 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 mInputMethodCallback = new InputMethodCallback(this);
267 mViewVisibility = View.GONE;
268 mTransparentRegion = new Region();
269 mPreviousTransparentRegion = new Region();
270 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 mAdded = false;
272 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
273 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700274 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 }
276
Carl Shapiro82fe5642010-02-24 00:14:23 -0800277 // For debug only
278 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 @Override
280 protected void finalize() throws Throwable {
281 super.finalize();
282 --sInstanceCount;
283 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800284 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285
286 public static long getInstanceCount() {
287 return sInstanceCount;
288 }
289
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800290 public static void addFirstDrawHandler(Runnable callback) {
291 synchronized (sFirstDrawHandlers) {
292 if (!sFirstDrawComplete) {
293 sFirstDrawHandlers.add(callback);
294 }
295 }
296 }
297
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800298 public static void addConfigCallback(ComponentCallbacks callback) {
299 synchronized (sConfigCallbacks) {
300 sConfigCallbacks.add(callback);
301 }
302 }
303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 // FIXME for perf testing only
305 private boolean mProfile = false;
306
307 /**
308 * Call this to profile the next traversal call.
309 * FIXME for perf testing only. Remove eventually
310 */
311 public void profile() {
312 mProfile = true;
313 }
314
315 /**
316 * Indicates whether we are in touch mode. Calling this method triggers an IPC
317 * call and should be avoided whenever possible.
318 *
319 * @return True, if the device is in touch mode, false otherwise.
320 *
321 * @hide
322 */
323 static boolean isInTouchMode() {
324 if (mInitialized) {
325 try {
326 return sWindowSession.getInTouchMode();
327 } catch (RemoteException e) {
328 }
329 }
330 return false;
331 }
332
333 private void initializeGL() {
334 initializeGLInner();
335 int err = mEgl.eglGetError();
336 if (err != EGL10.EGL_SUCCESS) {
337 // give-up on using GL
338 destroyGL();
339 mGlWanted = false;
340 }
341 }
342
343 private void initializeGLInner() {
344 final EGL10 egl = (EGL10) EGLContext.getEGL();
345 mEgl = egl;
346
347 /*
348 * Get to the default display.
349 */
350 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
351 mEglDisplay = eglDisplay;
352
353 /*
354 * We can now initialize EGL for that display
355 */
356 int[] version = new int[2];
357 egl.eglInitialize(eglDisplay, version);
358
359 /*
360 * Specify a configuration for our opengl session
361 * and grab the first configuration that matches is
362 */
363 final int[] configSpec = {
364 EGL10.EGL_RED_SIZE, 5,
365 EGL10.EGL_GREEN_SIZE, 6,
366 EGL10.EGL_BLUE_SIZE, 5,
367 EGL10.EGL_DEPTH_SIZE, 0,
368 EGL10.EGL_NONE
369 };
370 final EGLConfig[] configs = new EGLConfig[1];
371 final int[] num_config = new int[1];
372 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
373 final EGLConfig config = configs[0];
374
375 /*
376 * Create an OpenGL ES context. This must be done only once, an
377 * OpenGL context is a somewhat heavy object.
378 */
379 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
380 EGL10.EGL_NO_CONTEXT, null);
381 mEglContext = context;
382
383 /*
384 * Create an EGL surface we can render into.
385 */
386 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
387 mEglSurface = surface;
388
389 /*
390 * Before we can issue GL commands, we need to make sure
391 * the context is current and bound to a surface.
392 */
393 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
394
395 /*
396 * Get to the appropriate GL interface.
397 * This is simply done by casting the GL context to either
398 * GL10 or GL11.
399 */
400 final GL11 gl = (GL11) context.getGL();
401 mGL = gl;
402 mGlCanvas = new Canvas(gl);
403 mUseGL = true;
404 }
405
406 private void destroyGL() {
407 // inform skia that the context is gone
408 nativeAbandonGlCaches();
409
410 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
411 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
412 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
413 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
414 mEgl.eglTerminate(mEglDisplay);
415 mEglContext = null;
416 mEglSurface = null;
417 mEglDisplay = null;
418 mEgl = null;
419 mGlCanvas = null;
420 mGL = null;
421 mUseGL = false;
422 }
423
424 private void checkEglErrors() {
425 if (mUseGL) {
426 int err = mEgl.eglGetError();
427 if (err != EGL10.EGL_SUCCESS) {
428 // something bad has happened revert to
429 // normal rendering.
430 destroyGL();
431 if (err != EGL11.EGL_CONTEXT_LOST) {
432 // we'll try again if it was context lost
433 mGlWanted = false;
434 }
435 }
436 }
437 }
438
439 /**
440 * We have one child
441 */
442 public void setView(View view, WindowManager.LayoutParams attrs,
443 View panelParentView) {
444 synchronized (this) {
445 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700446 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700447 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700448 attrs = mWindowAttributes;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700449 if (view instanceof RootViewSurfaceTaker) {
450 mSurfaceHolderCallback =
451 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
452 if (mSurfaceHolderCallback != null) {
453 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700454 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700455 }
456 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700457 Resources resources = mView.getContext().getResources();
458 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700459 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700460
461 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700462 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
463 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700464 }
465
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700466 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700467 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700468 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700469 attrs.backup();
470 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700471 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700472 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
473
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700474 if (!compatibilityInfo.supportsScreen()) {
475 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
476 }
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 mSoftInputMode = attrs.softInputMode;
479 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700481 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700482 mAttachInfo.mApplicationScale =
483 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 if (panelParentView != null) {
485 mAttachInfo.mPanelParentWindowToken
486 = panelParentView.getApplicationWindowToken();
487 }
488 mAdded = true;
489 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 // Schedule the first layout -before- adding to the window
492 // manager, to make sure we do the relayout before receiving
493 // any other events from the system.
494 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700495 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700497 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700498 getHostVisibility(), mAttachInfo.mContentInsets,
499 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 } catch (RemoteException e) {
501 mAdded = false;
502 mView = null;
503 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700504 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 unscheduleTraversals();
506 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700507 } finally {
508 if (restore) {
509 attrs.restore();
510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700512
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700513 if (mTranslator != null) {
514 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 mPendingContentInsets.set(mAttachInfo.mContentInsets);
517 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700518 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 if (res < WindowManagerImpl.ADD_OKAY) {
520 mView = null;
521 mAttachInfo.mRootView = null;
522 mAdded = false;
523 unscheduleTraversals();
524 switch (res) {
525 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
526 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
527 throw new WindowManagerImpl.BadTokenException(
528 "Unable to add window -- token " + attrs.token
529 + " is not valid; is your activity running?");
530 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
531 throw new WindowManagerImpl.BadTokenException(
532 "Unable to add window -- token " + attrs.token
533 + " is not for an application");
534 case WindowManagerImpl.ADD_APP_EXITING:
535 throw new WindowManagerImpl.BadTokenException(
536 "Unable to add window -- app for token " + attrs.token
537 + " is exiting");
538 case WindowManagerImpl.ADD_DUPLICATE_ADD:
539 throw new WindowManagerImpl.BadTokenException(
540 "Unable to add window -- window " + mWindow
541 + " has already been added");
542 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
543 // Silently ignore -- we would have just removed it
544 // right away, anyway.
545 return;
546 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
547 throw new WindowManagerImpl.BadTokenException(
548 "Unable to add window " + mWindow +
549 " -- another window of this type already exists");
550 case WindowManagerImpl.ADD_PERMISSION_DENIED:
551 throw new WindowManagerImpl.BadTokenException(
552 "Unable to add window " + mWindow +
553 " -- permission denied for this window type");
554 }
555 throw new RuntimeException(
556 "Unable to add window -- unknown error code " + res);
557 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700558
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700559 if (view instanceof RootViewSurfaceTaker) {
560 mInputQueueCallback =
561 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
562 }
563 if (mInputQueueCallback != null) {
564 mInputQueue = new InputQueue(mInputChannel);
565 mInputQueueCallback.onInputQueueCreated(mInputQueue);
566 } else {
567 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
568 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700569 }
570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 view.assignParent(this);
572 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
573 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
574 }
575 }
576 }
577
578 public View getView() {
579 return mView;
580 }
581
582 final WindowLeaked getLocation() {
583 return mLocation;
584 }
585
586 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
587 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700588 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700589 // preserve compatible window flag if exists.
590 int compatibleWindowFlag =
591 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700593 mWindowAttributes.flags |= compatibleWindowFlag;
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 if (newView) {
596 mSoftInputMode = attrs.softInputMode;
597 requestLayout();
598 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700599 // Don't lose the mode we last auto-computed.
600 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
601 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
602 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
603 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
604 | (oldSoftInputMode
605 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 mWindowAttributesChanged = true;
608 scheduleTraversals();
609 }
610 }
611
612 void handleAppVisibility(boolean visible) {
613 if (mAppVisible != visible) {
614 mAppVisible = visible;
615 scheduleTraversals();
616 }
617 }
618
619 void handleGetNewSurface() {
620 mNewSurfaceNeeded = true;
621 mFullRedrawNeeded = true;
622 scheduleTraversals();
623 }
624
625 /**
626 * {@inheritDoc}
627 */
628 public void requestLayout() {
629 checkThread();
630 mLayoutRequested = true;
631 scheduleTraversals();
632 }
633
634 /**
635 * {@inheritDoc}
636 */
637 public boolean isLayoutRequested() {
638 return mLayoutRequested;
639 }
640
641 public void invalidateChild(View child, Rect dirty) {
642 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700643 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
644 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700646 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700647 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700648 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700649 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700650 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700651 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700652 }
Romain Guy1e095972009-07-07 11:22:45 -0700653 if (mAttachInfo.mScalingRequired) {
654 dirty.inset(-1, -1);
655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 }
657 mDirty.union(dirty);
658 if (!mWillDrawSoon) {
659 scheduleTraversals();
660 }
661 }
662
663 public ViewParent getParent() {
664 return null;
665 }
666
667 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
668 invalidateChild(null, dirty);
669 return null;
670 }
671
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700672 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 if (child != mView) {
674 throw new RuntimeException("child is not mine, honest!");
675 }
676 // Note: don't apply scroll offset, because we want to know its
677 // visibility in the virtual canvas being given to the view hierarchy.
678 return r.intersect(0, 0, mWidth, mHeight);
679 }
680
681 public void bringChildToFront(View child) {
682 }
683
684 public void scheduleTraversals() {
685 if (!mTraversalScheduled) {
686 mTraversalScheduled = true;
687 sendEmptyMessage(DO_TRAVERSAL);
688 }
689 }
690
691 public void unscheduleTraversals() {
692 if (mTraversalScheduled) {
693 mTraversalScheduled = false;
694 removeMessages(DO_TRAVERSAL);
695 }
696 }
697
698 int getHostVisibility() {
699 return mAppVisible ? mView.getVisibility() : View.GONE;
700 }
Romain Guy8506ab42009-06-11 17:35:47 -0700701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 private void performTraversals() {
703 // cache mView since it is used so much below...
704 final View host = mView;
705
706 if (DBG) {
707 System.out.println("======================================");
708 System.out.println("performTraversals");
709 host.debug();
710 }
711
712 if (host == null || !mAdded)
713 return;
714
715 mTraversalScheduled = false;
716 mWillDrawSoon = true;
717 boolean windowResizesToFitContent = false;
718 boolean fullRedrawNeeded = mFullRedrawNeeded;
719 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700720 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 WindowManager.LayoutParams lp = mWindowAttributes;
722
723 int desiredWindowWidth;
724 int desiredWindowHeight;
725 int childWidthMeasureSpec;
726 int childHeightMeasureSpec;
727
728 final View.AttachInfo attachInfo = mAttachInfo;
729
730 final int viewVisibility = getHostVisibility();
731 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
732 || mNewSurfaceNeeded;
733
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700734 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 WindowManager.LayoutParams params = null;
737 if (mWindowAttributesChanged) {
738 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700739 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 params = lp;
741 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700742 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 if (mFirst) {
744 fullRedrawNeeded = true;
745 mLayoutRequested = true;
746
Romain Guy8506ab42009-06-11 17:35:47 -0700747 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700748 mView.getContext().getResources().getDisplayMetrics();
749 desiredWindowWidth = packageMetrics.widthPixels;
750 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
752 // For the very first time, tell the view hierarchy that it
753 // is attached to the window. Note that at this point the surface
754 // object is not initialized to its backing store, but soon it
755 // will be (assuming the window is visible).
756 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700757 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 attachInfo.mHasWindowFocus = false;
759 attachInfo.mWindowVisibility = viewVisibility;
760 attachInfo.mRecomputeGlobalAttributes = false;
761 attachInfo.mKeepScreenOn = false;
762 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700763 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700768 desiredWindowWidth = frame.width();
769 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700771 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700772 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 fullRedrawNeeded = true;
774 mLayoutRequested = true;
775 windowResizesToFitContent = true;
776 }
777 }
778
779 if (viewVisibilityChanged) {
780 attachInfo.mWindowVisibility = viewVisibility;
781 host.dispatchWindowVisibilityChanged(viewVisibility);
782 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
783 if (mUseGL) {
784 destroyGL();
785 }
786 }
787 if (viewVisibility == View.GONE) {
788 // After making a window gone, we will count it as being
789 // shown for the first time the next time it gets focus.
790 mHasHadWindowFocus = false;
791 }
792 }
793
794 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700797 // Execute enqueued actions on every layout in case a view that was detached
798 // enqueued an action after being detached
799 getRunQueue().executeActions(attachInfo.mHandler);
800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 if (mFirst) {
802 host.fitSystemWindows(mAttachInfo.mContentInsets);
803 // make sure touch mode code executes by setting cached value
804 // to opposite of the added touch mode.
805 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700806 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 } else {
808 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
809 mAttachInfo.mContentInsets.set(mPendingContentInsets);
810 host.fitSystemWindows(mAttachInfo.mContentInsets);
811 insetsChanged = true;
812 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
813 + mAttachInfo.mContentInsets);
814 }
815 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
816 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
817 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
818 + mAttachInfo.mVisibleInsets);
819 }
820 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
821 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
822 windowResizesToFitContent = true;
823
Romain Guy8506ab42009-06-11 17:35:47 -0700824 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700825 mView.getContext().getResources().getDisplayMetrics();
826 desiredWindowWidth = packageMetrics.widthPixels;
827 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829 }
830
831 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
832 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
833
834 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700835 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 "Measuring " + host + " in display " + desiredWindowWidth
837 + "x" + desiredWindowHeight + "...");
838 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
839
840 if (DBG) {
841 System.out.println("======================================");
842 System.out.println("performTraversals -- after measure");
843 host.debug();
844 }
845 }
846
847 if (attachInfo.mRecomputeGlobalAttributes) {
848 //Log.i(TAG, "Computing screen on!");
849 attachInfo.mRecomputeGlobalAttributes = false;
850 boolean oldVal = attachInfo.mKeepScreenOn;
851 attachInfo.mKeepScreenOn = false;
852 host.dispatchCollectViewAttributes(0);
853 if (attachInfo.mKeepScreenOn != oldVal) {
854 params = lp;
855 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
856 }
857 }
858
859 if (mFirst || attachInfo.mViewVisibilityChanged) {
860 attachInfo.mViewVisibilityChanged = false;
861 int resizeMode = mSoftInputMode &
862 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
863 // If we are in auto resize mode, then we need to determine
864 // what mode to use now.
865 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
866 final int N = attachInfo.mScrollContainers.size();
867 for (int i=0; i<N; i++) {
868 if (attachInfo.mScrollContainers.get(i).isShown()) {
869 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
870 }
871 }
872 if (resizeMode == 0) {
873 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
874 }
875 if ((lp.softInputMode &
876 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
877 lp.softInputMode = (lp.softInputMode &
878 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
879 resizeMode;
880 params = lp;
881 }
882 }
883 }
Romain Guy8506ab42009-06-11 17:35:47 -0700884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
886 if (!PixelFormat.formatHasAlpha(params.format)) {
887 params.format = PixelFormat.TRANSLUCENT;
888 }
889 }
890
891 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700892 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
893 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
894 frame.width() < desiredWindowWidth && frame.width() != mWidth)
895 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
896 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897
898 final boolean computesInternalInsets =
899 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
900 boolean insetsPending = false;
901 int relayoutResult = 0;
902 if (mFirst || windowShouldResize || insetsChanged
903 || viewVisibilityChanged || params != null) {
904
905 if (viewVisibility == View.VISIBLE) {
906 // If this window is giving internal insets to the window
907 // manager, and it is being added or changing its visibility,
908 // then we want to first give the window manager "fake"
909 // insets to cause it to effectively ignore the content of
910 // the window during layout. This avoids it briefly causing
911 // other windows to resize/move based on the raw frame of the
912 // window, waiting until we can finish laying out this window
913 // and get back to the window manager with the ultimately
914 // computed insets.
915 insetsPending = computesInternalInsets
916 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
919 if (params == null) {
920 params = mWindowAttributes;
921 }
922 mGlWanted = true;
923 }
924 }
925
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700926 if (mSurfaceHolder != null) {
927 mSurfaceHolder.mSurfaceLock.lock();
928 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700929 }
930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 boolean initialized = false;
932 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700933 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700934 boolean hadSurface = mSurface.isValid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 int fl = 0;
937 if (params != null) {
938 fl = params.flags;
939 if (attachInfo.mKeepScreenOn) {
940 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
941 }
942 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700943 if (DEBUG_LAYOUT) {
944 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
945 host.mMeasuredHeight + ", params=" + params);
946 }
947 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 if (params != null) {
950 params.flags = fl;
951 }
952
953 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
954 + " content=" + mPendingContentInsets.toShortString()
955 + " visible=" + mPendingVisibleInsets.toShortString()
956 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700957
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700958 if (mPendingConfiguration.seq != 0) {
959 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
960 + mPendingConfiguration);
961 updateConfiguration(mPendingConfiguration, !mFirst);
962 mPendingConfiguration.seq = 0;
963 }
964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 contentInsetsChanged = !mPendingContentInsets.equals(
966 mAttachInfo.mContentInsets);
967 visibleInsetsChanged = !mPendingVisibleInsets.equals(
968 mAttachInfo.mVisibleInsets);
969 if (contentInsetsChanged) {
970 mAttachInfo.mContentInsets.set(mPendingContentInsets);
971 host.fitSystemWindows(mAttachInfo.mContentInsets);
972 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
973 + mAttachInfo.mContentInsets);
974 }
975 if (visibleInsetsChanged) {
976 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
977 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
978 + mAttachInfo.mVisibleInsets);
979 }
980
981 if (!hadSurface) {
982 if (mSurface.isValid()) {
983 // If we are creating a new surface, then we need to
984 // completely redraw it. Also, when we get to the
985 // point of drawing it we will hold off and schedule
986 // a new traversal instead. This is so we can tell the
987 // window manager about all of the windows being displayed
988 // before actually drawing them, so it can display then
989 // all at once.
990 newSurface = true;
991 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700992 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 if (mGlWanted && !mUseGL) {
995 initializeGL();
996 initialized = mGlCanvas != null;
997 }
998 }
999 } else if (!mSurface.isValid()) {
1000 // If the surface has been removed, then reset the scroll
1001 // positions.
1002 mLastScrolledFocus = null;
1003 mScrollY = mCurScrollY = 0;
1004 if (mScroller != null) {
1005 mScroller.abortAnimation();
1006 }
1007 }
1008 } catch (RemoteException e) {
1009 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001012 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013
1014 attachInfo.mWindowLeft = frame.left;
1015 attachInfo.mWindowTop = frame.top;
1016
1017 // !!FIXME!! This next section handles the case where we did not get the
1018 // window size we asked for. We should avoid this by getting a maximum size from
1019 // the window session beforehand.
1020 mWidth = frame.width();
1021 mHeight = frame.height();
1022
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001023 if (mSurfaceHolder != null) {
1024 // The app owns the surface; tell it about what is going on.
1025 if (mSurface.isValid()) {
1026 // XXX .copyFrom() doesn't work!
1027 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1028 mSurfaceHolder.mSurface = mSurface;
1029 }
1030 mSurfaceHolder.mSurfaceLock.unlock();
1031 if (mSurface.isValid()) {
1032 if (!hadSurface) {
1033 mSurfaceHolder.ungetCallbacks();
1034
1035 mIsCreating = true;
1036 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1037 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1038 if (callbacks != null) {
1039 for (SurfaceHolder.Callback c : callbacks) {
1040 c.surfaceCreated(mSurfaceHolder);
1041 }
1042 }
1043 surfaceChanged = true;
1044 }
1045 if (surfaceChanged) {
1046 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1047 lp.format, mWidth, mHeight);
1048 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1049 if (callbacks != null) {
1050 for (SurfaceHolder.Callback c : callbacks) {
1051 c.surfaceChanged(mSurfaceHolder, lp.format,
1052 mWidth, mHeight);
1053 }
1054 }
1055 }
1056 mIsCreating = false;
1057 } else if (hadSurface) {
1058 mSurfaceHolder.ungetCallbacks();
1059 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1060 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1061 if (callbacks != null) {
1062 for (SurfaceHolder.Callback c : callbacks) {
1063 c.surfaceDestroyed(mSurfaceHolder);
1064 }
1065 }
1066 mSurfaceHolder.mSurfaceLock.lock();
1067 // Make surface invalid.
1068 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1069 mSurfaceHolder.mSurface = new Surface();
1070 mSurfaceHolder.mSurfaceLock.unlock();
1071 }
1072 }
1073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001075 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
1076 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078
1079 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001080 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1082 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1083 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1084 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1085
1086 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1087 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1088 + " mHeight=" + mHeight
1089 + " measuredHeight" + host.mMeasuredHeight
1090 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 // Ask host how big it wants to be
1093 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1094
1095 // Implementation of weights from WindowManager.LayoutParams
1096 // We just grow the dimensions as needed and re-measure if
1097 // needs be
1098 int width = host.mMeasuredWidth;
1099 int height = host.mMeasuredHeight;
1100 boolean measureAgain = false;
1101
1102 if (lp.horizontalWeight > 0.0f) {
1103 width += (int) ((mWidth - width) * lp.horizontalWeight);
1104 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1105 MeasureSpec.EXACTLY);
1106 measureAgain = true;
1107 }
1108 if (lp.verticalWeight > 0.0f) {
1109 height += (int) ((mHeight - height) * lp.verticalWeight);
1110 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1111 MeasureSpec.EXACTLY);
1112 measureAgain = true;
1113 }
1114
1115 if (measureAgain) {
1116 if (DEBUG_LAYOUT) Log.v(TAG,
1117 "And hey let's measure once more: width=" + width
1118 + " height=" + height);
1119 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1120 }
1121
1122 mLayoutRequested = true;
1123 }
1124 }
1125
1126 final boolean didLayout = mLayoutRequested;
1127 boolean triggerGlobalLayoutListener = didLayout
1128 || attachInfo.mRecomputeGlobalAttributes;
1129 if (didLayout) {
1130 mLayoutRequested = false;
1131 mScrollMayChange = true;
1132 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001133 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001135 long startTime = 0L;
1136 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 startTime = SystemClock.elapsedRealtime();
1138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1140
Romain Guy13922e02009-05-12 17:56:14 -07001141 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1142 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1143 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1144 + "please refer to the logs with the tag "
1145 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1146 }
1147 }
1148
1149 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1151 }
1152
1153 // By this point all views have been sized and positionned
1154 // We can compute the transparent area
1155
1156 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1157 // start out transparent
1158 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1159 host.getLocationInWindow(mTmpLocation);
1160 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1161 mTmpLocation[0] + host.mRight - host.mLeft,
1162 mTmpLocation[1] + host.mBottom - host.mTop);
1163
1164 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001165 if (mTranslator != null) {
1166 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1167 }
1168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1170 mPreviousTransparentRegion.set(mTransparentRegion);
1171 // reconfigure window manager
1172 try {
1173 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1174 } catch (RemoteException e) {
1175 }
1176 }
1177 }
1178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 if (DBG) {
1180 System.out.println("======================================");
1181 System.out.println("performTraversals -- after setFrame");
1182 host.debug();
1183 }
1184 }
1185
1186 if (triggerGlobalLayoutListener) {
1187 attachInfo.mRecomputeGlobalAttributes = false;
1188 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1189 }
1190
1191 if (computesInternalInsets) {
1192 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1193 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1194 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1195 givenContent.left = givenContent.top = givenContent.right
1196 = givenContent.bottom = givenVisible.left = givenVisible.top
1197 = givenVisible.right = givenVisible.bottom = 0;
1198 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001199 Rect contentInsets = insets.contentInsets;
1200 Rect visibleInsets = insets.visibleInsets;
1201 if (mTranslator != null) {
1202 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1203 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1206 mLastGivenInsets.set(insets);
1207 try {
1208 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001209 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 } catch (RemoteException e) {
1211 }
1212 }
1213 }
Romain Guy8506ab42009-06-11 17:35:47 -07001214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 if (mFirst) {
1216 // handle first focus request
1217 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1218 + mView.hasFocus());
1219 if (mView != null) {
1220 if (!mView.hasFocus()) {
1221 mView.requestFocus(View.FOCUS_FORWARD);
1222 mFocusedView = mRealFocusedView = mView.findFocus();
1223 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1224 + mFocusedView);
1225 } else {
1226 mRealFocusedView = mView.findFocus();
1227 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1228 + mRealFocusedView);
1229 }
1230 }
1231 }
1232
1233 mFirst = false;
1234 mWillDrawSoon = false;
1235 mNewSurfaceNeeded = false;
1236 mViewVisibility = viewVisibility;
1237
1238 if (mAttachInfo.mHasWindowFocus) {
1239 final boolean imTarget = WindowManager.LayoutParams
1240 .mayUseInputMethod(mWindowAttributes.flags);
1241 if (imTarget != mLastWasImTarget) {
1242 mLastWasImTarget = imTarget;
1243 InputMethodManager imm = InputMethodManager.peekInstance();
1244 if (imm != null && imTarget) {
1245 imm.startGettingWindowFocus(mView);
1246 imm.onWindowFocus(mView, mView.findFocus(),
1247 mWindowAttributes.softInputMode,
1248 !mHasHadWindowFocus, mWindowAttributes.flags);
1249 }
1250 }
1251 }
Romain Guy8506ab42009-06-11 17:35:47 -07001252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1254
1255 if (!cancelDraw && !newSurface) {
1256 mFullRedrawNeeded = false;
1257 draw(fullRedrawNeeded);
1258
1259 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1260 || mReportNextDraw) {
1261 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001262 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
1264 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001265 if (mSurfaceHolder != null && mSurface.isValid()) {
1266 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1267 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1268 if (callbacks != null) {
1269 for (SurfaceHolder.Callback c : callbacks) {
1270 if (c instanceof SurfaceHolder.Callback2) {
1271 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1272 mSurfaceHolder);
1273 }
1274 }
1275 }
1276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 try {
1278 sWindowSession.finishDrawing(mWindow);
1279 } catch (RemoteException e) {
1280 }
1281 }
1282 } else {
1283 // We were supposed to report when we are done drawing. Since we canceled the
1284 // draw, remember it here.
1285 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1286 mReportNextDraw = true;
1287 }
1288 if (fullRedrawNeeded) {
1289 mFullRedrawNeeded = true;
1290 }
1291 // Try again
1292 scheduleTraversals();
1293 }
1294 }
1295
1296 public void requestTransparentRegion(View child) {
1297 // the test below should not fail unless someone is messing with us
1298 checkThread();
1299 if (mView == child) {
1300 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1301 // Need to make sure we re-evaluate the window attributes next
1302 // time around, to ensure the window has the correct format.
1303 mWindowAttributesChanged = true;
1304 }
1305 }
1306
1307 /**
1308 * Figures out the measure spec for the root view in a window based on it's
1309 * layout params.
1310 *
1311 * @param windowSize
1312 * The available width or height of the window
1313 *
1314 * @param rootDimension
1315 * The layout params for one dimension (width or height) of the
1316 * window.
1317 *
1318 * @return The measure spec to use to measure the root view.
1319 */
1320 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1321 int measureSpec;
1322 switch (rootDimension) {
1323
Romain Guy980a9382010-01-08 15:06:28 -08001324 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 // Window can't resize. Force root view to be windowSize.
1326 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1327 break;
1328 case ViewGroup.LayoutParams.WRAP_CONTENT:
1329 // Window can resize. Set max size for root view.
1330 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1331 break;
1332 default:
1333 // Window wants to be an exact size. Force root view to be that size.
1334 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1335 break;
1336 }
1337 return measureSpec;
1338 }
1339
1340 private void draw(boolean fullRedrawNeeded) {
1341 Surface surface = mSurface;
1342 if (surface == null || !surface.isValid()) {
1343 return;
1344 }
1345
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001346 if (!sFirstDrawComplete) {
1347 synchronized (sFirstDrawHandlers) {
1348 sFirstDrawComplete = true;
1349 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1350 post(sFirstDrawHandlers.get(i));
1351 }
1352 }
1353 }
1354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 scrollToRectOrFocus(null, false);
1356
1357 if (mAttachInfo.mViewScrollChanged) {
1358 mAttachInfo.mViewScrollChanged = false;
1359 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1360 }
Romain Guy8506ab42009-06-11 17:35:47 -07001361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001363 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 if (scrolling) {
1365 yoff = mScroller.getCurrY();
1366 } else {
1367 yoff = mScrollY;
1368 }
1369 if (mCurScrollY != yoff) {
1370 mCurScrollY = yoff;
1371 fullRedrawNeeded = true;
1372 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001373 float appScale = mAttachInfo.mApplicationScale;
1374 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375
1376 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001377 if (mSurfaceHolder != null) {
1378 // The app owns the surface, we won't draw.
1379 dirty.setEmpty();
1380 return;
1381 }
1382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 if (mUseGL) {
1384 if (!dirty.isEmpty()) {
1385 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001386 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 mGL.glDisable(GL_SCISSOR_TEST);
1388 mGL.glClearColor(0, 0, 0, 0);
1389 mGL.glClear(GL_COLOR_BUFFER_BIT);
1390 mGL.glEnable(GL_SCISSOR_TEST);
1391
1392 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001393 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001395
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001396 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1397 try {
1398 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001399 if (mTranslator != null) {
1400 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001401 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001402 canvas.setScreenDensity(scalingRequired
1403 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001404 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001405 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1406 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1407 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001408 } finally {
1409 canvas.restoreToCount(saveCount);
1410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411
Romain Guy5bcdff42009-05-14 21:27:18 -07001412 mAttachInfo.mIgnoreDirtyState = false;
1413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1415 checkEglErrors();
1416
Mike Reedfd716532009-10-12 14:42:56 -04001417 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 int now = (int)SystemClock.elapsedRealtime();
1419 if (sDrawTime != 0) {
1420 nativeShowFPS(canvas, now - sDrawTime);
1421 }
1422 sDrawTime = now;
1423 }
1424 }
1425 }
1426 if (scrolling) {
1427 mFullRedrawNeeded = true;
1428 scheduleTraversals();
1429 }
1430 return;
1431 }
1432
Romain Guy5bcdff42009-05-14 21:27:18 -07001433 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001434 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001435 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437
1438 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001439 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 + mWindowAttributes.getTitle()
1441 + ": dirty={" + dirty.left + "," + dirty.top
1442 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001443 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1444 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
1446
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001447 if (!dirty.isEmpty() || mIsAnimating) {
1448 Canvas canvas;
1449 try {
1450 int left = dirty.left;
1451 int top = dirty.top;
1452 int right = dirty.right;
1453 int bottom = dirty.bottom;
1454 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001455
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001456 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1457 bottom != dirty.bottom) {
1458 mAttachInfo.mIgnoreDirtyState = true;
1459 }
1460
1461 // TODO: Do this in native
1462 canvas.setDensity(mDensity);
1463 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001464 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001465 // TODO: we should ask the window manager to do something!
1466 // for now we just do nothing
1467 return;
1468 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001469 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001470 // TODO: we should ask the window manager to do something!
1471 // for now we just do nothing
1472 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001473 }
1474
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001475 try {
1476 if (!dirty.isEmpty() || mIsAnimating) {
1477 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001479 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001480 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001481 + canvas.getWidth() + ", h=" + canvas.getHeight());
1482 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001485 if (Config.DEBUG && ViewDebug.profileDrawing) {
1486 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001488
1489 // If this bitmap's format includes an alpha channel, we
1490 // need to clear it before drawing so that the child will
1491 // properly re-composite its drawing on a transparent
1492 // background. This automatically respects the clip/dirty region
1493 // or
1494 // If we are applying an offset, we need to clear the area
1495 // where the offset doesn't appear to avoid having garbage
1496 // left in the blank areas.
1497 if (!canvas.isOpaque() || yoff != 0) {
1498 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1499 }
1500
1501 dirty.setEmpty();
1502 mIsAnimating = false;
1503 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1504 mView.mPrivateFlags |= View.DRAWN;
1505
1506 if (DEBUG_DRAW) {
1507 Context cxt = mView.getContext();
1508 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1509 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1510 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1511 }
1512 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1513 try {
1514 canvas.translate(0, -yoff);
1515 if (mTranslator != null) {
1516 mTranslator.translateCanvas(canvas);
1517 }
1518 canvas.setScreenDensity(scalingRequired
1519 ? DisplayMetrics.DENSITY_DEVICE : 0);
1520 mView.draw(canvas);
1521 } finally {
1522 mAttachInfo.mIgnoreDirtyState = false;
1523 canvas.restoreToCount(saveCount);
1524 }
1525
1526 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1527 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1528 }
1529
1530 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1531 int now = (int)SystemClock.elapsedRealtime();
1532 if (sDrawTime != 0) {
1533 nativeShowFPS(canvas, now - sDrawTime);
1534 }
1535 sDrawTime = now;
1536 }
1537
1538 if (Config.DEBUG && ViewDebug.profileDrawing) {
1539 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001543 } finally {
1544 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547
1548 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001549 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
Romain Guy8506ab42009-06-11 17:35:47 -07001551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 if (scrolling) {
1553 mFullRedrawNeeded = true;
1554 scheduleTraversals();
1555 }
1556 }
1557
1558 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1559 final View.AttachInfo attachInfo = mAttachInfo;
1560 final Rect ci = attachInfo.mContentInsets;
1561 final Rect vi = attachInfo.mVisibleInsets;
1562 int scrollY = 0;
1563 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 if (vi.left > ci.left || vi.top > ci.top
1566 || vi.right > ci.right || vi.bottom > ci.bottom) {
1567 // We'll assume that we aren't going to change the scroll
1568 // offset, since we want to avoid that unless it is actually
1569 // going to make the focus visible... otherwise we scroll
1570 // all over the place.
1571 scrollY = mScrollY;
1572 // We can be called for two different situations: during a draw,
1573 // to update the scroll position if the focus has changed (in which
1574 // case 'rectangle' is null), or in response to a
1575 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1576 // is non-null and we just want to scroll to whatever that
1577 // rectangle is).
1578 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001579
1580 // When in touch mode, focus points to the previously focused view,
1581 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001582 // line checks whether the view is still in our hierarchy.
1583 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001584 mRealFocusedView = null;
1585 return false;
1586 }
1587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 if (focus != mLastScrolledFocus) {
1589 // If the focus has changed, then ignore any requests to scroll
1590 // to a rectangle; first we want to make sure the entire focus
1591 // view is visible.
1592 rectangle = null;
1593 }
1594 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1595 + " rectangle=" + rectangle + " ci=" + ci
1596 + " vi=" + vi);
1597 if (focus == mLastScrolledFocus && !mScrollMayChange
1598 && rectangle == null) {
1599 // Optimization: if the focus hasn't changed since last
1600 // time, and no layout has happened, then just leave things
1601 // as they are.
1602 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1603 + mScrollY + " vi=" + vi.toShortString());
1604 } else if (focus != null) {
1605 // We need to determine if the currently focused view is
1606 // within the visible part of the window and, if not, apply
1607 // a pan so it can be seen.
1608 mLastScrolledFocus = focus;
1609 mScrollMayChange = false;
1610 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1611 // Try to find the rectangle from the focus view.
1612 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1613 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1614 + mView.getWidth() + " h=" + mView.getHeight()
1615 + " ci=" + ci.toShortString()
1616 + " vi=" + vi.toShortString());
1617 if (rectangle == null) {
1618 focus.getFocusedRect(mTempRect);
1619 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1620 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001621 if (mView instanceof ViewGroup) {
1622 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1623 focus, mTempRect);
1624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1626 "Focus in window: focusRect="
1627 + mTempRect.toShortString()
1628 + " visRect=" + mVisRect.toShortString());
1629 } else {
1630 mTempRect.set(rectangle);
1631 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1632 "Request scroll to rect: "
1633 + mTempRect.toShortString()
1634 + " visRect=" + mVisRect.toShortString());
1635 }
1636 if (mTempRect.intersect(mVisRect)) {
1637 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1638 "Focus window visible rect: "
1639 + mTempRect.toShortString());
1640 if (mTempRect.height() >
1641 (mView.getHeight()-vi.top-vi.bottom)) {
1642 // If the focus simply is not going to fit, then
1643 // best is probably just to leave things as-is.
1644 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1645 "Too tall; leaving scrollY=" + scrollY);
1646 } else if ((mTempRect.top-scrollY) < vi.top) {
1647 scrollY -= vi.top - (mTempRect.top-scrollY);
1648 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1649 "Top covered; scrollY=" + scrollY);
1650 } else if ((mTempRect.bottom-scrollY)
1651 > (mView.getHeight()-vi.bottom)) {
1652 scrollY += (mTempRect.bottom-scrollY)
1653 - (mView.getHeight()-vi.bottom);
1654 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1655 "Bottom covered; scrollY=" + scrollY);
1656 }
1657 handled = true;
1658 }
1659 }
1660 }
1661 }
Romain Guy8506ab42009-06-11 17:35:47 -07001662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 if (scrollY != mScrollY) {
1664 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1665 + mScrollY + " , new=" + scrollY);
1666 if (!immediate) {
1667 if (mScroller == null) {
1668 mScroller = new Scroller(mView.getContext());
1669 }
1670 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1671 } else if (mScroller != null) {
1672 mScroller.abortAnimation();
1673 }
1674 mScrollY = scrollY;
1675 }
Romain Guy8506ab42009-06-11 17:35:47 -07001676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 return handled;
1678 }
Romain Guy8506ab42009-06-11 17:35:47 -07001679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 public void requestChildFocus(View child, View focused) {
1681 checkThread();
1682 if (mFocusedView != focused) {
1683 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1684 scheduleTraversals();
1685 }
1686 mFocusedView = mRealFocusedView = focused;
1687 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1688 + mFocusedView);
1689 }
1690
1691 public void clearChildFocus(View child) {
1692 checkThread();
1693
1694 View oldFocus = mFocusedView;
1695
1696 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1697 mFocusedView = mRealFocusedView = null;
1698 if (mView != null && !mView.hasFocus()) {
1699 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1700 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1701 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1702 }
1703 } else if (oldFocus != null) {
1704 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1705 }
1706 }
1707
1708
1709 public void focusableViewAvailable(View v) {
1710 checkThread();
1711
1712 if (mView != null && !mView.hasFocus()) {
1713 v.requestFocus();
1714 } else {
1715 // the one case where will transfer focus away from the current one
1716 // is if the current view is a view group that prefers to give focus
1717 // to its children first AND the view is a descendant of it.
1718 mFocusedView = mView.findFocus();
1719 boolean descendantsHaveDibsOnFocus =
1720 (mFocusedView instanceof ViewGroup) &&
1721 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1722 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1723 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1724 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1725 v.requestFocus();
1726 }
1727 }
1728 }
1729
1730 public void recomputeViewAttributes(View child) {
1731 checkThread();
1732 if (mView == child) {
1733 mAttachInfo.mRecomputeGlobalAttributes = true;
1734 if (!mWillDrawSoon) {
1735 scheduleTraversals();
1736 }
1737 }
1738 }
1739
1740 void dispatchDetachedFromWindow() {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001741 if (Config.LOGV) Log.v(TAG, "Detaching in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742
1743 if (mView != null) {
1744 mView.dispatchDetachedFromWindow();
1745 }
1746
1747 mView = null;
1748 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001749 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750
1751 if (mUseGL) {
1752 destroyGL();
1753 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001754 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001756 if (mInputChannel != null) {
1757 if (mInputQueueCallback != null) {
1758 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1759 mInputQueueCallback = null;
1760 } else {
1761 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001762 }
1763 }
1764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 try {
1766 sWindowSession.remove(mWindow);
1767 } catch (RemoteException e) {
1768 }
Jeff Brown349703e2010-06-22 01:27:15 -07001769
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001770 // Dispose the input channel after removing the window so the Window Manager
1771 // doesn't interpret the input channel being closed as an abnormal termination.
1772 if (mInputChannel != null) {
1773 mInputChannel.dispose();
1774 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
Romain Guy8506ab42009-06-11 17:35:47 -07001777
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001778 void updateConfiguration(Configuration config, boolean force) {
1779 if (DEBUG_CONFIGURATION) Log.v(TAG,
1780 "Applying new config to window "
1781 + mWindowAttributes.getTitle()
1782 + ": " + config);
1783 synchronized (sConfigCallbacks) {
1784 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1785 sConfigCallbacks.get(i).onConfigurationChanged(config);
1786 }
1787 }
1788 if (mView != null) {
1789 // At this point the resources have been updated to
1790 // have the most recent config, whatever that is. Use
1791 // the on in them which may be newer.
1792 if (mView != null) {
1793 config = mView.getResources().getConfiguration();
1794 }
1795 if (force || mLastConfiguration.diff(config) != 0) {
1796 mLastConfiguration.setTo(config);
1797 mView.dispatchConfigurationChanged(config);
1798 }
1799 }
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 /**
1803 * Return true if child is an ancestor of parent, (or equal to the parent).
1804 */
1805 private static boolean isViewDescendantOf(View child, View parent) {
1806 if (child == parent) {
1807 return true;
1808 }
1809
1810 final ViewParent theParent = child.getParent();
1811 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1812 }
1813
Romain Guycdb86672010-03-18 18:54:50 -07001814 private static void forceLayout(View view) {
1815 view.forceLayout();
1816 if (view instanceof ViewGroup) {
1817 ViewGroup group = (ViewGroup) view;
1818 final int count = group.getChildCount();
1819 for (int i = 0; i < count; i++) {
1820 forceLayout(group.getChildAt(i));
1821 }
1822 }
1823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824
1825 public final static int DO_TRAVERSAL = 1000;
1826 public final static int DIE = 1001;
1827 public final static int RESIZED = 1002;
1828 public final static int RESIZED_REPORT = 1003;
1829 public final static int WINDOW_FOCUS_CHANGED = 1004;
1830 public final static int DISPATCH_KEY = 1005;
1831 public final static int DISPATCH_POINTER = 1006;
1832 public final static int DISPATCH_TRACKBALL = 1007;
1833 public final static int DISPATCH_APP_VISIBILITY = 1008;
1834 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1835 public final static int FINISHED_EVENT = 1010;
1836 public final static int DISPATCH_KEY_FROM_IME = 1011;
1837 public final static int FINISH_INPUT_CONNECTION = 1012;
1838 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001839 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840
1841 @Override
1842 public void handleMessage(Message msg) {
1843 switch (msg.what) {
1844 case View.AttachInfo.INVALIDATE_MSG:
1845 ((View) msg.obj).invalidate();
1846 break;
1847 case View.AttachInfo.INVALIDATE_RECT_MSG:
1848 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1849 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1850 info.release();
1851 break;
1852 case DO_TRAVERSAL:
1853 if (mProfile) {
1854 Debug.startMethodTracing("ViewRoot");
1855 }
1856
1857 performTraversals();
1858
1859 if (mProfile) {
1860 Debug.stopMethodTracing();
1861 mProfile = false;
1862 }
1863 break;
1864 case FINISHED_EVENT:
1865 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1866 break;
1867 case DISPATCH_KEY:
1868 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001869 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 + msg.obj + " to " + mView);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001871 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001873 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001874 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001876 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001878 event.recycle();
Jeff Brown93ed4e32010-09-23 13:51:48 -07001879 if (msg.arg1 != 0) {
1880 finishInputEvent();
1881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001884 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001885 case DISPATCH_TRACKBALL: {
1886 MotionEvent event = (MotionEvent) msg.obj;
1887 try {
1888 deliverTrackballEvent(event);
1889 } finally {
1890 event.recycle();
Jeff Brown93ed4e32010-09-23 13:51:48 -07001891 if (msg.arg1 != 0) {
1892 finishInputEvent();
1893 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001894 }
1895 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 case DISPATCH_APP_VISIBILITY:
1897 handleAppVisibility(msg.arg1 != 0);
1898 break;
1899 case DISPATCH_GET_NEW_SURFACE:
1900 handleGetNewSurface();
1901 break;
1902 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001903 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001906 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001907 && mPendingVisibleInsets.equals(ri.visibleInsets)
1908 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 break;
1910 }
1911 // fall through...
1912 case RESIZED_REPORT:
1913 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001914 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1915 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001916 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 mWinFrame.left = 0;
1919 mWinFrame.right = msg.arg1;
1920 mWinFrame.top = 0;
1921 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001922 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1923 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 if (msg.what == RESIZED_REPORT) {
1925 mReportNextDraw = true;
1926 }
Romain Guycdb86672010-03-18 18:54:50 -07001927
1928 if (mView != null) {
1929 forceLayout(mView);
1930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 requestLayout();
1932 }
1933 break;
1934 case WINDOW_FOCUS_CHANGED: {
1935 if (mAdded) {
1936 boolean hasWindowFocus = msg.arg1 != 0;
1937 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1938 if (hasWindowFocus) {
1939 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001940 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941
1942 if (mGlWanted) {
1943 checkEglErrors();
1944 // we lost the gl context, so recreate it.
1945 if (mGlWanted && !mUseGL) {
1946 initializeGL();
1947 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001948 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001949 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001950 (int) (mWidth * appScale + 0.5f),
1951 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 }
1953 }
1954 }
1955 }
Romain Guy8506ab42009-06-11 17:35:47 -07001956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 mLastWasImTarget = WindowManager.LayoutParams
1958 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 InputMethodManager imm = InputMethodManager.peekInstance();
1961 if (mView != null) {
1962 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1963 imm.startGettingWindowFocus(mView);
1964 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001965 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 mView.dispatchWindowFocusChanged(hasWindowFocus);
1967 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 // Note: must be done after the focus change callbacks,
1970 // so all of the view state is set up correctly.
1971 if (hasWindowFocus) {
1972 if (imm != null && mLastWasImTarget) {
1973 imm.onWindowFocus(mView, mView.findFocus(),
1974 mWindowAttributes.softInputMode,
1975 !mHasHadWindowFocus, mWindowAttributes.flags);
1976 }
1977 // Clear the forward bit. We can just do this directly, since
1978 // the window manager doesn't care about it.
1979 mWindowAttributes.softInputMode &=
1980 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1981 ((WindowManager.LayoutParams)mView.getLayoutParams())
1982 .softInputMode &=
1983 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1984 mHasHadWindowFocus = true;
1985 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001986
1987 if (hasWindowFocus && mView != null) {
1988 sendAccessibilityEvents();
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
1991 } break;
1992 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001993 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001995 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001997 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001999 KeyEvent event = (KeyEvent)msg.obj;
2000 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2001 // The IME is trying to say this event is from the
2002 // system! Bad bad bad!
2003 event = KeyEvent.changeFlags(event,
2004 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
2005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002007 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 case FINISH_INPUT_CONNECTION: {
2009 InputMethodManager imm = InputMethodManager.peekInstance();
2010 if (imm != null) {
2011 imm.reportFinishInputConnection((InputConnection)msg.obj);
2012 }
2013 } break;
2014 case CHECK_FOCUS: {
2015 InputMethodManager imm = InputMethodManager.peekInstance();
2016 if (imm != null) {
2017 imm.checkFocus();
2018 }
2019 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002020 case CLOSE_SYSTEM_DIALOGS: {
2021 if (mView != null) {
2022 mView.onCloseSystemDialogs((String)msg.obj);
2023 }
2024 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
2026 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002027
Jeff Brown93ed4e32010-09-23 13:51:48 -07002028 private void startInputEvent(Runnable finishedCallback) {
2029 if (mFinishedCallback != null) {
2030 Slog.w(TAG, "Received a new input event from the input queue but there is "
2031 + "already an unfinished input event in progress.");
2032 }
2033
2034 mFinishedCallback = finishedCallback;
2035 }
2036
2037 private void finishInputEvent() {
2038 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002039
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002040 if (mFinishedCallback != null) {
2041 mFinishedCallback.run();
2042 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002043 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002044 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2045 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002046 }
2047 }
2048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 /**
2050 * Something in the current window tells us we need to change the touch mode. For
2051 * example, we are not in touch mode, and the user touches the screen.
2052 *
2053 * If the touch mode has changed, tell the window manager, and handle it locally.
2054 *
2055 * @param inTouchMode Whether we want to be in touch mode.
2056 * @return True if the touch mode changed and focus changed was changed as a result
2057 */
2058 boolean ensureTouchMode(boolean inTouchMode) {
2059 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2060 + "touch mode is " + mAttachInfo.mInTouchMode);
2061 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2062
2063 // tell the window manager
2064 try {
2065 sWindowSession.setInTouchMode(inTouchMode);
2066 } catch (RemoteException e) {
2067 throw new RuntimeException(e);
2068 }
2069
2070 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002071 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073
2074 /**
2075 * Ensure that the touch mode for this window is set, and if it is changing,
2076 * take the appropriate action.
2077 * @param inTouchMode Whether we want to be in touch mode.
2078 * @return True if the touch mode changed and focus changed was changed as a result
2079 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002080 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2082 + "touch mode is " + mAttachInfo.mInTouchMode);
2083
2084 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2085
2086 mAttachInfo.mInTouchMode = inTouchMode;
2087 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2088
Romain Guy2d4cff62010-04-09 15:39:00 -07002089 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091
2092 private boolean enterTouchMode() {
2093 if (mView != null) {
2094 if (mView.hasFocus()) {
2095 // note: not relying on mFocusedView here because this could
2096 // be when the window is first being added, and mFocused isn't
2097 // set yet.
2098 final View focused = mView.findFocus();
2099 if (focused != null && !focused.isFocusableInTouchMode()) {
2100
2101 final ViewGroup ancestorToTakeFocus =
2102 findAncestorToTakeFocusInTouchMode(focused);
2103 if (ancestorToTakeFocus != null) {
2104 // there is an ancestor that wants focus after its descendants that
2105 // is focusable in touch mode.. give it focus
2106 return ancestorToTakeFocus.requestFocus();
2107 } else {
2108 // nothing appropriate to have focus in touch mode, clear it out
2109 mView.unFocus();
2110 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2111 mFocusedView = null;
2112 return true;
2113 }
2114 }
2115 }
2116 }
2117 return false;
2118 }
2119
2120
2121 /**
2122 * Find an ancestor of focused that wants focus after its descendants and is
2123 * focusable in touch mode.
2124 * @param focused The currently focused view.
2125 * @return An appropriate view, or null if no such view exists.
2126 */
2127 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2128 ViewParent parent = focused.getParent();
2129 while (parent instanceof ViewGroup) {
2130 final ViewGroup vgParent = (ViewGroup) parent;
2131 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2132 && vgParent.isFocusableInTouchMode()) {
2133 return vgParent;
2134 }
2135 if (vgParent.isRootNamespace()) {
2136 return null;
2137 } else {
2138 parent = vgParent.getParent();
2139 }
2140 }
2141 return null;
2142 }
2143
2144 private boolean leaveTouchMode() {
2145 if (mView != null) {
2146 if (mView.hasFocus()) {
2147 // i learned the hard way to not trust mFocusedView :)
2148 mFocusedView = mView.findFocus();
2149 if (!(mFocusedView instanceof ViewGroup)) {
2150 // some view has focus, let it keep it
2151 return false;
2152 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2153 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2154 // some view group has focus, and doesn't prefer its children
2155 // over itself for focus, so let them keep it.
2156 return false;
2157 }
2158 }
2159
2160 // find the best view to give focus to in this brave new non-touch-mode
2161 // world
2162 final View focused = focusSearch(null, View.FOCUS_DOWN);
2163 if (focused != null) {
2164 return focused.requestFocus(View.FOCUS_DOWN);
2165 }
2166 }
2167 return false;
2168 }
2169
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002170 private void deliverPointerEvent(MotionEvent event) {
2171 if (mTranslator != null) {
2172 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002174
2175 boolean handled;
2176 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002178 // enter touch mode on the down
2179 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2180 if (isDown) {
2181 ensureTouchMode(true);
2182 }
2183 if(Config.LOGV) {
2184 captureMotionLog("captureDispatchPointer", event);
2185 }
2186 if (mCurScrollY != 0) {
2187 event.offsetLocation(0, mCurScrollY);
2188 }
2189 if (MEASURE_LATENCY) {
2190 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2191 }
2192 handled = mView.dispatchTouchEvent(event);
2193 if (MEASURE_LATENCY) {
2194 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2195 }
2196 if (!handled && isDown) {
2197 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2198
2199 final int edgeFlags = event.getEdgeFlags();
2200 int direction = View.FOCUS_UP;
2201 int x = (int)event.getX();
2202 int y = (int)event.getY();
2203 final int[] deltas = new int[2];
2204
2205 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2206 direction = View.FOCUS_DOWN;
2207 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2208 deltas[0] = edgeSlop;
2209 x += edgeSlop;
2210 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2211 deltas[0] = -edgeSlop;
2212 x -= edgeSlop;
2213 }
2214 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2215 direction = View.FOCUS_UP;
2216 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2217 deltas[0] = edgeSlop;
2218 x += edgeSlop;
2219 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2220 deltas[0] = -edgeSlop;
2221 x -= edgeSlop;
2222 }
2223 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2224 direction = View.FOCUS_RIGHT;
2225 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2226 direction = View.FOCUS_LEFT;
2227 }
2228
2229 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2230 View nearest = FocusFinder.getInstance().findNearestTouchable(
2231 ((ViewGroup) mView), x, y, direction, deltas);
2232 if (nearest != null) {
2233 event.offsetLocation(deltas[0], deltas[1]);
2234 event.setEdgeFlags(0);
2235 mView.dispatchTouchEvent(event);
2236 }
2237 }
2238 }
2239 }
2240 }
2241
2242 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2244
2245 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002246 if (mView != null && mAdded) {
2247 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 // If we reach this, we delivered a trackball event to mView and
2250 // mView consumed it. Because we will not translate the trackball
2251 // event into a key event, touch mode will not exit, so we exit
2252 // touch mode here.
2253 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 return;
2255 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002256
2257 // Otherwise we could do something here, like changing the focus
2258 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 }
2260
2261 final TrackballAxis x = mTrackballAxisX;
2262 final TrackballAxis y = mTrackballAxisY;
2263
2264 long curTime = SystemClock.uptimeMillis();
2265 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2266 // It has been too long since the last movement,
2267 // so restart at the beginning.
2268 x.reset(0);
2269 y.reset(0);
2270 mLastTrackballTime = curTime;
2271 }
2272
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002273 final int action = event.getAction();
2274 final int metastate = event.getMetaState();
2275 switch (action) {
2276 case MotionEvent.ACTION_DOWN:
2277 x.reset(2);
2278 y.reset(2);
2279 deliverKeyEvent(new KeyEvent(curTime, curTime,
2280 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2281 0, metastate), false);
2282 break;
2283 case MotionEvent.ACTION_UP:
2284 x.reset(2);
2285 y.reset(2);
2286 deliverKeyEvent(new KeyEvent(curTime, curTime,
2287 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2288 0, metastate), false);
2289 break;
2290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002292 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2293 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2294 + " move=" + event.getX()
2295 + " / Y=" + y.position + " step="
2296 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2297 + " move=" + event.getY());
2298 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2299 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002301 // Generate DPAD events based on the trackball movement.
2302 // We pick the axis that has moved the most as the direction of
2303 // the DPAD. When we generate DPAD events for one axis, then the
2304 // other axis is reset -- we don't want to perform DPAD jumps due
2305 // to slight movements in the trackball when making major movements
2306 // along the other axis.
2307 int keycode = 0;
2308 int movement = 0;
2309 float accel = 1;
2310 if (xOff > yOff) {
2311 movement = x.generate((2/event.getXPrecision()));
2312 if (movement != 0) {
2313 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2314 : KeyEvent.KEYCODE_DPAD_LEFT;
2315 accel = x.acceleration;
2316 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002318 } else if (yOff > 0) {
2319 movement = y.generate((2/event.getYPrecision()));
2320 if (movement != 0) {
2321 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2322 : KeyEvent.KEYCODE_DPAD_UP;
2323 accel = y.acceleration;
2324 x.reset(2);
2325 }
2326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002328 if (keycode != 0) {
2329 if (movement < 0) movement = -movement;
2330 int accelMovement = (int)(movement * accel);
2331 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2332 + " accelMovement=" + accelMovement
2333 + " accel=" + accel);
2334 if (accelMovement > movement) {
2335 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2336 + keycode);
2337 movement--;
2338 deliverKeyEvent(new KeyEvent(curTime, curTime,
2339 KeyEvent.ACTION_MULTIPLE, keycode,
2340 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002342 while (movement > 0) {
2343 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2344 + keycode);
2345 movement--;
2346 curTime = SystemClock.uptimeMillis();
2347 deliverKeyEvent(new KeyEvent(curTime, curTime,
2348 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2349 deliverKeyEvent(new KeyEvent(curTime, curTime,
2350 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002352 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 }
2354 }
2355
2356 /**
2357 * @param keyCode The key code
2358 * @return True if the key is directional.
2359 */
2360 static boolean isDirectional(int keyCode) {
2361 switch (keyCode) {
2362 case KeyEvent.KEYCODE_DPAD_LEFT:
2363 case KeyEvent.KEYCODE_DPAD_RIGHT:
2364 case KeyEvent.KEYCODE_DPAD_UP:
2365 case KeyEvent.KEYCODE_DPAD_DOWN:
2366 return true;
2367 }
2368 return false;
2369 }
2370
2371 /**
2372 * Returns true if this key is a keyboard key.
2373 * @param keyEvent The key event.
2374 * @return whether this key is a keyboard key.
2375 */
2376 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2377 final int convertedKey = keyEvent.getUnicodeChar();
2378 return convertedKey > 0;
2379 }
2380
2381
2382
2383 /**
2384 * See if the key event means we should leave touch mode (and leave touch
2385 * mode if so).
2386 * @param event The key event.
2387 * @return Whether this key event should be consumed (meaning the act of
2388 * leaving touch mode alone is considered the event).
2389 */
2390 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002391 final int action = event.getAction();
2392 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 return false;
2394 }
2395 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2396 return false;
2397 }
2398
2399 // only relevant if we are in touch mode
2400 if (!mAttachInfo.mInTouchMode) {
2401 return false;
2402 }
2403
2404 // if something like an edit text has focus and the user is typing,
2405 // leave touch mode
2406 //
2407 // note: the condition of not being a keyboard key is kind of a hacky
2408 // approximation of whether we think the focused view will want the
2409 // key; if we knew for sure whether the focused view would consume
2410 // the event, that would be better.
2411 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2412 mFocusedView = mView.findFocus();
2413 if ((mFocusedView instanceof ViewGroup)
2414 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2415 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2416 // something has focus, but is holding it weakly as a container
2417 return false;
2418 }
2419 if (ensureTouchMode(false)) {
2420 throw new IllegalStateException("should not have changed focus "
2421 + "when leaving touch mode while a view has focus.");
2422 }
2423 return false;
2424 }
2425
2426 if (isDirectional(event.getKeyCode())) {
2427 // no view has focus, so we leave touch mode (and find something
2428 // to give focus to). the event is consumed if we were able to
2429 // find something to give focus to.
2430 return ensureTouchMode(false);
2431 }
2432 return false;
2433 }
2434
2435 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002436 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 */
2438 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002439 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 if (ev == null ||
2441 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2442 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 }
Romain Guy8506ab42009-06-11 17:35:47 -07002444
2445 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 sb.append(ev.getDownTime()).append(',');
2447 sb.append(ev.getEventTime()).append(',');
2448 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002449 sb.append(ev.getX()).append(',');
2450 sb.append(ev.getY()).append(',');
2451 sb.append(ev.getPressure()).append(',');
2452 sb.append(ev.getSize()).append(',');
2453 sb.append(ev.getMetaState()).append(',');
2454 sb.append(ev.getXPrecision()).append(',');
2455 sb.append(ev.getYPrecision()).append(',');
2456 sb.append(ev.getDeviceId()).append(',');
2457 sb.append(ev.getEdgeFlags());
2458 Log.d(TAG, sb.toString());
2459 }
2460 /**
2461 * log motion events
2462 */
2463 private static void captureKeyLog(String subTag, KeyEvent ev) {
2464 //check dynamic switch
2465 if (ev == null ||
2466 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2467 return;
2468 }
2469 StringBuilder sb = new StringBuilder(subTag + ": ");
2470 sb.append(ev.getDownTime()).append(',');
2471 sb.append(ev.getEventTime()).append(',');
2472 sb.append(ev.getAction()).append(',');
2473 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 sb.append(ev.getRepeatCount()).append(',');
2475 sb.append(ev.getMetaState()).append(',');
2476 sb.append(ev.getDeviceId()).append(',');
2477 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002478 Log.d(TAG, sb.toString());
2479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480
2481 int enqueuePendingEvent(Object event, boolean sendDone) {
2482 int seq = mPendingEventSeq+1;
2483 if (seq < 0) seq = 0;
2484 mPendingEventSeq = seq;
2485 mPendingEvents.put(seq, event);
2486 return sendDone ? seq : -seq;
2487 }
2488
2489 Object retrievePendingEvent(int seq) {
2490 if (seq < 0) seq = -seq;
2491 Object event = mPendingEvents.get(seq);
2492 if (event != null) {
2493 mPendingEvents.remove(seq);
2494 }
2495 return event;
2496 }
Romain Guy8506ab42009-06-11 17:35:47 -07002497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2499 // If mView is null, we just consume the key event because it doesn't
2500 // make sense to do anything else with it.
2501 boolean handled = mView != null
2502 ? mView.dispatchKeyEventPreIme(event) : true;
2503 if (handled) {
2504 if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002505 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 }
2507 return;
2508 }
2509 // If it is possible for this window to interact with the input
2510 // method window, then we want to first dispatch our key events
2511 // to the input method.
2512 if (mLastWasImTarget) {
2513 InputMethodManager imm = InputMethodManager.peekInstance();
2514 if (imm != null && mView != null) {
2515 int seq = enqueuePendingEvent(event, sendDone);
2516 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2517 + seq + " event=" + event);
2518 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2519 mInputMethodCallback);
2520 return;
2521 }
2522 }
2523 deliverKeyEventToViewHierarchy(event, sendDone);
2524 }
2525
2526 void handleFinishedEvent(int seq, boolean handled) {
2527 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2528 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2529 + " handled=" + handled + " event=" + event);
2530 if (event != null) {
2531 final boolean sendDone = seq >= 0;
2532 if (!handled) {
2533 deliverKeyEventToViewHierarchy(event, sendDone);
2534 return;
2535 } else if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002536 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002538 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 + " handled=" + handled + " ev=" + event
2540 + ") neither delivering nor finishing key");
2541 }
2542 }
2543 }
Romain Guy8506ab42009-06-11 17:35:47 -07002544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2546 try {
2547 if (mView != null && mAdded) {
2548 final int action = event.getAction();
2549 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2550
2551 if (checkForLeavingTouchModeAndConsume(event)) {
2552 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002553 }
2554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 if (Config.LOGV) {
2556 captureKeyLog("captureDispatchKeyEvent", event);
2557 }
2558 boolean keyHandled = mView.dispatchKeyEvent(event);
2559
2560 if (!keyHandled && isDown) {
2561 int direction = 0;
2562 switch (event.getKeyCode()) {
2563 case KeyEvent.KEYCODE_DPAD_LEFT:
2564 direction = View.FOCUS_LEFT;
2565 break;
2566 case KeyEvent.KEYCODE_DPAD_RIGHT:
2567 direction = View.FOCUS_RIGHT;
2568 break;
2569 case KeyEvent.KEYCODE_DPAD_UP:
2570 direction = View.FOCUS_UP;
2571 break;
2572 case KeyEvent.KEYCODE_DPAD_DOWN:
2573 direction = View.FOCUS_DOWN;
2574 break;
2575 }
2576
2577 if (direction != 0) {
2578
2579 View focused = mView != null ? mView.findFocus() : null;
2580 if (focused != null) {
2581 View v = focused.focusSearch(direction);
2582 boolean focusPassed = false;
2583 if (v != null && v != focused) {
2584 // do the math the get the interesting rect
2585 // of previous focused into the coord system of
2586 // newly focused view
2587 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002588 if (mView instanceof ViewGroup) {
2589 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2590 focused, mTempRect);
2591 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2592 v, mTempRect);
2593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 focusPassed = v.requestFocus(direction, mTempRect);
2595 }
2596
2597 if (!focusPassed) {
2598 mView.dispatchUnhandledMove(focused, direction);
2599 } else {
2600 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2601 }
2602 }
2603 }
2604 }
2605 }
2606
2607 } finally {
2608 if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002609 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 }
2611 // Let the exception fall through -- the looper will catch
2612 // it and take care of the bad app for us.
2613 }
2614 }
2615
2616 private AudioManager getAudioManager() {
2617 if (mView == null) {
2618 throw new IllegalStateException("getAudioManager called when there is no mView");
2619 }
2620 if (mAudioManager == null) {
2621 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2622 }
2623 return mAudioManager;
2624 }
2625
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002626 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2627 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002628
2629 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002630 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002631 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002632 restore = true;
2633 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002634 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002635 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002636 if (params != null) {
2637 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002638 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002639 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002640 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002641 int relayoutResult = sWindowSession.relayout(
2642 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002643 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2644 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002645 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002646 mPendingContentInsets, mPendingVisibleInsets,
2647 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002648 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002649 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002650 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002651 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002652
2653 if (mTranslator != null) {
2654 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2655 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2656 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002657 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002658 return relayoutResult;
2659 }
Romain Guy8506ab42009-06-11 17:35:47 -07002660
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002661 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 * {@inheritDoc}
2663 */
2664 public void playSoundEffect(int effectId) {
2665 checkThread();
2666
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002667 try {
2668 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002670 switch (effectId) {
2671 case SoundEffectConstants.CLICK:
2672 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2673 return;
2674 case SoundEffectConstants.NAVIGATION_DOWN:
2675 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2676 return;
2677 case SoundEffectConstants.NAVIGATION_LEFT:
2678 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2679 return;
2680 case SoundEffectConstants.NAVIGATION_RIGHT:
2681 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2682 return;
2683 case SoundEffectConstants.NAVIGATION_UP:
2684 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2685 return;
2686 default:
2687 throw new IllegalArgumentException("unknown effect id " + effectId +
2688 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2689 }
2690 } catch (IllegalStateException e) {
2691 // Exception thrown by getAudioManager() when mView is null
2692 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2693 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
2695 }
2696
2697 /**
2698 * {@inheritDoc}
2699 */
2700 public boolean performHapticFeedback(int effectId, boolean always) {
2701 try {
2702 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2703 } catch (RemoteException e) {
2704 return false;
2705 }
2706 }
2707
2708 /**
2709 * {@inheritDoc}
2710 */
2711 public View focusSearch(View focused, int direction) {
2712 checkThread();
2713 if (!(mView instanceof ViewGroup)) {
2714 return null;
2715 }
2716 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2717 }
2718
2719 public void debug() {
2720 mView.debug();
2721 }
2722
2723 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002724 if (immediate) {
2725 doDie();
2726 } else {
2727 sendEmptyMessage(DIE);
2728 }
2729 }
2730
2731 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 checkThread();
Jeff Brownc5ed5912010-07-14 18:48:53 -07002733 if (Config.LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 synchronized (this) {
2735 if (mAdded && !mFirst) {
2736 int viewVisibility = mView.getVisibility();
2737 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2738 if (mWindowAttributesChanged || viewVisibilityChanged) {
2739 // If layout params have been changed, first give them
2740 // to the window manager to make sure it has the correct
2741 // animation info.
2742 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002743 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2744 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 sWindowSession.finishDrawing(mWindow);
2746 }
2747 } catch (RemoteException e) {
2748 }
2749 }
2750
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002751 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 }
2753 if (mAdded) {
2754 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002755 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
2757 }
2758 }
2759
2760 public void dispatchFinishedEvent(int seq, boolean handled) {
2761 Message msg = obtainMessage(FINISHED_EVENT);
2762 msg.arg1 = seq;
2763 msg.arg2 = handled ? 1 : 0;
2764 sendMessage(msg);
2765 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002768 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2770 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2771 + " visibleInsets=" + visibleInsets.toShortString()
2772 + " reportDraw=" + reportDraw);
2773 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002774 if (mTranslator != null) {
2775 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2776 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2777 w *= mTranslator.applicationInvertedScale;
2778 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002779 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002780 msg.arg1 = w;
2781 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002782 ResizedInfo ri = new ResizedInfo();
2783 ri.coveredInsets = new Rect(coveredInsets);
2784 ri.visibleInsets = new Rect(visibleInsets);
2785 ri.newConfig = newConfig;
2786 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 sendMessage(msg);
2788 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002789
2790 private Runnable mFinishedCallback;
2791
2792 private final InputHandler mInputHandler = new InputHandler() {
2793 public void handleKey(KeyEvent event, Runnable finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002794 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002795 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002796 }
2797
Jeff Brownc5ed5912010-07-14 18:48:53 -07002798 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002799 startInputEvent(finishedCallback);
2800 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002801 }
2802 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803
2804 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002805 dispatchKey(event, false);
2806 }
2807
2808 private void dispatchKey(KeyEvent event, boolean sendDone) {
2809 //noinspection ConstantConditions
2810 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2811 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 if (Config.LOGD) Log.d("keydisp",
2813 "===================================================");
2814 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2815 debug();
2816
2817 if (Config.LOGD) Log.d("keydisp",
2818 "===================================================");
2819 }
2820 }
2821
2822 Message msg = obtainMessage(DISPATCH_KEY);
2823 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002824 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825
2826 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002827 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828
2829 sendMessageAtTime(msg, event.getEventTime());
2830 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002831
2832 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002833 dispatchMotion(event, false);
2834 }
2835
2836 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002837 int source = event.getSource();
2838 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002839 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002840 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002841 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002842 } else {
2843 // TODO
2844 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002845 if (sendDone) {
2846 finishInputEvent();
2847 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002848 }
2849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002851 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002852 dispatchPointer(event, false);
2853 }
2854
2855 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 Message msg = obtainMessage(DISPATCH_POINTER);
2857 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002858 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002859 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002862 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002863 dispatchTrackball(event, false);
2864 }
2865
2866 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2868 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002869 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002870 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 public void dispatchAppVisibility(boolean visible) {
2874 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2875 msg.arg1 = visible ? 1 : 0;
2876 sendMessage(msg);
2877 }
2878
2879 public void dispatchGetNewSurface() {
2880 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2881 sendMessage(msg);
2882 }
2883
2884 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2885 Message msg = Message.obtain();
2886 msg.what = WINDOW_FOCUS_CHANGED;
2887 msg.arg1 = hasFocus ? 1 : 0;
2888 msg.arg2 = inTouchMode ? 1 : 0;
2889 sendMessage(msg);
2890 }
2891
Dianne Hackbornffa42482009-09-23 22:20:11 -07002892 public void dispatchCloseSystemDialogs(String reason) {
2893 Message msg = Message.obtain();
2894 msg.what = CLOSE_SYSTEM_DIALOGS;
2895 msg.obj = reason;
2896 sendMessage(msg);
2897 }
2898
svetoslavganov75986cf2009-05-14 22:28:01 -07002899 /**
2900 * The window is getting focus so if there is anything focused/selected
2901 * send an {@link AccessibilityEvent} to announce that.
2902 */
2903 private void sendAccessibilityEvents() {
2904 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2905 return;
2906 }
2907 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2908 View focusedView = mView.findFocus();
2909 if (focusedView != null && focusedView != mView) {
2910 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2911 }
2912 }
2913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 public boolean showContextMenuForChild(View originalView) {
2915 return false;
2916 }
2917
2918 public void createContextMenu(ContextMenu menu) {
2919 }
2920
2921 public void childDrawableStateChanged(View child) {
2922 }
2923
2924 protected Rect getWindowFrame() {
2925 return mWinFrame;
2926 }
2927
2928 void checkThread() {
2929 if (mThread != Thread.currentThread()) {
2930 throw new CalledFromWrongThreadException(
2931 "Only the original thread that created a view hierarchy can touch its views.");
2932 }
2933 }
2934
2935 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2936 // ViewRoot never intercepts touch event, so this can be a no-op
2937 }
2938
2939 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2940 boolean immediate) {
2941 return scrollToRectOrFocus(rectangle, immediate);
2942 }
Romain Guy8506ab42009-06-11 17:35:47 -07002943
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002944 class TakenSurfaceHolder extends BaseSurfaceHolder {
2945 @Override
2946 public boolean onAllowLockCanvas() {
2947 return mDrawingAllowed;
2948 }
2949
2950 @Override
2951 public void onRelayoutContainer() {
2952 // Not currently interesting -- from changing between fixed and layout size.
2953 }
2954
2955 public void setFormat(int format) {
2956 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2957 }
2958
2959 public void setType(int type) {
2960 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2961 }
2962
2963 @Override
2964 public void onUpdateSurface() {
2965 // We take care of format and type changes on our own.
2966 throw new IllegalStateException("Shouldn't be here");
2967 }
2968
2969 public boolean isCreating() {
2970 return mIsCreating;
2971 }
2972
2973 @Override
2974 public void setFixedSize(int width, int height) {
2975 throw new UnsupportedOperationException(
2976 "Currently only support sizing from layout");
2977 }
2978
2979 public void setKeepScreenOn(boolean screenOn) {
2980 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2981 }
2982 }
2983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 static class InputMethodCallback extends IInputMethodCallback.Stub {
2985 private WeakReference<ViewRoot> mViewRoot;
2986
2987 public InputMethodCallback(ViewRoot viewRoot) {
2988 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2989 }
Romain Guy8506ab42009-06-11 17:35:47 -07002990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 public void finishedEvent(int seq, boolean handled) {
2992 final ViewRoot viewRoot = mViewRoot.get();
2993 if (viewRoot != null) {
2994 viewRoot.dispatchFinishedEvent(seq, handled);
2995 }
2996 }
2997
2998 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2999 // Stub -- not for use in the client.
3000 }
3001 }
Romain Guy8506ab42009-06-11 17:35:47 -07003002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003004 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003006 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3008 }
3009
3010 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003011 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 final ViewRoot viewRoot = mViewRoot.get();
3013 if (viewRoot != null) {
3014 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003015 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 }
3017 }
3018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 public void dispatchAppVisibility(boolean visible) {
3020 final ViewRoot viewRoot = mViewRoot.get();
3021 if (viewRoot != null) {
3022 viewRoot.dispatchAppVisibility(visible);
3023 }
3024 }
3025
3026 public void dispatchGetNewSurface() {
3027 final ViewRoot viewRoot = mViewRoot.get();
3028 if (viewRoot != null) {
3029 viewRoot.dispatchGetNewSurface();
3030 }
3031 }
3032
3033 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3034 final ViewRoot viewRoot = mViewRoot.get();
3035 if (viewRoot != null) {
3036 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3037 }
3038 }
3039
3040 private static int checkCallingPermission(String permission) {
3041 if (!Process.supportsProcesses()) {
3042 return PackageManager.PERMISSION_GRANTED;
3043 }
3044
3045 try {
3046 return ActivityManagerNative.getDefault().checkPermission(
3047 permission, Binder.getCallingPid(), Binder.getCallingUid());
3048 } catch (RemoteException e) {
3049 return PackageManager.PERMISSION_DENIED;
3050 }
3051 }
3052
3053 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3054 final ViewRoot viewRoot = mViewRoot.get();
3055 if (viewRoot != null) {
3056 final View view = viewRoot.mView;
3057 if (view != null) {
3058 if (checkCallingPermission(Manifest.permission.DUMP) !=
3059 PackageManager.PERMISSION_GRANTED) {
3060 throw new SecurityException("Insufficient permissions to invoke"
3061 + " executeCommand() from pid=" + Binder.getCallingPid()
3062 + ", uid=" + Binder.getCallingUid());
3063 }
3064
3065 OutputStream clientStream = null;
3066 try {
3067 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3068 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3069 } catch (IOException e) {
3070 e.printStackTrace();
3071 } finally {
3072 if (clientStream != null) {
3073 try {
3074 clientStream.close();
3075 } catch (IOException e) {
3076 e.printStackTrace();
3077 }
3078 }
3079 }
3080 }
3081 }
3082 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003083
Dianne Hackbornffa42482009-09-23 22:20:11 -07003084 public void closeSystemDialogs(String reason) {
3085 final ViewRoot viewRoot = mViewRoot.get();
3086 if (viewRoot != null) {
3087 viewRoot.dispatchCloseSystemDialogs(reason);
3088 }
3089 }
3090
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003091 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3092 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003093 if (sync) {
3094 try {
3095 sWindowSession.wallpaperOffsetsComplete(asBinder());
3096 } catch (RemoteException e) {
3097 }
3098 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003099 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003100
3101 public void dispatchWallpaperCommand(String action, int x, int y,
3102 int z, Bundle extras, boolean sync) {
3103 if (sync) {
3104 try {
3105 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3106 } catch (RemoteException e) {
3107 }
3108 }
3109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 }
3111
3112 /**
3113 * Maintains state information for a single trackball axis, generating
3114 * discrete (DPAD) movements based on raw trackball motion.
3115 */
3116 static final class TrackballAxis {
3117 /**
3118 * The maximum amount of acceleration we will apply.
3119 */
3120 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 /**
3123 * The maximum amount of time (in milliseconds) between events in order
3124 * for us to consider the user to be doing fast trackball movements,
3125 * and thus apply an acceleration.
3126 */
3127 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 /**
3130 * Scaling factor to the time (in milliseconds) between events to how
3131 * much to multiple/divide the current acceleration. When movement
3132 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3133 * FAST_MOVE_TIME it divides it.
3134 */
3135 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 float position;
3138 float absPosition;
3139 float acceleration = 1;
3140 long lastMoveTime = 0;
3141 int step;
3142 int dir;
3143 int nonAccelMovement;
3144
3145 void reset(int _step) {
3146 position = 0;
3147 acceleration = 1;
3148 lastMoveTime = 0;
3149 step = _step;
3150 dir = 0;
3151 }
3152
3153 /**
3154 * Add trackball movement into the state. If the direction of movement
3155 * has been reversed, the state is reset before adding the
3156 * movement (so that you don't have to compensate for any previously
3157 * collected movement before see the result of the movement in the
3158 * new direction).
3159 *
3160 * @return Returns the absolute value of the amount of movement
3161 * collected so far.
3162 */
3163 float collect(float off, long time, String axis) {
3164 long normTime;
3165 if (off > 0) {
3166 normTime = (long)(off * FAST_MOVE_TIME);
3167 if (dir < 0) {
3168 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3169 position = 0;
3170 step = 0;
3171 acceleration = 1;
3172 lastMoveTime = 0;
3173 }
3174 dir = 1;
3175 } else if (off < 0) {
3176 normTime = (long)((-off) * FAST_MOVE_TIME);
3177 if (dir > 0) {
3178 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3179 position = 0;
3180 step = 0;
3181 acceleration = 1;
3182 lastMoveTime = 0;
3183 }
3184 dir = -1;
3185 } else {
3186 normTime = 0;
3187 }
Romain Guy8506ab42009-06-11 17:35:47 -07003188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 // The number of milliseconds between each movement that is
3190 // considered "normal" and will not result in any acceleration
3191 // or deceleration, scaled by the offset we have here.
3192 if (normTime > 0) {
3193 long delta = time - lastMoveTime;
3194 lastMoveTime = time;
3195 float acc = acceleration;
3196 if (delta < normTime) {
3197 // The user is scrolling rapidly, so increase acceleration.
3198 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3199 if (scale > 1) acc *= scale;
3200 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3201 + off + " normTime=" + normTime + " delta=" + delta
3202 + " scale=" + scale + " acc=" + acc);
3203 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3204 } else {
3205 // The user is scrolling slowly, so decrease acceleration.
3206 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3207 if (scale > 1) acc /= scale;
3208 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3209 + off + " normTime=" + normTime + " delta=" + delta
3210 + " scale=" + scale + " acc=" + acc);
3211 acceleration = acc > 1 ? acc : 1;
3212 }
3213 }
3214 position += off;
3215 return (absPosition = Math.abs(position));
3216 }
3217
3218 /**
3219 * Generate the number of discrete movement events appropriate for
3220 * the currently collected trackball movement.
3221 *
3222 * @param precision The minimum movement required to generate the
3223 * first discrete movement.
3224 *
3225 * @return Returns the number of discrete movements, either positive
3226 * or negative, or 0 if there is not enough trackball movement yet
3227 * for a discrete movement.
3228 */
3229 int generate(float precision) {
3230 int movement = 0;
3231 nonAccelMovement = 0;
3232 do {
3233 final int dir = position >= 0 ? 1 : -1;
3234 switch (step) {
3235 // If we are going to execute the first step, then we want
3236 // to do this as soon as possible instead of waiting for
3237 // a full movement, in order to make things look responsive.
3238 case 0:
3239 if (absPosition < precision) {
3240 return movement;
3241 }
3242 movement += dir;
3243 nonAccelMovement += dir;
3244 step = 1;
3245 break;
3246 // If we have generated the first movement, then we need
3247 // to wait for the second complete trackball motion before
3248 // generating the second discrete movement.
3249 case 1:
3250 if (absPosition < 2) {
3251 return movement;
3252 }
3253 movement += dir;
3254 nonAccelMovement += dir;
3255 position += dir > 0 ? -2 : 2;
3256 absPosition = Math.abs(position);
3257 step = 2;
3258 break;
3259 // After the first two, we generate discrete movements
3260 // consistently with the trackball, applying an acceleration
3261 // if the trackball is moving quickly. This is a simple
3262 // acceleration on top of what we already compute based
3263 // on how quickly the wheel is being turned, to apply
3264 // a longer increasing acceleration to continuous movement
3265 // in one direction.
3266 default:
3267 if (absPosition < 1) {
3268 return movement;
3269 }
3270 movement += dir;
3271 position += dir >= 0 ? -1 : 1;
3272 absPosition = Math.abs(position);
3273 float acc = acceleration;
3274 acc *= 1.1f;
3275 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3276 break;
3277 }
3278 } while (true);
3279 }
3280 }
3281
3282 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3283 public CalledFromWrongThreadException(String msg) {
3284 super(msg);
3285 }
3286 }
3287
3288 private SurfaceHolder mHolder = new SurfaceHolder() {
3289 // we only need a SurfaceHolder for opengl. it would be nice
3290 // to implement everything else though, especially the callback
3291 // support (opengl doesn't make use of it right now, but eventually
3292 // will).
3293 public Surface getSurface() {
3294 return mSurface;
3295 }
3296
3297 public boolean isCreating() {
3298 return false;
3299 }
3300
3301 public void addCallback(Callback callback) {
3302 }
3303
3304 public void removeCallback(Callback callback) {
3305 }
3306
3307 public void setFixedSize(int width, int height) {
3308 }
3309
3310 public void setSizeFromLayout() {
3311 }
3312
3313 public void setFormat(int format) {
3314 }
3315
3316 public void setType(int type) {
3317 }
3318
3319 public void setKeepScreenOn(boolean screenOn) {
3320 }
3321
3322 public Canvas lockCanvas() {
3323 return null;
3324 }
3325
3326 public Canvas lockCanvas(Rect dirty) {
3327 return null;
3328 }
3329
3330 public void unlockCanvasAndPost(Canvas canvas) {
3331 }
3332 public Rect getSurfaceFrame() {
3333 return null;
3334 }
3335 };
3336
3337 static RunQueue getRunQueue() {
3338 RunQueue rq = sRunQueues.get();
3339 if (rq != null) {
3340 return rq;
3341 }
3342 rq = new RunQueue();
3343 sRunQueues.set(rq);
3344 return rq;
3345 }
Romain Guy8506ab42009-06-11 17:35:47 -07003346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 /**
3348 * @hide
3349 */
3350 static final class RunQueue {
3351 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3352
3353 void post(Runnable action) {
3354 postDelayed(action, 0);
3355 }
3356
3357 void postDelayed(Runnable action, long delayMillis) {
3358 HandlerAction handlerAction = new HandlerAction();
3359 handlerAction.action = action;
3360 handlerAction.delay = delayMillis;
3361
3362 synchronized (mActions) {
3363 mActions.add(handlerAction);
3364 }
3365 }
3366
3367 void removeCallbacks(Runnable action) {
3368 final HandlerAction handlerAction = new HandlerAction();
3369 handlerAction.action = action;
3370
3371 synchronized (mActions) {
3372 final ArrayList<HandlerAction> actions = mActions;
3373
3374 while (actions.remove(handlerAction)) {
3375 // Keep going
3376 }
3377 }
3378 }
3379
3380 void executeActions(Handler handler) {
3381 synchronized (mActions) {
3382 final ArrayList<HandlerAction> actions = mActions;
3383 final int count = actions.size();
3384
3385 for (int i = 0; i < count; i++) {
3386 final HandlerAction handlerAction = actions.get(i);
3387 handler.postDelayed(handlerAction.action, handlerAction.delay);
3388 }
3389
Romain Guy15df6702009-08-17 20:17:30 -07003390 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 }
3392 }
3393
3394 private static class HandlerAction {
3395 Runnable action;
3396 long delay;
3397
3398 @Override
3399 public boolean equals(Object o) {
3400 if (this == o) return true;
3401 if (o == null || getClass() != o.getClass()) return false;
3402
3403 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 return !(action != null ? !action.equals(that.action) : that.action != null);
3405
3406 }
3407
3408 @Override
3409 public int hashCode() {
3410 int result = action != null ? action.hashCode() : 0;
3411 result = 31 * result + (int) (delay ^ (delay >>> 32));
3412 return result;
3413 }
3414 }
3415 }
3416
3417 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3418
3419 // inform skia to just abandon its texture cache IDs
3420 // doesn't call glDeleteTextures
3421 private static native void nativeAbandonGlCaches();
3422}