blob: aa124e6a6e20f0299383c4441b1252699458f280 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070019import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.view.IInputMethodCallback;
21import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070022import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import android.graphics.Canvas;
25import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.PorterDuff;
27import android.graphics.Rect;
28import android.graphics.Region;
29import android.os.*;
30import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.util.AndroidRuntimeException;
32import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070033import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.Log;
35import android.util.EventLog;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070036import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070039import android.view.accessibility.AccessibilityEvent;
40import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.view.inputmethod.InputConnection;
42import android.view.inputmethod.InputMethodManager;
43import android.widget.Scroller;
44import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070045import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080046import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070047import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080048import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.Context;
50import android.app.ActivityManagerNative;
51import android.Manifest;
52import android.media.AudioManager;
53
54import java.lang.ref.WeakReference;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070055import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.io.IOException;
57import java.io.OutputStream;
58import java.util.ArrayList;
59
60import javax.microedition.khronos.egl.*;
61import javax.microedition.khronos.opengles.*;
62import static javax.microedition.khronos.opengles.GL10.*;
63
64/**
65 * The top of a view hierarchy, implementing the needed protocol between View
66 * and the WindowManager. This is for the most part an internal implementation
67 * detail of {@link WindowManagerImpl}.
68 *
69 * {@hide}
70 */
71@SuppressWarnings({"EmptyCatchBlock"})
72public final class ViewRoot extends Handler implements ViewParent,
73 View.AttachInfo.Callbacks {
74 private static final String TAG = "ViewRoot";
75 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040076 private static final boolean SHOW_FPS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 @SuppressWarnings({"ConstantConditionalExpression"})
78 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
79 /** @noinspection PointlessBooleanExpression*/
80 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
81 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070082 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
84 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
85 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
86 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070087 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final boolean WATCH_POINTER = false;
89
Michael Chan53071d62009-05-13 17:29:48 -070090 private static final boolean MEASURE_LATENCY = false;
91 private static LatencyTimer lt;
92
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 /**
94 * Maximum time we allow the user to roll the trackball enough to generate
95 * a key event, before resetting the counters.
96 */
97 static final int MAX_TRACKBALL_DELAY = 250;
98
99 static long sInstanceCount = 0;
100
101 static IWindowSession sWindowSession;
102
103 static final Object mStaticInit = new Object();
104 static boolean mInitialized = false;
105
106 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
107
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800108 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
109 static boolean sFirstDrawComplete = false;
110
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800111 static final ArrayList<ComponentCallbacks> sConfigCallbacks
112 = new ArrayList<ComponentCallbacks>();
113
Romain Guy8506ab42009-06-11 17:35:47 -0700114 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 long mLastTrackballTime = 0;
117 final TrackballAxis mTrackballAxisX = new TrackballAxis();
118 final TrackballAxis mTrackballAxisY = new TrackballAxis();
119
120 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 final InputMethodCallback mInputMethodCallback;
123 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
124 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 final Thread mThread;
127
128 final WindowLeaked mLocation;
129
130 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
131
132 final W mWindow;
133
134 View mView;
135 View mFocusedView;
136 View mRealFocusedView; // this is not set to null in touch mode
137 int mViewVisibility;
138 boolean mAppVisible = true;
139
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700140 SurfaceHolder.Callback mSurfaceHolderCallback;
141 BaseSurfaceHolder mSurfaceHolder;
142 boolean mIsCreating;
143 boolean mDrawingAllowed;
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 final Region mTransparentRegion;
146 final Region mPreviousTransparentRegion;
147
148 int mWidth;
149 int mHeight;
150 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700151 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700152
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700153 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
155 final View.AttachInfo mAttachInfo;
156
157 final Rect mTempRect; // used in the transaction to not thrash the heap.
158 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
160 boolean mTraversalScheduled;
161 boolean mWillDrawSoon;
162 boolean mLayoutRequested;
163 boolean mFirst;
164 boolean mReportNextDraw;
165 boolean mFullRedrawNeeded;
166 boolean mNewSurfaceNeeded;
167 boolean mHasHadWindowFocus;
168 boolean mLastWasImTarget;
169
170 boolean mWindowAttributesChanged = false;
171
172 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700173 // Surface can never be reassigned or cleared (use Surface.clear()).
174 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
176 boolean mAdded;
177 boolean mAddedTouchMode;
178
179 /*package*/ int mAddNesting;
180
181 // These are accessed by multiple threads.
182 final Rect mWinFrame; // frame given by window manager.
183
184 final Rect mPendingVisibleInsets = new Rect();
185 final Rect mPendingContentInsets = new Rect();
186 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
187 = new ViewTreeObserver.InternalInsetsInfo();
188
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700189 final Configuration mLastConfiguration = new Configuration();
190 final Configuration mPendingConfiguration = new Configuration();
191
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800192 class ResizedInfo {
193 Rect coveredInsets;
194 Rect visibleInsets;
195 Configuration newConfig;
196 }
197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 boolean mScrollMayChange;
199 int mSoftInputMode;
200 View mLastScrolledFocus;
201 int mScrollY;
202 int mCurScrollY;
203 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 EGL10 mEgl;
206 EGLDisplay mEglDisplay;
207 EGLContext mEglContext;
208 EGLSurface mEglSurface;
209 GL11 mGL;
210 Canvas mGlCanvas;
211 boolean mUseGL;
212 boolean mGlWanted;
213
Romain Guy8506ab42009-06-11 17:35:47 -0700214 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
216 /**
217 * see {@link #playSoundEffect(int)}
218 */
219 AudioManager mAudioManager;
220
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700221 private final int mDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700223 public static IWindowSession getWindowSession(Looper mainLooper) {
224 synchronized (mStaticInit) {
225 if (!mInitialized) {
226 try {
227 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
228 sWindowSession = IWindowManager.Stub.asInterface(
229 ServiceManager.getService("window"))
230 .openSession(imm.getClient(), imm.getInputContext());
231 mInitialized = true;
232 } catch (RemoteException e) {
233 }
234 }
235 return sWindowSession;
236 }
237 }
238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 public ViewRoot(Context context) {
240 super();
241
Michael Chan53071d62009-05-13 17:29:48 -0700242 if (MEASURE_LATENCY && lt == null) {
243 lt = new LatencyTimer(100, 1000);
244 }
245
Carl Shapiro82fe5642010-02-24 00:14:23 -0800246 // For debug only
247 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
249 // Initialize the statics when this class is first instantiated. This is
250 // done here instead of in the static block because Zygote does not
251 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700252 getWindowSession(context.getMainLooper());
253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 mThread = Thread.currentThread();
255 mLocation = new WindowLeaked(null);
256 mLocation.fillInStackTrace();
257 mWidth = -1;
258 mHeight = -1;
259 mDirty = new Rect();
260 mTempRect = new Rect();
261 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700263 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 mInputMethodCallback = new InputMethodCallback(this);
265 mViewVisibility = View.GONE;
266 mTransparentRegion = new Region();
267 mPreviousTransparentRegion = new Region();
268 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 mAdded = false;
270 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
271 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700272 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 }
274
Carl Shapiro82fe5642010-02-24 00:14:23 -0800275 // For debug only
276 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 @Override
278 protected void finalize() throws Throwable {
279 super.finalize();
280 --sInstanceCount;
281 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800282 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283
284 public static long getInstanceCount() {
285 return sInstanceCount;
286 }
287
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800288 public static void addFirstDrawHandler(Runnable callback) {
289 synchronized (sFirstDrawHandlers) {
290 if (!sFirstDrawComplete) {
291 sFirstDrawHandlers.add(callback);
292 }
293 }
294 }
295
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800296 public static void addConfigCallback(ComponentCallbacks callback) {
297 synchronized (sConfigCallbacks) {
298 sConfigCallbacks.add(callback);
299 }
300 }
301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 // FIXME for perf testing only
303 private boolean mProfile = false;
304
305 /**
306 * Call this to profile the next traversal call.
307 * FIXME for perf testing only. Remove eventually
308 */
309 public void profile() {
310 mProfile = true;
311 }
312
313 /**
314 * Indicates whether we are in touch mode. Calling this method triggers an IPC
315 * call and should be avoided whenever possible.
316 *
317 * @return True, if the device is in touch mode, false otherwise.
318 *
319 * @hide
320 */
321 static boolean isInTouchMode() {
322 if (mInitialized) {
323 try {
324 return sWindowSession.getInTouchMode();
325 } catch (RemoteException e) {
326 }
327 }
328 return false;
329 }
330
331 private void initializeGL() {
332 initializeGLInner();
333 int err = mEgl.eglGetError();
334 if (err != EGL10.EGL_SUCCESS) {
335 // give-up on using GL
336 destroyGL();
337 mGlWanted = false;
338 }
339 }
340
341 private void initializeGLInner() {
342 final EGL10 egl = (EGL10) EGLContext.getEGL();
343 mEgl = egl;
344
345 /*
346 * Get to the default display.
347 */
348 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
349 mEglDisplay = eglDisplay;
350
351 /*
352 * We can now initialize EGL for that display
353 */
354 int[] version = new int[2];
355 egl.eglInitialize(eglDisplay, version);
356
357 /*
358 * Specify a configuration for our opengl session
359 * and grab the first configuration that matches is
360 */
361 final int[] configSpec = {
362 EGL10.EGL_RED_SIZE, 5,
363 EGL10.EGL_GREEN_SIZE, 6,
364 EGL10.EGL_BLUE_SIZE, 5,
365 EGL10.EGL_DEPTH_SIZE, 0,
366 EGL10.EGL_NONE
367 };
368 final EGLConfig[] configs = new EGLConfig[1];
369 final int[] num_config = new int[1];
370 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
371 final EGLConfig config = configs[0];
372
373 /*
374 * Create an OpenGL ES context. This must be done only once, an
375 * OpenGL context is a somewhat heavy object.
376 */
377 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
378 EGL10.EGL_NO_CONTEXT, null);
379 mEglContext = context;
380
381 /*
382 * Create an EGL surface we can render into.
383 */
384 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
385 mEglSurface = surface;
386
387 /*
388 * Before we can issue GL commands, we need to make sure
389 * the context is current and bound to a surface.
390 */
391 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
392
393 /*
394 * Get to the appropriate GL interface.
395 * This is simply done by casting the GL context to either
396 * GL10 or GL11.
397 */
398 final GL11 gl = (GL11) context.getGL();
399 mGL = gl;
400 mGlCanvas = new Canvas(gl);
401 mUseGL = true;
402 }
403
404 private void destroyGL() {
405 // inform skia that the context is gone
406 nativeAbandonGlCaches();
407
408 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
409 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
410 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
411 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
412 mEgl.eglTerminate(mEglDisplay);
413 mEglContext = null;
414 mEglSurface = null;
415 mEglDisplay = null;
416 mEgl = null;
417 mGlCanvas = null;
418 mGL = null;
419 mUseGL = false;
420 }
421
422 private void checkEglErrors() {
423 if (mUseGL) {
424 int err = mEgl.eglGetError();
425 if (err != EGL10.EGL_SUCCESS) {
426 // something bad has happened revert to
427 // normal rendering.
428 destroyGL();
429 if (err != EGL11.EGL_CONTEXT_LOST) {
430 // we'll try again if it was context lost
431 mGlWanted = false;
432 }
433 }
434 }
435 }
436
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700437 // fd [0] is the receiver, [1] is the sender
438 private native int[] makeInputChannel();
439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 /**
441 * We have one child
442 */
443 public void setView(View view, WindowManager.LayoutParams attrs,
444 View panelParentView) {
445 synchronized (this) {
446 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700447 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700448 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700449 attrs = mWindowAttributes;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700450 if (view instanceof RootViewSurfaceTaker) {
451 mSurfaceHolderCallback =
452 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
453 if (mSurfaceHolderCallback != null) {
454 mSurfaceHolder = new TakenSurfaceHolder();
455 }
456 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700457 Resources resources = mView.getContext().getResources();
458 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700459 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700460
461 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700462 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
463 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700464 }
465
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700466 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700467 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700468 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700469 attrs.backup();
470 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700471 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700472 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
473
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700474 if (!compatibilityInfo.supportsScreen()) {
475 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
476 }
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 mSoftInputMode = attrs.softInputMode;
479 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700481 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700482 mAttachInfo.mApplicationScale =
483 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 if (panelParentView != null) {
485 mAttachInfo.mPanelParentWindowToken
486 = panelParentView.getApplicationWindowToken();
487 }
488 mAdded = true;
489 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700490
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700491 // Set up the input event channel
492 if (false) {
493 int[] fds = makeInputChannel();
494 if (DEBUG_INPUT) {
495 Log.v(TAG, "makeInputChannel() returned " + fds);
496 }
497 }
498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 // Schedule the first layout -before- adding to the window
500 // manager, to make sure we do the relayout before receiving
501 // any other events from the system.
502 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700504 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 getHostVisibility(), mAttachInfo.mContentInsets);
506 } catch (RemoteException e) {
507 mAdded = false;
508 mView = null;
509 mAttachInfo.mRootView = null;
510 unscheduleTraversals();
511 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700512 } finally {
513 if (restore) {
514 attrs.restore();
515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700517
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700518 if (mTranslator != null) {
519 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 mPendingContentInsets.set(mAttachInfo.mContentInsets);
522 mPendingVisibleInsets.set(0, 0, 0, 0);
523 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
524 if (res < WindowManagerImpl.ADD_OKAY) {
525 mView = null;
526 mAttachInfo.mRootView = null;
527 mAdded = false;
528 unscheduleTraversals();
529 switch (res) {
530 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
531 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
532 throw new WindowManagerImpl.BadTokenException(
533 "Unable to add window -- token " + attrs.token
534 + " is not valid; is your activity running?");
535 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
536 throw new WindowManagerImpl.BadTokenException(
537 "Unable to add window -- token " + attrs.token
538 + " is not for an application");
539 case WindowManagerImpl.ADD_APP_EXITING:
540 throw new WindowManagerImpl.BadTokenException(
541 "Unable to add window -- app for token " + attrs.token
542 + " is exiting");
543 case WindowManagerImpl.ADD_DUPLICATE_ADD:
544 throw new WindowManagerImpl.BadTokenException(
545 "Unable to add window -- window " + mWindow
546 + " has already been added");
547 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
548 // Silently ignore -- we would have just removed it
549 // right away, anyway.
550 return;
551 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
552 throw new WindowManagerImpl.BadTokenException(
553 "Unable to add window " + mWindow +
554 " -- another window of this type already exists");
555 case WindowManagerImpl.ADD_PERMISSION_DENIED:
556 throw new WindowManagerImpl.BadTokenException(
557 "Unable to add window " + mWindow +
558 " -- permission denied for this window type");
559 }
560 throw new RuntimeException(
561 "Unable to add window -- unknown error code " + res);
562 }
563 view.assignParent(this);
564 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
565 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
566 }
567 }
568 }
569
570 public View getView() {
571 return mView;
572 }
573
574 final WindowLeaked getLocation() {
575 return mLocation;
576 }
577
578 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
579 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700580 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700581 // preserve compatible window flag if exists.
582 int compatibleWindowFlag =
583 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700585 mWindowAttributes.flags |= compatibleWindowFlag;
586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 if (newView) {
588 mSoftInputMode = attrs.softInputMode;
589 requestLayout();
590 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700591 // Don't lose the mode we last auto-computed.
592 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
593 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
594 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
595 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
596 | (oldSoftInputMode
597 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 mWindowAttributesChanged = true;
600 scheduleTraversals();
601 }
602 }
603
604 void handleAppVisibility(boolean visible) {
605 if (mAppVisible != visible) {
606 mAppVisible = visible;
607 scheduleTraversals();
608 }
609 }
610
611 void handleGetNewSurface() {
612 mNewSurfaceNeeded = true;
613 mFullRedrawNeeded = true;
614 scheduleTraversals();
615 }
616
617 /**
618 * {@inheritDoc}
619 */
620 public void requestLayout() {
621 checkThread();
622 mLayoutRequested = true;
623 scheduleTraversals();
624 }
625
626 /**
627 * {@inheritDoc}
628 */
629 public boolean isLayoutRequested() {
630 return mLayoutRequested;
631 }
632
633 public void invalidateChild(View child, Rect dirty) {
634 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700635 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
636 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700638 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700639 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700640 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700641 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700642 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700643 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700644 }
Romain Guy1e095972009-07-07 11:22:45 -0700645 if (mAttachInfo.mScalingRequired) {
646 dirty.inset(-1, -1);
647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
649 mDirty.union(dirty);
650 if (!mWillDrawSoon) {
651 scheduleTraversals();
652 }
653 }
654
655 public ViewParent getParent() {
656 return null;
657 }
658
659 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
660 invalidateChild(null, dirty);
661 return null;
662 }
663
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700664 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 if (child != mView) {
666 throw new RuntimeException("child is not mine, honest!");
667 }
668 // Note: don't apply scroll offset, because we want to know its
669 // visibility in the virtual canvas being given to the view hierarchy.
670 return r.intersect(0, 0, mWidth, mHeight);
671 }
672
673 public void bringChildToFront(View child) {
674 }
675
676 public void scheduleTraversals() {
677 if (!mTraversalScheduled) {
678 mTraversalScheduled = true;
679 sendEmptyMessage(DO_TRAVERSAL);
680 }
681 }
682
683 public void unscheduleTraversals() {
684 if (mTraversalScheduled) {
685 mTraversalScheduled = false;
686 removeMessages(DO_TRAVERSAL);
687 }
688 }
689
690 int getHostVisibility() {
691 return mAppVisible ? mView.getVisibility() : View.GONE;
692 }
Romain Guy8506ab42009-06-11 17:35:47 -0700693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 private void performTraversals() {
695 // cache mView since it is used so much below...
696 final View host = mView;
697
698 if (DBG) {
699 System.out.println("======================================");
700 System.out.println("performTraversals");
701 host.debug();
702 }
703
704 if (host == null || !mAdded)
705 return;
706
707 mTraversalScheduled = false;
708 mWillDrawSoon = true;
709 boolean windowResizesToFitContent = false;
710 boolean fullRedrawNeeded = mFullRedrawNeeded;
711 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700712 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 WindowManager.LayoutParams lp = mWindowAttributes;
714
715 int desiredWindowWidth;
716 int desiredWindowHeight;
717 int childWidthMeasureSpec;
718 int childHeightMeasureSpec;
719
720 final View.AttachInfo attachInfo = mAttachInfo;
721
722 final int viewVisibility = getHostVisibility();
723 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
724 || mNewSurfaceNeeded;
725
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700726 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 WindowManager.LayoutParams params = null;
729 if (mWindowAttributesChanged) {
730 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700731 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 params = lp;
733 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700734 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 if (mFirst) {
736 fullRedrawNeeded = true;
737 mLayoutRequested = true;
738
Romain Guy8506ab42009-06-11 17:35:47 -0700739 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700740 mView.getContext().getResources().getDisplayMetrics();
741 desiredWindowWidth = packageMetrics.widthPixels;
742 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743
744 // For the very first time, tell the view hierarchy that it
745 // is attached to the window. Note that at this point the surface
746 // object is not initialized to its backing store, but soon it
747 // will be (assuming the window is visible).
748 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700749 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 attachInfo.mHasWindowFocus = false;
751 attachInfo.mWindowVisibility = viewVisibility;
752 attachInfo.mRecomputeGlobalAttributes = false;
753 attachInfo.mKeepScreenOn = false;
754 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700755 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700760 desiredWindowWidth = frame.width();
761 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
763 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700764 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 fullRedrawNeeded = true;
766 mLayoutRequested = true;
767 windowResizesToFitContent = true;
768 }
769 }
770
771 if (viewVisibilityChanged) {
772 attachInfo.mWindowVisibility = viewVisibility;
773 host.dispatchWindowVisibilityChanged(viewVisibility);
774 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
775 if (mUseGL) {
776 destroyGL();
777 }
778 }
779 if (viewVisibility == View.GONE) {
780 // After making a window gone, we will count it as being
781 // shown for the first time the next time it gets focus.
782 mHasHadWindowFocus = false;
783 }
784 }
785
786 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700789 // Execute enqueued actions on every layout in case a view that was detached
790 // enqueued an action after being detached
791 getRunQueue().executeActions(attachInfo.mHandler);
792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 if (mFirst) {
794 host.fitSystemWindows(mAttachInfo.mContentInsets);
795 // make sure touch mode code executes by setting cached value
796 // to opposite of the added touch mode.
797 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700798 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 } else {
800 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
801 mAttachInfo.mContentInsets.set(mPendingContentInsets);
802 host.fitSystemWindows(mAttachInfo.mContentInsets);
803 insetsChanged = true;
804 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
805 + mAttachInfo.mContentInsets);
806 }
807 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
808 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
809 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
810 + mAttachInfo.mVisibleInsets);
811 }
812 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
813 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
814 windowResizesToFitContent = true;
815
Romain Guy8506ab42009-06-11 17:35:47 -0700816 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700817 mView.getContext().getResources().getDisplayMetrics();
818 desiredWindowWidth = packageMetrics.widthPixels;
819 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 }
821 }
822
823 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
824 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
825
826 // Ask host how big it wants to be
827 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
828 "Measuring " + host + " in display " + desiredWindowWidth
829 + "x" + desiredWindowHeight + "...");
830 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
831
832 if (DBG) {
833 System.out.println("======================================");
834 System.out.println("performTraversals -- after measure");
835 host.debug();
836 }
837 }
838
839 if (attachInfo.mRecomputeGlobalAttributes) {
840 //Log.i(TAG, "Computing screen on!");
841 attachInfo.mRecomputeGlobalAttributes = false;
842 boolean oldVal = attachInfo.mKeepScreenOn;
843 attachInfo.mKeepScreenOn = false;
844 host.dispatchCollectViewAttributes(0);
845 if (attachInfo.mKeepScreenOn != oldVal) {
846 params = lp;
847 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
848 }
849 }
850
851 if (mFirst || attachInfo.mViewVisibilityChanged) {
852 attachInfo.mViewVisibilityChanged = false;
853 int resizeMode = mSoftInputMode &
854 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
855 // If we are in auto resize mode, then we need to determine
856 // what mode to use now.
857 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
858 final int N = attachInfo.mScrollContainers.size();
859 for (int i=0; i<N; i++) {
860 if (attachInfo.mScrollContainers.get(i).isShown()) {
861 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
862 }
863 }
864 if (resizeMode == 0) {
865 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
866 }
867 if ((lp.softInputMode &
868 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
869 lp.softInputMode = (lp.softInputMode &
870 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
871 resizeMode;
872 params = lp;
873 }
874 }
875 }
Romain Guy8506ab42009-06-11 17:35:47 -0700876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
878 if (!PixelFormat.formatHasAlpha(params.format)) {
879 params.format = PixelFormat.TRANSLUCENT;
880 }
881 }
882
883 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700884 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
885 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
886 frame.width() < desiredWindowWidth && frame.width() != mWidth)
887 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
888 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889
890 final boolean computesInternalInsets =
891 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
892 boolean insetsPending = false;
893 int relayoutResult = 0;
894 if (mFirst || windowShouldResize || insetsChanged
895 || viewVisibilityChanged || params != null) {
896
897 if (viewVisibility == View.VISIBLE) {
898 // If this window is giving internal insets to the window
899 // manager, and it is being added or changing its visibility,
900 // then we want to first give the window manager "fake"
901 // insets to cause it to effectively ignore the content of
902 // the window during layout. This avoids it briefly causing
903 // other windows to resize/move based on the raw frame of the
904 // window, waiting until we can finish laying out this window
905 // and get back to the window manager with the ultimately
906 // computed insets.
907 insetsPending = computesInternalInsets
908 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
911 if (params == null) {
912 params = mWindowAttributes;
913 }
914 mGlWanted = true;
915 }
916 }
917
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700918 if (mSurfaceHolder != null) {
919 mSurfaceHolder.mSurfaceLock.lock();
920 mDrawingAllowed = true;
921 lp.format = mSurfaceHolder.getRequestedFormat();
922 lp.type = mSurfaceHolder.getRequestedType();
923 }
924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 boolean initialized = false;
926 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700927 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700928 boolean hadSurface = mSurface.isValid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 int fl = 0;
931 if (params != null) {
932 fl = params.flags;
933 if (attachInfo.mKeepScreenOn) {
934 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
935 }
936 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700937 if (DEBUG_LAYOUT) {
938 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
939 host.mMeasuredHeight + ", params=" + params);
940 }
941 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 if (params != null) {
944 params.flags = fl;
945 }
946
947 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
948 + " content=" + mPendingContentInsets.toShortString()
949 + " visible=" + mPendingVisibleInsets.toShortString()
950 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700951
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700952 if (mPendingConfiguration.seq != 0) {
953 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
954 + mPendingConfiguration);
955 updateConfiguration(mPendingConfiguration, !mFirst);
956 mPendingConfiguration.seq = 0;
957 }
958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 contentInsetsChanged = !mPendingContentInsets.equals(
960 mAttachInfo.mContentInsets);
961 visibleInsetsChanged = !mPendingVisibleInsets.equals(
962 mAttachInfo.mVisibleInsets);
963 if (contentInsetsChanged) {
964 mAttachInfo.mContentInsets.set(mPendingContentInsets);
965 host.fitSystemWindows(mAttachInfo.mContentInsets);
966 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
967 + mAttachInfo.mContentInsets);
968 }
969 if (visibleInsetsChanged) {
970 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
971 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
972 + mAttachInfo.mVisibleInsets);
973 }
974
975 if (!hadSurface) {
976 if (mSurface.isValid()) {
977 // If we are creating a new surface, then we need to
978 // completely redraw it. Also, when we get to the
979 // point of drawing it we will hold off and schedule
980 // a new traversal instead. This is so we can tell the
981 // window manager about all of the windows being displayed
982 // before actually drawing them, so it can display then
983 // all at once.
984 newSurface = true;
985 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700986 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 if (mGlWanted && !mUseGL) {
989 initializeGL();
990 initialized = mGlCanvas != null;
991 }
992 }
993 } else if (!mSurface.isValid()) {
994 // If the surface has been removed, then reset the scroll
995 // positions.
996 mLastScrolledFocus = null;
997 mScrollY = mCurScrollY = 0;
998 if (mScroller != null) {
999 mScroller.abortAnimation();
1000 }
1001 }
1002 } catch (RemoteException e) {
1003 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001006 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007
1008 attachInfo.mWindowLeft = frame.left;
1009 attachInfo.mWindowTop = frame.top;
1010
1011 // !!FIXME!! This next section handles the case where we did not get the
1012 // window size we asked for. We should avoid this by getting a maximum size from
1013 // the window session beforehand.
1014 mWidth = frame.width();
1015 mHeight = frame.height();
1016
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001017 if (mSurfaceHolder != null) {
1018 // The app owns the surface; tell it about what is going on.
1019 if (mSurface.isValid()) {
1020 // XXX .copyFrom() doesn't work!
1021 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1022 mSurfaceHolder.mSurface = mSurface;
1023 }
1024 mSurfaceHolder.mSurfaceLock.unlock();
1025 if (mSurface.isValid()) {
1026 if (!hadSurface) {
1027 mSurfaceHolder.ungetCallbacks();
1028
1029 mIsCreating = true;
1030 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1031 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1032 if (callbacks != null) {
1033 for (SurfaceHolder.Callback c : callbacks) {
1034 c.surfaceCreated(mSurfaceHolder);
1035 }
1036 }
1037 surfaceChanged = true;
1038 }
1039 if (surfaceChanged) {
1040 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1041 lp.format, mWidth, mHeight);
1042 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1043 if (callbacks != null) {
1044 for (SurfaceHolder.Callback c : callbacks) {
1045 c.surfaceChanged(mSurfaceHolder, lp.format,
1046 mWidth, mHeight);
1047 }
1048 }
1049 }
1050 mIsCreating = false;
1051 } else if (hadSurface) {
1052 mSurfaceHolder.ungetCallbacks();
1053 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1054 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1055 if (callbacks != null) {
1056 for (SurfaceHolder.Callback c : callbacks) {
1057 c.surfaceDestroyed(mSurfaceHolder);
1058 }
1059 }
1060 mSurfaceHolder.mSurfaceLock.lock();
1061 // Make surface invalid.
1062 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1063 mSurfaceHolder.mSurface = new Surface();
1064 mSurfaceHolder.mSurfaceLock.unlock();
1065 }
1066 }
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001069 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
1070 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
1072
1073 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001074 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1076 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1077 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1078 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1079
1080 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1081 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1082 + " mHeight=" + mHeight
1083 + " measuredHeight" + host.mMeasuredHeight
1084 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 // Ask host how big it wants to be
1087 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1088
1089 // Implementation of weights from WindowManager.LayoutParams
1090 // We just grow the dimensions as needed and re-measure if
1091 // needs be
1092 int width = host.mMeasuredWidth;
1093 int height = host.mMeasuredHeight;
1094 boolean measureAgain = false;
1095
1096 if (lp.horizontalWeight > 0.0f) {
1097 width += (int) ((mWidth - width) * lp.horizontalWeight);
1098 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1099 MeasureSpec.EXACTLY);
1100 measureAgain = true;
1101 }
1102 if (lp.verticalWeight > 0.0f) {
1103 height += (int) ((mHeight - height) * lp.verticalWeight);
1104 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1105 MeasureSpec.EXACTLY);
1106 measureAgain = true;
1107 }
1108
1109 if (measureAgain) {
1110 if (DEBUG_LAYOUT) Log.v(TAG,
1111 "And hey let's measure once more: width=" + width
1112 + " height=" + height);
1113 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1114 }
1115
1116 mLayoutRequested = true;
1117 }
1118 }
1119
1120 final boolean didLayout = mLayoutRequested;
1121 boolean triggerGlobalLayoutListener = didLayout
1122 || attachInfo.mRecomputeGlobalAttributes;
1123 if (didLayout) {
1124 mLayoutRequested = false;
1125 mScrollMayChange = true;
1126 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1127 "ViewRoot", "Laying out " + host + " to (" +
1128 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001129 long startTime = 0L;
1130 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 startTime = SystemClock.elapsedRealtime();
1132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1134
Romain Guy13922e02009-05-12 17:56:14 -07001135 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1136 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1137 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1138 + "please refer to the logs with the tag "
1139 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1140 }
1141 }
1142
1143 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1145 }
1146
1147 // By this point all views have been sized and positionned
1148 // We can compute the transparent area
1149
1150 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1151 // start out transparent
1152 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1153 host.getLocationInWindow(mTmpLocation);
1154 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1155 mTmpLocation[0] + host.mRight - host.mLeft,
1156 mTmpLocation[1] + host.mBottom - host.mTop);
1157
1158 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001159 if (mTranslator != null) {
1160 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1161 }
1162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1164 mPreviousTransparentRegion.set(mTransparentRegion);
1165 // reconfigure window manager
1166 try {
1167 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1168 } catch (RemoteException e) {
1169 }
1170 }
1171 }
1172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 if (DBG) {
1174 System.out.println("======================================");
1175 System.out.println("performTraversals -- after setFrame");
1176 host.debug();
1177 }
1178 }
1179
1180 if (triggerGlobalLayoutListener) {
1181 attachInfo.mRecomputeGlobalAttributes = false;
1182 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1183 }
1184
1185 if (computesInternalInsets) {
1186 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1187 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1188 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1189 givenContent.left = givenContent.top = givenContent.right
1190 = givenContent.bottom = givenVisible.left = givenVisible.top
1191 = givenVisible.right = givenVisible.bottom = 0;
1192 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001193 Rect contentInsets = insets.contentInsets;
1194 Rect visibleInsets = insets.visibleInsets;
1195 if (mTranslator != null) {
1196 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1197 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1200 mLastGivenInsets.set(insets);
1201 try {
1202 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001203 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 } catch (RemoteException e) {
1205 }
1206 }
1207 }
Romain Guy8506ab42009-06-11 17:35:47 -07001208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 if (mFirst) {
1210 // handle first focus request
1211 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1212 + mView.hasFocus());
1213 if (mView != null) {
1214 if (!mView.hasFocus()) {
1215 mView.requestFocus(View.FOCUS_FORWARD);
1216 mFocusedView = mRealFocusedView = mView.findFocus();
1217 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1218 + mFocusedView);
1219 } else {
1220 mRealFocusedView = mView.findFocus();
1221 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1222 + mRealFocusedView);
1223 }
1224 }
1225 }
1226
1227 mFirst = false;
1228 mWillDrawSoon = false;
1229 mNewSurfaceNeeded = false;
1230 mViewVisibility = viewVisibility;
1231
1232 if (mAttachInfo.mHasWindowFocus) {
1233 final boolean imTarget = WindowManager.LayoutParams
1234 .mayUseInputMethod(mWindowAttributes.flags);
1235 if (imTarget != mLastWasImTarget) {
1236 mLastWasImTarget = imTarget;
1237 InputMethodManager imm = InputMethodManager.peekInstance();
1238 if (imm != null && imTarget) {
1239 imm.startGettingWindowFocus(mView);
1240 imm.onWindowFocus(mView, mView.findFocus(),
1241 mWindowAttributes.softInputMode,
1242 !mHasHadWindowFocus, mWindowAttributes.flags);
1243 }
1244 }
1245 }
Romain Guy8506ab42009-06-11 17:35:47 -07001246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1248
1249 if (!cancelDraw && !newSurface) {
1250 mFullRedrawNeeded = false;
1251 draw(fullRedrawNeeded);
1252
1253 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1254 || mReportNextDraw) {
1255 if (LOCAL_LOGV) {
1256 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1257 }
1258 mReportNextDraw = false;
1259 try {
1260 sWindowSession.finishDrawing(mWindow);
1261 } catch (RemoteException e) {
1262 }
1263 }
1264 } else {
1265 // We were supposed to report when we are done drawing. Since we canceled the
1266 // draw, remember it here.
1267 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1268 mReportNextDraw = true;
1269 }
1270 if (fullRedrawNeeded) {
1271 mFullRedrawNeeded = true;
1272 }
1273 // Try again
1274 scheduleTraversals();
1275 }
1276 }
1277
1278 public void requestTransparentRegion(View child) {
1279 // the test below should not fail unless someone is messing with us
1280 checkThread();
1281 if (mView == child) {
1282 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1283 // Need to make sure we re-evaluate the window attributes next
1284 // time around, to ensure the window has the correct format.
1285 mWindowAttributesChanged = true;
1286 }
1287 }
1288
1289 /**
1290 * Figures out the measure spec for the root view in a window based on it's
1291 * layout params.
1292 *
1293 * @param windowSize
1294 * The available width or height of the window
1295 *
1296 * @param rootDimension
1297 * The layout params for one dimension (width or height) of the
1298 * window.
1299 *
1300 * @return The measure spec to use to measure the root view.
1301 */
1302 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1303 int measureSpec;
1304 switch (rootDimension) {
1305
Romain Guy980a9382010-01-08 15:06:28 -08001306 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 // Window can't resize. Force root view to be windowSize.
1308 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1309 break;
1310 case ViewGroup.LayoutParams.WRAP_CONTENT:
1311 // Window can resize. Set max size for root view.
1312 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1313 break;
1314 default:
1315 // Window wants to be an exact size. Force root view to be that size.
1316 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1317 break;
1318 }
1319 return measureSpec;
1320 }
1321
1322 private void draw(boolean fullRedrawNeeded) {
1323 Surface surface = mSurface;
1324 if (surface == null || !surface.isValid()) {
1325 return;
1326 }
1327
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001328 if (!sFirstDrawComplete) {
1329 synchronized (sFirstDrawHandlers) {
1330 sFirstDrawComplete = true;
1331 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1332 post(sFirstDrawHandlers.get(i));
1333 }
1334 }
1335 }
1336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 scrollToRectOrFocus(null, false);
1338
1339 if (mAttachInfo.mViewScrollChanged) {
1340 mAttachInfo.mViewScrollChanged = false;
1341 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1342 }
Romain Guy8506ab42009-06-11 17:35:47 -07001343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001345 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 if (scrolling) {
1347 yoff = mScroller.getCurrY();
1348 } else {
1349 yoff = mScrollY;
1350 }
1351 if (mCurScrollY != yoff) {
1352 mCurScrollY = yoff;
1353 fullRedrawNeeded = true;
1354 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001355 float appScale = mAttachInfo.mApplicationScale;
1356 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001359 if (mSurfaceHolder != null) {
1360 // The app owns the surface, we won't draw.
1361 dirty.setEmpty();
1362 return;
1363 }
1364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 if (mUseGL) {
1366 if (!dirty.isEmpty()) {
1367 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001368 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 mGL.glDisable(GL_SCISSOR_TEST);
1370 mGL.glClearColor(0, 0, 0, 0);
1371 mGL.glClear(GL_COLOR_BUFFER_BIT);
1372 mGL.glEnable(GL_SCISSOR_TEST);
1373
1374 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001375 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001377
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001378 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1379 try {
1380 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001381 if (mTranslator != null) {
1382 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001383 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001384 canvas.setScreenDensity(scalingRequired
1385 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001386 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001387 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1388 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1389 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001390 } finally {
1391 canvas.restoreToCount(saveCount);
1392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393
Romain Guy5bcdff42009-05-14 21:27:18 -07001394 mAttachInfo.mIgnoreDirtyState = false;
1395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1397 checkEglErrors();
1398
Mike Reedfd716532009-10-12 14:42:56 -04001399 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 int now = (int)SystemClock.elapsedRealtime();
1401 if (sDrawTime != 0) {
1402 nativeShowFPS(canvas, now - sDrawTime);
1403 }
1404 sDrawTime = now;
1405 }
1406 }
1407 }
1408 if (scrolling) {
1409 mFullRedrawNeeded = true;
1410 scheduleTraversals();
1411 }
1412 return;
1413 }
1414
Romain Guy5bcdff42009-05-14 21:27:18 -07001415 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001416 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001417 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419
1420 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1421 Log.v("ViewRoot", "Draw " + mView + "/"
1422 + mWindowAttributes.getTitle()
1423 + ": dirty={" + dirty.left + "," + dirty.top
1424 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001425 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1426 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001429 if (!dirty.isEmpty() || mIsAnimating) {
1430 Canvas canvas;
1431 try {
1432 int left = dirty.left;
1433 int top = dirty.top;
1434 int right = dirty.right;
1435 int bottom = dirty.bottom;
1436 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001437
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001438 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1439 bottom != dirty.bottom) {
1440 mAttachInfo.mIgnoreDirtyState = true;
1441 }
1442
1443 // TODO: Do this in native
1444 canvas.setDensity(mDensity);
1445 } catch (Surface.OutOfResourcesException e) {
1446 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1447 // TODO: we should ask the window manager to do something!
1448 // for now we just do nothing
1449 return;
1450 } catch (IllegalArgumentException e) {
1451 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1452 // TODO: we should ask the window manager to do something!
1453 // for now we just do nothing
1454 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001455 }
1456
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001457 try {
1458 if (!dirty.isEmpty() || mIsAnimating) {
1459 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001461 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1462 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1463 + canvas.getWidth() + ", h=" + canvas.getHeight());
1464 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001467 if (Config.DEBUG && ViewDebug.profileDrawing) {
1468 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001470
1471 // If this bitmap's format includes an alpha channel, we
1472 // need to clear it before drawing so that the child will
1473 // properly re-composite its drawing on a transparent
1474 // background. This automatically respects the clip/dirty region
1475 // or
1476 // If we are applying an offset, we need to clear the area
1477 // where the offset doesn't appear to avoid having garbage
1478 // left in the blank areas.
1479 if (!canvas.isOpaque() || yoff != 0) {
1480 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1481 }
1482
1483 dirty.setEmpty();
1484 mIsAnimating = false;
1485 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1486 mView.mPrivateFlags |= View.DRAWN;
1487
1488 if (DEBUG_DRAW) {
1489 Context cxt = mView.getContext();
1490 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1491 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1492 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1493 }
1494 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1495 try {
1496 canvas.translate(0, -yoff);
1497 if (mTranslator != null) {
1498 mTranslator.translateCanvas(canvas);
1499 }
1500 canvas.setScreenDensity(scalingRequired
1501 ? DisplayMetrics.DENSITY_DEVICE : 0);
1502 mView.draw(canvas);
1503 } finally {
1504 mAttachInfo.mIgnoreDirtyState = false;
1505 canvas.restoreToCount(saveCount);
1506 }
1507
1508 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1509 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1510 }
1511
1512 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1513 int now = (int)SystemClock.elapsedRealtime();
1514 if (sDrawTime != 0) {
1515 nativeShowFPS(canvas, now - sDrawTime);
1516 }
1517 sDrawTime = now;
1518 }
1519
1520 if (Config.DEBUG && ViewDebug.profileDrawing) {
1521 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001525 } finally {
1526 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529
1530 if (LOCAL_LOGV) {
1531 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1532 }
Romain Guy8506ab42009-06-11 17:35:47 -07001533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 if (scrolling) {
1535 mFullRedrawNeeded = true;
1536 scheduleTraversals();
1537 }
1538 }
1539
1540 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1541 final View.AttachInfo attachInfo = mAttachInfo;
1542 final Rect ci = attachInfo.mContentInsets;
1543 final Rect vi = attachInfo.mVisibleInsets;
1544 int scrollY = 0;
1545 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 if (vi.left > ci.left || vi.top > ci.top
1548 || vi.right > ci.right || vi.bottom > ci.bottom) {
1549 // We'll assume that we aren't going to change the scroll
1550 // offset, since we want to avoid that unless it is actually
1551 // going to make the focus visible... otherwise we scroll
1552 // all over the place.
1553 scrollY = mScrollY;
1554 // We can be called for two different situations: during a draw,
1555 // to update the scroll position if the focus has changed (in which
1556 // case 'rectangle' is null), or in response to a
1557 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1558 // is non-null and we just want to scroll to whatever that
1559 // rectangle is).
1560 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001561
1562 // When in touch mode, focus points to the previously focused view,
1563 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001564 // line checks whether the view is still in our hierarchy.
1565 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001566 mRealFocusedView = null;
1567 return false;
1568 }
1569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 if (focus != mLastScrolledFocus) {
1571 // If the focus has changed, then ignore any requests to scroll
1572 // to a rectangle; first we want to make sure the entire focus
1573 // view is visible.
1574 rectangle = null;
1575 }
1576 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1577 + " rectangle=" + rectangle + " ci=" + ci
1578 + " vi=" + vi);
1579 if (focus == mLastScrolledFocus && !mScrollMayChange
1580 && rectangle == null) {
1581 // Optimization: if the focus hasn't changed since last
1582 // time, and no layout has happened, then just leave things
1583 // as they are.
1584 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1585 + mScrollY + " vi=" + vi.toShortString());
1586 } else if (focus != null) {
1587 // We need to determine if the currently focused view is
1588 // within the visible part of the window and, if not, apply
1589 // a pan so it can be seen.
1590 mLastScrolledFocus = focus;
1591 mScrollMayChange = false;
1592 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1593 // Try to find the rectangle from the focus view.
1594 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1595 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1596 + mView.getWidth() + " h=" + mView.getHeight()
1597 + " ci=" + ci.toShortString()
1598 + " vi=" + vi.toShortString());
1599 if (rectangle == null) {
1600 focus.getFocusedRect(mTempRect);
1601 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1602 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001603 if (mView instanceof ViewGroup) {
1604 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1605 focus, mTempRect);
1606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1608 "Focus in window: focusRect="
1609 + mTempRect.toShortString()
1610 + " visRect=" + mVisRect.toShortString());
1611 } else {
1612 mTempRect.set(rectangle);
1613 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1614 "Request scroll to rect: "
1615 + mTempRect.toShortString()
1616 + " visRect=" + mVisRect.toShortString());
1617 }
1618 if (mTempRect.intersect(mVisRect)) {
1619 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1620 "Focus window visible rect: "
1621 + mTempRect.toShortString());
1622 if (mTempRect.height() >
1623 (mView.getHeight()-vi.top-vi.bottom)) {
1624 // If the focus simply is not going to fit, then
1625 // best is probably just to leave things as-is.
1626 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1627 "Too tall; leaving scrollY=" + scrollY);
1628 } else if ((mTempRect.top-scrollY) < vi.top) {
1629 scrollY -= vi.top - (mTempRect.top-scrollY);
1630 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1631 "Top covered; scrollY=" + scrollY);
1632 } else if ((mTempRect.bottom-scrollY)
1633 > (mView.getHeight()-vi.bottom)) {
1634 scrollY += (mTempRect.bottom-scrollY)
1635 - (mView.getHeight()-vi.bottom);
1636 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1637 "Bottom covered; scrollY=" + scrollY);
1638 }
1639 handled = true;
1640 }
1641 }
1642 }
1643 }
Romain Guy8506ab42009-06-11 17:35:47 -07001644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if (scrollY != mScrollY) {
1646 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1647 + mScrollY + " , new=" + scrollY);
1648 if (!immediate) {
1649 if (mScroller == null) {
1650 mScroller = new Scroller(mView.getContext());
1651 }
1652 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1653 } else if (mScroller != null) {
1654 mScroller.abortAnimation();
1655 }
1656 mScrollY = scrollY;
1657 }
Romain Guy8506ab42009-06-11 17:35:47 -07001658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 return handled;
1660 }
Romain Guy8506ab42009-06-11 17:35:47 -07001661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 public void requestChildFocus(View child, View focused) {
1663 checkThread();
1664 if (mFocusedView != focused) {
1665 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1666 scheduleTraversals();
1667 }
1668 mFocusedView = mRealFocusedView = focused;
1669 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1670 + mFocusedView);
1671 }
1672
1673 public void clearChildFocus(View child) {
1674 checkThread();
1675
1676 View oldFocus = mFocusedView;
1677
1678 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1679 mFocusedView = mRealFocusedView = null;
1680 if (mView != null && !mView.hasFocus()) {
1681 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1682 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1683 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1684 }
1685 } else if (oldFocus != null) {
1686 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1687 }
1688 }
1689
1690
1691 public void focusableViewAvailable(View v) {
1692 checkThread();
1693
1694 if (mView != null && !mView.hasFocus()) {
1695 v.requestFocus();
1696 } else {
1697 // the one case where will transfer focus away from the current one
1698 // is if the current view is a view group that prefers to give focus
1699 // to its children first AND the view is a descendant of it.
1700 mFocusedView = mView.findFocus();
1701 boolean descendantsHaveDibsOnFocus =
1702 (mFocusedView instanceof ViewGroup) &&
1703 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1704 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1705 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1706 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1707 v.requestFocus();
1708 }
1709 }
1710 }
1711
1712 public void recomputeViewAttributes(View child) {
1713 checkThread();
1714 if (mView == child) {
1715 mAttachInfo.mRecomputeGlobalAttributes = true;
1716 if (!mWillDrawSoon) {
1717 scheduleTraversals();
1718 }
1719 }
1720 }
1721
1722 void dispatchDetachedFromWindow() {
1723 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1724
1725 if (mView != null) {
1726 mView.dispatchDetachedFromWindow();
1727 }
1728
1729 mView = null;
1730 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001731 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732
1733 if (mUseGL) {
1734 destroyGL();
1735 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001736 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737
1738 try {
1739 sWindowSession.remove(mWindow);
1740 } catch (RemoteException e) {
1741 }
1742 }
Romain Guy8506ab42009-06-11 17:35:47 -07001743
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001744 void updateConfiguration(Configuration config, boolean force) {
1745 if (DEBUG_CONFIGURATION) Log.v(TAG,
1746 "Applying new config to window "
1747 + mWindowAttributes.getTitle()
1748 + ": " + config);
1749 synchronized (sConfigCallbacks) {
1750 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1751 sConfigCallbacks.get(i).onConfigurationChanged(config);
1752 }
1753 }
1754 if (mView != null) {
1755 // At this point the resources have been updated to
1756 // have the most recent config, whatever that is. Use
1757 // the on in them which may be newer.
1758 if (mView != null) {
1759 config = mView.getResources().getConfiguration();
1760 }
1761 if (force || mLastConfiguration.diff(config) != 0) {
1762 mLastConfiguration.setTo(config);
1763 mView.dispatchConfigurationChanged(config);
1764 }
1765 }
1766 }
1767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 /**
1769 * Return true if child is an ancestor of parent, (or equal to the parent).
1770 */
1771 private static boolean isViewDescendantOf(View child, View parent) {
1772 if (child == parent) {
1773 return true;
1774 }
1775
1776 final ViewParent theParent = child.getParent();
1777 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1778 }
1779
Romain Guycdb86672010-03-18 18:54:50 -07001780 private static void forceLayout(View view) {
1781 view.forceLayout();
1782 if (view instanceof ViewGroup) {
1783 ViewGroup group = (ViewGroup) view;
1784 final int count = group.getChildCount();
1785 for (int i = 0; i < count; i++) {
1786 forceLayout(group.getChildAt(i));
1787 }
1788 }
1789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790
1791 public final static int DO_TRAVERSAL = 1000;
1792 public final static int DIE = 1001;
1793 public final static int RESIZED = 1002;
1794 public final static int RESIZED_REPORT = 1003;
1795 public final static int WINDOW_FOCUS_CHANGED = 1004;
1796 public final static int DISPATCH_KEY = 1005;
1797 public final static int DISPATCH_POINTER = 1006;
1798 public final static int DISPATCH_TRACKBALL = 1007;
1799 public final static int DISPATCH_APP_VISIBILITY = 1008;
1800 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1801 public final static int FINISHED_EVENT = 1010;
1802 public final static int DISPATCH_KEY_FROM_IME = 1011;
1803 public final static int FINISH_INPUT_CONNECTION = 1012;
1804 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001805 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806
1807 @Override
1808 public void handleMessage(Message msg) {
1809 switch (msg.what) {
1810 case View.AttachInfo.INVALIDATE_MSG:
1811 ((View) msg.obj).invalidate();
1812 break;
1813 case View.AttachInfo.INVALIDATE_RECT_MSG:
1814 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1815 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1816 info.release();
1817 break;
1818 case DO_TRAVERSAL:
1819 if (mProfile) {
1820 Debug.startMethodTracing("ViewRoot");
1821 }
1822
1823 performTraversals();
1824
1825 if (mProfile) {
1826 Debug.stopMethodTracing();
1827 mProfile = false;
1828 }
1829 break;
1830 case FINISHED_EVENT:
1831 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1832 break;
1833 case DISPATCH_KEY:
1834 if (LOCAL_LOGV) Log.v(
1835 "ViewRoot", "Dispatching key "
1836 + msg.obj + " to " + mView);
1837 deliverKeyEvent((KeyEvent)msg.obj, true);
1838 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001839 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001841 boolean callWhenDone = msg.arg1 != 0;
1842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 if (event == null) {
1844 try {
Michael Chan53071d62009-05-13 17:29:48 -07001845 long timeBeforeGettingEvents;
1846 if (MEASURE_LATENCY) {
1847 timeBeforeGettingEvents = System.nanoTime();
1848 }
1849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001851
1852 if (MEASURE_LATENCY && event != null) {
1853 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1854 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 } catch (RemoteException e) {
1857 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001858 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001860 if (event != null && mTranslator != null) {
1861 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 try {
1864 boolean handled;
1865 if (mView != null && mAdded && event != null) {
1866
1867 // enter touch mode on the down
1868 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1869 if (isDown) {
1870 ensureTouchMode(true);
1871 }
1872 if(Config.LOGV) {
1873 captureMotionLog("captureDispatchPointer", event);
1874 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001875 if (mCurScrollY != 0) {
1876 event.offsetLocation(0, mCurScrollY);
1877 }
Michael Chan53071d62009-05-13 17:29:48 -07001878 if (MEASURE_LATENCY) {
1879 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001882 if (MEASURE_LATENCY) {
1883 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 if (!handled && isDown) {
1886 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1887
1888 final int edgeFlags = event.getEdgeFlags();
1889 int direction = View.FOCUS_UP;
1890 int x = (int)event.getX();
1891 int y = (int)event.getY();
1892 final int[] deltas = new int[2];
1893
1894 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1895 direction = View.FOCUS_DOWN;
1896 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1897 deltas[0] = edgeSlop;
1898 x += edgeSlop;
1899 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1900 deltas[0] = -edgeSlop;
1901 x -= edgeSlop;
1902 }
1903 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1904 direction = View.FOCUS_UP;
1905 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1906 deltas[0] = edgeSlop;
1907 x += edgeSlop;
1908 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1909 deltas[0] = -edgeSlop;
1910 x -= edgeSlop;
1911 }
1912 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1913 direction = View.FOCUS_RIGHT;
1914 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1915 direction = View.FOCUS_LEFT;
1916 }
1917
1918 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1919 View nearest = FocusFinder.getInstance().findNearestTouchable(
1920 ((ViewGroup) mView), x, y, direction, deltas);
1921 if (nearest != null) {
1922 event.offsetLocation(deltas[0], deltas[1]);
1923 event.setEdgeFlags(0);
1924 mView.dispatchTouchEvent(event);
1925 }
1926 }
1927 }
1928 }
1929 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001930 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 try {
1932 sWindowSession.finishKey(mWindow);
1933 } catch (RemoteException e) {
1934 }
1935 }
1936 if (event != null) {
1937 event.recycle();
1938 }
1939 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1940 // Let the exception fall through -- the looper will catch
1941 // it and take care of the bad app for us.
1942 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001943 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001945 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 break;
1947 case DISPATCH_APP_VISIBILITY:
1948 handleAppVisibility(msg.arg1 != 0);
1949 break;
1950 case DISPATCH_GET_NEW_SURFACE:
1951 handleGetNewSurface();
1952 break;
1953 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001954 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001957 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001958 && mPendingVisibleInsets.equals(ri.visibleInsets)
1959 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 break;
1961 }
1962 // fall through...
1963 case RESIZED_REPORT:
1964 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001965 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1966 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001967 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 mWinFrame.left = 0;
1970 mWinFrame.right = msg.arg1;
1971 mWinFrame.top = 0;
1972 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001973 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1974 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 if (msg.what == RESIZED_REPORT) {
1976 mReportNextDraw = true;
1977 }
Romain Guycdb86672010-03-18 18:54:50 -07001978
1979 if (mView != null) {
1980 forceLayout(mView);
1981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 requestLayout();
1983 }
1984 break;
1985 case WINDOW_FOCUS_CHANGED: {
1986 if (mAdded) {
1987 boolean hasWindowFocus = msg.arg1 != 0;
1988 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1989 if (hasWindowFocus) {
1990 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001991 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992
1993 if (mGlWanted) {
1994 checkEglErrors();
1995 // we lost the gl context, so recreate it.
1996 if (mGlWanted && !mUseGL) {
1997 initializeGL();
1998 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001999 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002000 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002001 (int) (mWidth * appScale + 0.5f),
2002 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004 }
2005 }
2006 }
Romain Guy8506ab42009-06-11 17:35:47 -07002007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 mLastWasImTarget = WindowManager.LayoutParams
2009 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 InputMethodManager imm = InputMethodManager.peekInstance();
2012 if (mView != null) {
2013 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2014 imm.startGettingWindowFocus(mView);
2015 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002016 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 mView.dispatchWindowFocusChanged(hasWindowFocus);
2018 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 // Note: must be done after the focus change callbacks,
2021 // so all of the view state is set up correctly.
2022 if (hasWindowFocus) {
2023 if (imm != null && mLastWasImTarget) {
2024 imm.onWindowFocus(mView, mView.findFocus(),
2025 mWindowAttributes.softInputMode,
2026 !mHasHadWindowFocus, mWindowAttributes.flags);
2027 }
2028 // Clear the forward bit. We can just do this directly, since
2029 // the window manager doesn't care about it.
2030 mWindowAttributes.softInputMode &=
2031 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2032 ((WindowManager.LayoutParams)mView.getLayoutParams())
2033 .softInputMode &=
2034 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2035 mHasHadWindowFocus = true;
2036 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002037
2038 if (hasWindowFocus && mView != null) {
2039 sendAccessibilityEvents();
2040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042 } break;
2043 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002044 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002046 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 if (LOCAL_LOGV) Log.v(
2048 "ViewRoot", "Dispatching key "
2049 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002050 KeyEvent event = (KeyEvent)msg.obj;
2051 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2052 // The IME is trying to say this event is from the
2053 // system! Bad bad bad!
2054 event = KeyEvent.changeFlags(event,
2055 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
2056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002058 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 case FINISH_INPUT_CONNECTION: {
2060 InputMethodManager imm = InputMethodManager.peekInstance();
2061 if (imm != null) {
2062 imm.reportFinishInputConnection((InputConnection)msg.obj);
2063 }
2064 } break;
2065 case CHECK_FOCUS: {
2066 InputMethodManager imm = InputMethodManager.peekInstance();
2067 if (imm != null) {
2068 imm.checkFocus();
2069 }
2070 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002071 case CLOSE_SYSTEM_DIALOGS: {
2072 if (mView != null) {
2073 mView.onCloseSystemDialogs((String)msg.obj);
2074 }
2075 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 }
2077 }
2078
2079 /**
2080 * Something in the current window tells us we need to change the touch mode. For
2081 * example, we are not in touch mode, and the user touches the screen.
2082 *
2083 * If the touch mode has changed, tell the window manager, and handle it locally.
2084 *
2085 * @param inTouchMode Whether we want to be in touch mode.
2086 * @return True if the touch mode changed and focus changed was changed as a result
2087 */
2088 boolean ensureTouchMode(boolean inTouchMode) {
2089 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2090 + "touch mode is " + mAttachInfo.mInTouchMode);
2091 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2092
2093 // tell the window manager
2094 try {
2095 sWindowSession.setInTouchMode(inTouchMode);
2096 } catch (RemoteException e) {
2097 throw new RuntimeException(e);
2098 }
2099
2100 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002101 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
2103
2104 /**
2105 * Ensure that the touch mode for this window is set, and if it is changing,
2106 * take the appropriate action.
2107 * @param inTouchMode Whether we want to be in touch mode.
2108 * @return True if the touch mode changed and focus changed was changed as a result
2109 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002110 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2112 + "touch mode is " + mAttachInfo.mInTouchMode);
2113
2114 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2115
2116 mAttachInfo.mInTouchMode = inTouchMode;
2117 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2118
Romain Guy2d4cff62010-04-09 15:39:00 -07002119 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121
2122 private boolean enterTouchMode() {
2123 if (mView != null) {
2124 if (mView.hasFocus()) {
2125 // note: not relying on mFocusedView here because this could
2126 // be when the window is first being added, and mFocused isn't
2127 // set yet.
2128 final View focused = mView.findFocus();
2129 if (focused != null && !focused.isFocusableInTouchMode()) {
2130
2131 final ViewGroup ancestorToTakeFocus =
2132 findAncestorToTakeFocusInTouchMode(focused);
2133 if (ancestorToTakeFocus != null) {
2134 // there is an ancestor that wants focus after its descendants that
2135 // is focusable in touch mode.. give it focus
2136 return ancestorToTakeFocus.requestFocus();
2137 } else {
2138 // nothing appropriate to have focus in touch mode, clear it out
2139 mView.unFocus();
2140 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2141 mFocusedView = null;
2142 return true;
2143 }
2144 }
2145 }
2146 }
2147 return false;
2148 }
2149
2150
2151 /**
2152 * Find an ancestor of focused that wants focus after its descendants and is
2153 * focusable in touch mode.
2154 * @param focused The currently focused view.
2155 * @return An appropriate view, or null if no such view exists.
2156 */
2157 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2158 ViewParent parent = focused.getParent();
2159 while (parent instanceof ViewGroup) {
2160 final ViewGroup vgParent = (ViewGroup) parent;
2161 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2162 && vgParent.isFocusableInTouchMode()) {
2163 return vgParent;
2164 }
2165 if (vgParent.isRootNamespace()) {
2166 return null;
2167 } else {
2168 parent = vgParent.getParent();
2169 }
2170 }
2171 return null;
2172 }
2173
2174 private boolean leaveTouchMode() {
2175 if (mView != null) {
2176 if (mView.hasFocus()) {
2177 // i learned the hard way to not trust mFocusedView :)
2178 mFocusedView = mView.findFocus();
2179 if (!(mFocusedView instanceof ViewGroup)) {
2180 // some view has focus, let it keep it
2181 return false;
2182 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2183 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2184 // some view group has focus, and doesn't prefer its children
2185 // over itself for focus, so let them keep it.
2186 return false;
2187 }
2188 }
2189
2190 // find the best view to give focus to in this brave new non-touch-mode
2191 // world
2192 final View focused = focusSearch(null, View.FOCUS_DOWN);
2193 if (focused != null) {
2194 return focused.requestFocus(View.FOCUS_DOWN);
2195 }
2196 }
2197 return false;
2198 }
2199
2200
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002201 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 if (event == null) {
2203 try {
2204 event = sWindowSession.getPendingTrackballMove(mWindow);
2205 } catch (RemoteException e) {
2206 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002207 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 }
2209
2210 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2211
2212 boolean handled = false;
2213 try {
2214 if (event == null) {
2215 handled = true;
2216 } else if (mView != null && mAdded) {
2217 handled = mView.dispatchTrackballEvent(event);
2218 if (!handled) {
2219 // we could do something here, like changing the focus
2220 // or something?
2221 }
2222 }
2223 } finally {
2224 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002225 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 try {
2227 sWindowSession.finishKey(mWindow);
2228 } catch (RemoteException e) {
2229 }
2230 }
2231 if (event != null) {
2232 event.recycle();
2233 }
2234 // If we reach this, we delivered a trackball event to mView and
2235 // mView consumed it. Because we will not translate the trackball
2236 // event into a key event, touch mode will not exit, so we exit
2237 // touch mode here.
2238 ensureTouchMode(false);
2239 //noinspection ReturnInsideFinallyBlock
2240 return;
2241 }
2242 // Let the exception fall through -- the looper will catch
2243 // it and take care of the bad app for us.
2244 }
2245
2246 final TrackballAxis x = mTrackballAxisX;
2247 final TrackballAxis y = mTrackballAxisY;
2248
2249 long curTime = SystemClock.uptimeMillis();
2250 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2251 // It has been too long since the last movement,
2252 // so restart at the beginning.
2253 x.reset(0);
2254 y.reset(0);
2255 mLastTrackballTime = curTime;
2256 }
2257
2258 try {
2259 final int action = event.getAction();
2260 final int metastate = event.getMetaState();
2261 switch (action) {
2262 case MotionEvent.ACTION_DOWN:
2263 x.reset(2);
2264 y.reset(2);
2265 deliverKeyEvent(new KeyEvent(curTime, curTime,
2266 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2267 0, metastate), false);
2268 break;
2269 case MotionEvent.ACTION_UP:
2270 x.reset(2);
2271 y.reset(2);
2272 deliverKeyEvent(new KeyEvent(curTime, curTime,
2273 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2274 0, metastate), false);
2275 break;
2276 }
2277
2278 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2279 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2280 + " move=" + event.getX()
2281 + " / Y=" + y.position + " step="
2282 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2283 + " move=" + event.getY());
2284 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2285 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2286
2287 // Generate DPAD events based on the trackball movement.
2288 // We pick the axis that has moved the most as the direction of
2289 // the DPAD. When we generate DPAD events for one axis, then the
2290 // other axis is reset -- we don't want to perform DPAD jumps due
2291 // to slight movements in the trackball when making major movements
2292 // along the other axis.
2293 int keycode = 0;
2294 int movement = 0;
2295 float accel = 1;
2296 if (xOff > yOff) {
2297 movement = x.generate((2/event.getXPrecision()));
2298 if (movement != 0) {
2299 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2300 : KeyEvent.KEYCODE_DPAD_LEFT;
2301 accel = x.acceleration;
2302 y.reset(2);
2303 }
2304 } else if (yOff > 0) {
2305 movement = y.generate((2/event.getYPrecision()));
2306 if (movement != 0) {
2307 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2308 : KeyEvent.KEYCODE_DPAD_UP;
2309 accel = y.acceleration;
2310 x.reset(2);
2311 }
2312 }
2313
2314 if (keycode != 0) {
2315 if (movement < 0) movement = -movement;
2316 int accelMovement = (int)(movement * accel);
2317 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2318 + " accelMovement=" + accelMovement
2319 + " accel=" + accel);
2320 if (accelMovement > movement) {
2321 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2322 + keycode);
2323 movement--;
2324 deliverKeyEvent(new KeyEvent(curTime, curTime,
2325 KeyEvent.ACTION_MULTIPLE, keycode,
2326 accelMovement-movement, metastate), false);
2327 }
2328 while (movement > 0) {
2329 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2330 + keycode);
2331 movement--;
2332 curTime = SystemClock.uptimeMillis();
2333 deliverKeyEvent(new KeyEvent(curTime, curTime,
2334 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2335 deliverKeyEvent(new KeyEvent(curTime, curTime,
2336 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2337 }
2338 mLastTrackballTime = curTime;
2339 }
2340 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002341 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 try {
2343 sWindowSession.finishKey(mWindow);
2344 } catch (RemoteException e) {
2345 }
2346 if (event != null) {
2347 event.recycle();
2348 }
2349 }
2350 // Let the exception fall through -- the looper will catch
2351 // it and take care of the bad app for us.
2352 }
2353 }
2354
2355 /**
2356 * @param keyCode The key code
2357 * @return True if the key is directional.
2358 */
2359 static boolean isDirectional(int keyCode) {
2360 switch (keyCode) {
2361 case KeyEvent.KEYCODE_DPAD_LEFT:
2362 case KeyEvent.KEYCODE_DPAD_RIGHT:
2363 case KeyEvent.KEYCODE_DPAD_UP:
2364 case KeyEvent.KEYCODE_DPAD_DOWN:
2365 return true;
2366 }
2367 return false;
2368 }
2369
2370 /**
2371 * Returns true if this key is a keyboard key.
2372 * @param keyEvent The key event.
2373 * @return whether this key is a keyboard key.
2374 */
2375 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2376 final int convertedKey = keyEvent.getUnicodeChar();
2377 return convertedKey > 0;
2378 }
2379
2380
2381
2382 /**
2383 * See if the key event means we should leave touch mode (and leave touch
2384 * mode if so).
2385 * @param event The key event.
2386 * @return Whether this key event should be consumed (meaning the act of
2387 * leaving touch mode alone is considered the event).
2388 */
2389 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002390 final int action = event.getAction();
2391 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 return false;
2393 }
2394 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2395 return false;
2396 }
2397
2398 // only relevant if we are in touch mode
2399 if (!mAttachInfo.mInTouchMode) {
2400 return false;
2401 }
2402
2403 // if something like an edit text has focus and the user is typing,
2404 // leave touch mode
2405 //
2406 // note: the condition of not being a keyboard key is kind of a hacky
2407 // approximation of whether we think the focused view will want the
2408 // key; if we knew for sure whether the focused view would consume
2409 // the event, that would be better.
2410 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2411 mFocusedView = mView.findFocus();
2412 if ((mFocusedView instanceof ViewGroup)
2413 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2414 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2415 // something has focus, but is holding it weakly as a container
2416 return false;
2417 }
2418 if (ensureTouchMode(false)) {
2419 throw new IllegalStateException("should not have changed focus "
2420 + "when leaving touch mode while a view has focus.");
2421 }
2422 return false;
2423 }
2424
2425 if (isDirectional(event.getKeyCode())) {
2426 // no view has focus, so we leave touch mode (and find something
2427 // to give focus to). the event is consumed if we were able to
2428 // find something to give focus to.
2429 return ensureTouchMode(false);
2430 }
2431 return false;
2432 }
2433
2434 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002435 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 */
2437 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002438 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 if (ev == null ||
2440 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2441 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 }
Romain Guy8506ab42009-06-11 17:35:47 -07002443
2444 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 sb.append(ev.getDownTime()).append(',');
2446 sb.append(ev.getEventTime()).append(',');
2447 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002448 sb.append(ev.getX()).append(',');
2449 sb.append(ev.getY()).append(',');
2450 sb.append(ev.getPressure()).append(',');
2451 sb.append(ev.getSize()).append(',');
2452 sb.append(ev.getMetaState()).append(',');
2453 sb.append(ev.getXPrecision()).append(',');
2454 sb.append(ev.getYPrecision()).append(',');
2455 sb.append(ev.getDeviceId()).append(',');
2456 sb.append(ev.getEdgeFlags());
2457 Log.d(TAG, sb.toString());
2458 }
2459 /**
2460 * log motion events
2461 */
2462 private static void captureKeyLog(String subTag, KeyEvent ev) {
2463 //check dynamic switch
2464 if (ev == null ||
2465 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2466 return;
2467 }
2468 StringBuilder sb = new StringBuilder(subTag + ": ");
2469 sb.append(ev.getDownTime()).append(',');
2470 sb.append(ev.getEventTime()).append(',');
2471 sb.append(ev.getAction()).append(',');
2472 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 sb.append(ev.getRepeatCount()).append(',');
2474 sb.append(ev.getMetaState()).append(',');
2475 sb.append(ev.getDeviceId()).append(',');
2476 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002477 Log.d(TAG, sb.toString());
2478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479
2480 int enqueuePendingEvent(Object event, boolean sendDone) {
2481 int seq = mPendingEventSeq+1;
2482 if (seq < 0) seq = 0;
2483 mPendingEventSeq = seq;
2484 mPendingEvents.put(seq, event);
2485 return sendDone ? seq : -seq;
2486 }
2487
2488 Object retrievePendingEvent(int seq) {
2489 if (seq < 0) seq = -seq;
2490 Object event = mPendingEvents.get(seq);
2491 if (event != null) {
2492 mPendingEvents.remove(seq);
2493 }
2494 return event;
2495 }
Romain Guy8506ab42009-06-11 17:35:47 -07002496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2498 // If mView is null, we just consume the key event because it doesn't
2499 // make sense to do anything else with it.
2500 boolean handled = mView != null
2501 ? mView.dispatchKeyEventPreIme(event) : true;
2502 if (handled) {
2503 if (sendDone) {
2504 if (LOCAL_LOGV) Log.v(
2505 "ViewRoot", "Telling window manager key is finished");
2506 try {
2507 sWindowSession.finishKey(mWindow);
2508 } catch (RemoteException e) {
2509 }
2510 }
2511 return;
2512 }
2513 // If it is possible for this window to interact with the input
2514 // method window, then we want to first dispatch our key events
2515 // to the input method.
2516 if (mLastWasImTarget) {
2517 InputMethodManager imm = InputMethodManager.peekInstance();
2518 if (imm != null && mView != null) {
2519 int seq = enqueuePendingEvent(event, sendDone);
2520 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2521 + seq + " event=" + event);
2522 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2523 mInputMethodCallback);
2524 return;
2525 }
2526 }
2527 deliverKeyEventToViewHierarchy(event, sendDone);
2528 }
2529
2530 void handleFinishedEvent(int seq, boolean handled) {
2531 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2532 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2533 + " handled=" + handled + " event=" + event);
2534 if (event != null) {
2535 final boolean sendDone = seq >= 0;
2536 if (!handled) {
2537 deliverKeyEventToViewHierarchy(event, sendDone);
2538 return;
2539 } else if (sendDone) {
2540 if (LOCAL_LOGV) Log.v(
2541 "ViewRoot", "Telling window manager key is finished");
2542 try {
2543 sWindowSession.finishKey(mWindow);
2544 } catch (RemoteException e) {
2545 }
2546 } else {
2547 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2548 + " handled=" + handled + " ev=" + event
2549 + ") neither delivering nor finishing key");
2550 }
2551 }
2552 }
Romain Guy8506ab42009-06-11 17:35:47 -07002553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2555 try {
2556 if (mView != null && mAdded) {
2557 final int action = event.getAction();
2558 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2559
2560 if (checkForLeavingTouchModeAndConsume(event)) {
2561 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002562 }
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 if (Config.LOGV) {
2565 captureKeyLog("captureDispatchKeyEvent", event);
2566 }
2567 boolean keyHandled = mView.dispatchKeyEvent(event);
2568
2569 if (!keyHandled && isDown) {
2570 int direction = 0;
2571 switch (event.getKeyCode()) {
2572 case KeyEvent.KEYCODE_DPAD_LEFT:
2573 direction = View.FOCUS_LEFT;
2574 break;
2575 case KeyEvent.KEYCODE_DPAD_RIGHT:
2576 direction = View.FOCUS_RIGHT;
2577 break;
2578 case KeyEvent.KEYCODE_DPAD_UP:
2579 direction = View.FOCUS_UP;
2580 break;
2581 case KeyEvent.KEYCODE_DPAD_DOWN:
2582 direction = View.FOCUS_DOWN;
2583 break;
2584 }
2585
2586 if (direction != 0) {
2587
2588 View focused = mView != null ? mView.findFocus() : null;
2589 if (focused != null) {
2590 View v = focused.focusSearch(direction);
2591 boolean focusPassed = false;
2592 if (v != null && v != focused) {
2593 // do the math the get the interesting rect
2594 // of previous focused into the coord system of
2595 // newly focused view
2596 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002597 if (mView instanceof ViewGroup) {
2598 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2599 focused, mTempRect);
2600 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2601 v, mTempRect);
2602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 focusPassed = v.requestFocus(direction, mTempRect);
2604 }
2605
2606 if (!focusPassed) {
2607 mView.dispatchUnhandledMove(focused, direction);
2608 } else {
2609 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2610 }
2611 }
2612 }
2613 }
2614 }
2615
2616 } finally {
2617 if (sendDone) {
2618 if (LOCAL_LOGV) Log.v(
2619 "ViewRoot", "Telling window manager key is finished");
2620 try {
2621 sWindowSession.finishKey(mWindow);
2622 } catch (RemoteException e) {
2623 }
2624 }
2625 // Let the exception fall through -- the looper will catch
2626 // it and take care of the bad app for us.
2627 }
2628 }
2629
2630 private AudioManager getAudioManager() {
2631 if (mView == null) {
2632 throw new IllegalStateException("getAudioManager called when there is no mView");
2633 }
2634 if (mAudioManager == null) {
2635 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2636 }
2637 return mAudioManager;
2638 }
2639
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002640 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2641 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002642
2643 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002644 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002645 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002646 restore = true;
2647 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002648 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002649 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002650 if (params != null) {
2651 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002652 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002653 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002654 int relayoutResult = sWindowSession.relayout(
2655 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002656 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2657 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002658 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002659 mPendingContentInsets, mPendingVisibleInsets,
2660 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002661 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002662 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002663 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002664
2665 if (mTranslator != null) {
2666 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2667 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2668 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002669 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002670 return relayoutResult;
2671 }
Romain Guy8506ab42009-06-11 17:35:47 -07002672
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002673 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 * {@inheritDoc}
2675 */
2676 public void playSoundEffect(int effectId) {
2677 checkThread();
2678
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002679 try {
2680 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002682 switch (effectId) {
2683 case SoundEffectConstants.CLICK:
2684 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2685 return;
2686 case SoundEffectConstants.NAVIGATION_DOWN:
2687 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2688 return;
2689 case SoundEffectConstants.NAVIGATION_LEFT:
2690 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2691 return;
2692 case SoundEffectConstants.NAVIGATION_RIGHT:
2693 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2694 return;
2695 case SoundEffectConstants.NAVIGATION_UP:
2696 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2697 return;
2698 default:
2699 throw new IllegalArgumentException("unknown effect id " + effectId +
2700 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2701 }
2702 } catch (IllegalStateException e) {
2703 // Exception thrown by getAudioManager() when mView is null
2704 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2705 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
2707 }
2708
2709 /**
2710 * {@inheritDoc}
2711 */
2712 public boolean performHapticFeedback(int effectId, boolean always) {
2713 try {
2714 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2715 } catch (RemoteException e) {
2716 return false;
2717 }
2718 }
2719
2720 /**
2721 * {@inheritDoc}
2722 */
2723 public View focusSearch(View focused, int direction) {
2724 checkThread();
2725 if (!(mView instanceof ViewGroup)) {
2726 return null;
2727 }
2728 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2729 }
2730
2731 public void debug() {
2732 mView.debug();
2733 }
2734
2735 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002736 if (immediate) {
2737 doDie();
2738 } else {
2739 sendEmptyMessage(DIE);
2740 }
2741 }
2742
2743 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 checkThread();
2745 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2746 synchronized (this) {
2747 if (mAdded && !mFirst) {
2748 int viewVisibility = mView.getVisibility();
2749 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2750 if (mWindowAttributesChanged || viewVisibilityChanged) {
2751 // If layout params have been changed, first give them
2752 // to the window manager to make sure it has the correct
2753 // animation info.
2754 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002755 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2756 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 sWindowSession.finishDrawing(mWindow);
2758 }
2759 } catch (RemoteException e) {
2760 }
2761 }
2762
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002763 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 }
2765 if (mAdded) {
2766 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002767 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 }
2769 }
2770 }
2771
2772 public void dispatchFinishedEvent(int seq, boolean handled) {
2773 Message msg = obtainMessage(FINISHED_EVENT);
2774 msg.arg1 = seq;
2775 msg.arg2 = handled ? 1 : 0;
2776 sendMessage(msg);
2777 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002780 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2782 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2783 + " visibleInsets=" + visibleInsets.toShortString()
2784 + " reportDraw=" + reportDraw);
2785 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002786 if (mTranslator != null) {
2787 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2788 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2789 w *= mTranslator.applicationInvertedScale;
2790 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002791 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002792 msg.arg1 = w;
2793 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002794 ResizedInfo ri = new ResizedInfo();
2795 ri.coveredInsets = new Rect(coveredInsets);
2796 ri.visibleInsets = new Rect(visibleInsets);
2797 ri.newConfig = newConfig;
2798 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 sendMessage(msg);
2800 }
2801
2802 public void dispatchKey(KeyEvent event) {
2803 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2804 //noinspection ConstantConditions
2805 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2806 if (Config.LOGD) Log.d("keydisp",
2807 "===================================================");
2808 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2809 debug();
2810
2811 if (Config.LOGD) Log.d("keydisp",
2812 "===================================================");
2813 }
2814 }
2815
2816 Message msg = obtainMessage(DISPATCH_KEY);
2817 msg.obj = event;
2818
2819 if (LOCAL_LOGV) Log.v(
2820 "ViewRoot", "sending key " + event + " to " + mView);
2821
2822 sendMessageAtTime(msg, event.getEventTime());
2823 }
2824
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002825 public void dispatchPointer(MotionEvent event, long eventTime,
2826 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 Message msg = obtainMessage(DISPATCH_POINTER);
2828 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002829 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 sendMessageAtTime(msg, eventTime);
2831 }
2832
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002833 public void dispatchTrackball(MotionEvent event, long eventTime,
2834 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2836 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002837 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 sendMessageAtTime(msg, eventTime);
2839 }
2840
2841 public void dispatchAppVisibility(boolean visible) {
2842 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2843 msg.arg1 = visible ? 1 : 0;
2844 sendMessage(msg);
2845 }
2846
2847 public void dispatchGetNewSurface() {
2848 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2849 sendMessage(msg);
2850 }
2851
2852 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2853 Message msg = Message.obtain();
2854 msg.what = WINDOW_FOCUS_CHANGED;
2855 msg.arg1 = hasFocus ? 1 : 0;
2856 msg.arg2 = inTouchMode ? 1 : 0;
2857 sendMessage(msg);
2858 }
2859
Dianne Hackbornffa42482009-09-23 22:20:11 -07002860 public void dispatchCloseSystemDialogs(String reason) {
2861 Message msg = Message.obtain();
2862 msg.what = CLOSE_SYSTEM_DIALOGS;
2863 msg.obj = reason;
2864 sendMessage(msg);
2865 }
2866
svetoslavganov75986cf2009-05-14 22:28:01 -07002867 /**
2868 * The window is getting focus so if there is anything focused/selected
2869 * send an {@link AccessibilityEvent} to announce that.
2870 */
2871 private void sendAccessibilityEvents() {
2872 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2873 return;
2874 }
2875 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2876 View focusedView = mView.findFocus();
2877 if (focusedView != null && focusedView != mView) {
2878 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2879 }
2880 }
2881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 public boolean showContextMenuForChild(View originalView) {
2883 return false;
2884 }
2885
2886 public void createContextMenu(ContextMenu menu) {
2887 }
2888
2889 public void childDrawableStateChanged(View child) {
2890 }
2891
2892 protected Rect getWindowFrame() {
2893 return mWinFrame;
2894 }
2895
2896 void checkThread() {
2897 if (mThread != Thread.currentThread()) {
2898 throw new CalledFromWrongThreadException(
2899 "Only the original thread that created a view hierarchy can touch its views.");
2900 }
2901 }
2902
2903 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2904 // ViewRoot never intercepts touch event, so this can be a no-op
2905 }
2906
2907 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2908 boolean immediate) {
2909 return scrollToRectOrFocus(rectangle, immediate);
2910 }
Romain Guy8506ab42009-06-11 17:35:47 -07002911
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002912 class TakenSurfaceHolder extends BaseSurfaceHolder {
2913 @Override
2914 public boolean onAllowLockCanvas() {
2915 return mDrawingAllowed;
2916 }
2917
2918 @Override
2919 public void onRelayoutContainer() {
2920 // Not currently interesting -- from changing between fixed and layout size.
2921 }
2922
2923 public void setFormat(int format) {
2924 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2925 }
2926
2927 public void setType(int type) {
2928 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2929 }
2930
2931 @Override
2932 public void onUpdateSurface() {
2933 // We take care of format and type changes on our own.
2934 throw new IllegalStateException("Shouldn't be here");
2935 }
2936
2937 public boolean isCreating() {
2938 return mIsCreating;
2939 }
2940
2941 @Override
2942 public void setFixedSize(int width, int height) {
2943 throw new UnsupportedOperationException(
2944 "Currently only support sizing from layout");
2945 }
2946
2947 public void setKeepScreenOn(boolean screenOn) {
2948 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2949 }
2950 }
2951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 static class InputMethodCallback extends IInputMethodCallback.Stub {
2953 private WeakReference<ViewRoot> mViewRoot;
2954
2955 public InputMethodCallback(ViewRoot viewRoot) {
2956 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2957 }
Romain Guy8506ab42009-06-11 17:35:47 -07002958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 public void finishedEvent(int seq, boolean handled) {
2960 final ViewRoot viewRoot = mViewRoot.get();
2961 if (viewRoot != null) {
2962 viewRoot.dispatchFinishedEvent(seq, handled);
2963 }
2964 }
2965
2966 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2967 // Stub -- not for use in the client.
2968 }
2969 }
Romain Guy8506ab42009-06-11 17:35:47 -07002970
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002971 static class EventCompletion extends Handler {
2972 final IWindow mWindow;
2973 final KeyEvent mKeyEvent;
2974 final boolean mIsPointer;
2975 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002976
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002977 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2978 boolean isPointer, MotionEvent motion) {
2979 super(looper);
2980 mWindow = window;
2981 mKeyEvent = key;
2982 mIsPointer = isPointer;
2983 mMotionEvent = motion;
2984 sendEmptyMessage(0);
2985 }
Romain Guy8506ab42009-06-11 17:35:47 -07002986
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002987 @Override
2988 public void handleMessage(Message msg) {
2989 if (mKeyEvent != null) {
2990 try {
2991 sWindowSession.finishKey(mWindow);
2992 } catch (RemoteException e) {
2993 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002994 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002995 boolean didFinish;
2996 MotionEvent event = mMotionEvent;
2997 if (event == null) {
2998 try {
2999 event = sWindowSession.getPendingPointerMove(mWindow);
3000 } catch (RemoteException e) {
3001 }
3002 didFinish = true;
3003 } else {
3004 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
3005 }
3006 if (!didFinish) {
3007 try {
3008 sWindowSession.finishKey(mWindow);
3009 } catch (RemoteException e) {
3010 }
3011 }
3012 } else {
3013 MotionEvent event = mMotionEvent;
3014 if (event == null) {
3015 try {
3016 event = sWindowSession.getPendingTrackballMove(mWindow);
3017 } catch (RemoteException e) {
3018 }
3019 } else {
3020 try {
3021 sWindowSession.finishKey(mWindow);
3022 } catch (RemoteException e) {
3023 }
3024 }
3025 }
3026 }
3027 }
Romain Guy8506ab42009-06-11 17:35:47 -07003028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003030 private final WeakReference<ViewRoot> mViewRoot;
3031 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003033 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003035 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 }
3037
3038 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003039 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 final ViewRoot viewRoot = mViewRoot.get();
3041 if (viewRoot != null) {
3042 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003043 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 }
3045 }
3046
3047 public void dispatchKey(KeyEvent event) {
3048 final ViewRoot viewRoot = mViewRoot.get();
3049 if (viewRoot != null) {
3050 viewRoot.dispatchKey(event);
3051 } else {
3052 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003053 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 }
3055 }
3056
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003057 public void dispatchPointer(MotionEvent event, long eventTime,
3058 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07003060 if (viewRoot != null) {
3061 if (MEASURE_LATENCY) {
3062 // Note: eventTime is in milliseconds
3063 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
3064 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003065 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003066 } else {
3067 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 }
3069 }
3070
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003071 public void dispatchTrackball(MotionEvent event, long eventTime,
3072 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 final ViewRoot viewRoot = mViewRoot.get();
3074 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07003075 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003076 } else {
3077 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 }
3079 }
3080
3081 public void dispatchAppVisibility(boolean visible) {
3082 final ViewRoot viewRoot = mViewRoot.get();
3083 if (viewRoot != null) {
3084 viewRoot.dispatchAppVisibility(visible);
3085 }
3086 }
3087
3088 public void dispatchGetNewSurface() {
3089 final ViewRoot viewRoot = mViewRoot.get();
3090 if (viewRoot != null) {
3091 viewRoot.dispatchGetNewSurface();
3092 }
3093 }
3094
3095 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3096 final ViewRoot viewRoot = mViewRoot.get();
3097 if (viewRoot != null) {
3098 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3099 }
3100 }
3101
3102 private static int checkCallingPermission(String permission) {
3103 if (!Process.supportsProcesses()) {
3104 return PackageManager.PERMISSION_GRANTED;
3105 }
3106
3107 try {
3108 return ActivityManagerNative.getDefault().checkPermission(
3109 permission, Binder.getCallingPid(), Binder.getCallingUid());
3110 } catch (RemoteException e) {
3111 return PackageManager.PERMISSION_DENIED;
3112 }
3113 }
3114
3115 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3116 final ViewRoot viewRoot = mViewRoot.get();
3117 if (viewRoot != null) {
3118 final View view = viewRoot.mView;
3119 if (view != null) {
3120 if (checkCallingPermission(Manifest.permission.DUMP) !=
3121 PackageManager.PERMISSION_GRANTED) {
3122 throw new SecurityException("Insufficient permissions to invoke"
3123 + " executeCommand() from pid=" + Binder.getCallingPid()
3124 + ", uid=" + Binder.getCallingUid());
3125 }
3126
3127 OutputStream clientStream = null;
3128 try {
3129 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3130 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3131 } catch (IOException e) {
3132 e.printStackTrace();
3133 } finally {
3134 if (clientStream != null) {
3135 try {
3136 clientStream.close();
3137 } catch (IOException e) {
3138 e.printStackTrace();
3139 }
3140 }
3141 }
3142 }
3143 }
3144 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003145
Dianne Hackbornffa42482009-09-23 22:20:11 -07003146 public void closeSystemDialogs(String reason) {
3147 final ViewRoot viewRoot = mViewRoot.get();
3148 if (viewRoot != null) {
3149 viewRoot.dispatchCloseSystemDialogs(reason);
3150 }
3151 }
3152
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003153 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3154 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003155 if (sync) {
3156 try {
3157 sWindowSession.wallpaperOffsetsComplete(asBinder());
3158 } catch (RemoteException e) {
3159 }
3160 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003161 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003162
3163 public void dispatchWallpaperCommand(String action, int x, int y,
3164 int z, Bundle extras, boolean sync) {
3165 if (sync) {
3166 try {
3167 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3168 } catch (RemoteException e) {
3169 }
3170 }
3171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 }
3173
3174 /**
3175 * Maintains state information for a single trackball axis, generating
3176 * discrete (DPAD) movements based on raw trackball motion.
3177 */
3178 static final class TrackballAxis {
3179 /**
3180 * The maximum amount of acceleration we will apply.
3181 */
3182 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 /**
3185 * The maximum amount of time (in milliseconds) between events in order
3186 * for us to consider the user to be doing fast trackball movements,
3187 * and thus apply an acceleration.
3188 */
3189 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 /**
3192 * Scaling factor to the time (in milliseconds) between events to how
3193 * much to multiple/divide the current acceleration. When movement
3194 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3195 * FAST_MOVE_TIME it divides it.
3196 */
3197 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 float position;
3200 float absPosition;
3201 float acceleration = 1;
3202 long lastMoveTime = 0;
3203 int step;
3204 int dir;
3205 int nonAccelMovement;
3206
3207 void reset(int _step) {
3208 position = 0;
3209 acceleration = 1;
3210 lastMoveTime = 0;
3211 step = _step;
3212 dir = 0;
3213 }
3214
3215 /**
3216 * Add trackball movement into the state. If the direction of movement
3217 * has been reversed, the state is reset before adding the
3218 * movement (so that you don't have to compensate for any previously
3219 * collected movement before see the result of the movement in the
3220 * new direction).
3221 *
3222 * @return Returns the absolute value of the amount of movement
3223 * collected so far.
3224 */
3225 float collect(float off, long time, String axis) {
3226 long normTime;
3227 if (off > 0) {
3228 normTime = (long)(off * FAST_MOVE_TIME);
3229 if (dir < 0) {
3230 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3231 position = 0;
3232 step = 0;
3233 acceleration = 1;
3234 lastMoveTime = 0;
3235 }
3236 dir = 1;
3237 } else if (off < 0) {
3238 normTime = (long)((-off) * FAST_MOVE_TIME);
3239 if (dir > 0) {
3240 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3241 position = 0;
3242 step = 0;
3243 acceleration = 1;
3244 lastMoveTime = 0;
3245 }
3246 dir = -1;
3247 } else {
3248 normTime = 0;
3249 }
Romain Guy8506ab42009-06-11 17:35:47 -07003250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 // The number of milliseconds between each movement that is
3252 // considered "normal" and will not result in any acceleration
3253 // or deceleration, scaled by the offset we have here.
3254 if (normTime > 0) {
3255 long delta = time - lastMoveTime;
3256 lastMoveTime = time;
3257 float acc = acceleration;
3258 if (delta < normTime) {
3259 // The user is scrolling rapidly, so increase acceleration.
3260 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3261 if (scale > 1) acc *= scale;
3262 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3263 + off + " normTime=" + normTime + " delta=" + delta
3264 + " scale=" + scale + " acc=" + acc);
3265 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3266 } else {
3267 // The user is scrolling slowly, so decrease acceleration.
3268 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3269 if (scale > 1) acc /= scale;
3270 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3271 + off + " normTime=" + normTime + " delta=" + delta
3272 + " scale=" + scale + " acc=" + acc);
3273 acceleration = acc > 1 ? acc : 1;
3274 }
3275 }
3276 position += off;
3277 return (absPosition = Math.abs(position));
3278 }
3279
3280 /**
3281 * Generate the number of discrete movement events appropriate for
3282 * the currently collected trackball movement.
3283 *
3284 * @param precision The minimum movement required to generate the
3285 * first discrete movement.
3286 *
3287 * @return Returns the number of discrete movements, either positive
3288 * or negative, or 0 if there is not enough trackball movement yet
3289 * for a discrete movement.
3290 */
3291 int generate(float precision) {
3292 int movement = 0;
3293 nonAccelMovement = 0;
3294 do {
3295 final int dir = position >= 0 ? 1 : -1;
3296 switch (step) {
3297 // If we are going to execute the first step, then we want
3298 // to do this as soon as possible instead of waiting for
3299 // a full movement, in order to make things look responsive.
3300 case 0:
3301 if (absPosition < precision) {
3302 return movement;
3303 }
3304 movement += dir;
3305 nonAccelMovement += dir;
3306 step = 1;
3307 break;
3308 // If we have generated the first movement, then we need
3309 // to wait for the second complete trackball motion before
3310 // generating the second discrete movement.
3311 case 1:
3312 if (absPosition < 2) {
3313 return movement;
3314 }
3315 movement += dir;
3316 nonAccelMovement += dir;
3317 position += dir > 0 ? -2 : 2;
3318 absPosition = Math.abs(position);
3319 step = 2;
3320 break;
3321 // After the first two, we generate discrete movements
3322 // consistently with the trackball, applying an acceleration
3323 // if the trackball is moving quickly. This is a simple
3324 // acceleration on top of what we already compute based
3325 // on how quickly the wheel is being turned, to apply
3326 // a longer increasing acceleration to continuous movement
3327 // in one direction.
3328 default:
3329 if (absPosition < 1) {
3330 return movement;
3331 }
3332 movement += dir;
3333 position += dir >= 0 ? -1 : 1;
3334 absPosition = Math.abs(position);
3335 float acc = acceleration;
3336 acc *= 1.1f;
3337 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3338 break;
3339 }
3340 } while (true);
3341 }
3342 }
3343
3344 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3345 public CalledFromWrongThreadException(String msg) {
3346 super(msg);
3347 }
3348 }
3349
3350 private SurfaceHolder mHolder = new SurfaceHolder() {
3351 // we only need a SurfaceHolder for opengl. it would be nice
3352 // to implement everything else though, especially the callback
3353 // support (opengl doesn't make use of it right now, but eventually
3354 // will).
3355 public Surface getSurface() {
3356 return mSurface;
3357 }
3358
3359 public boolean isCreating() {
3360 return false;
3361 }
3362
3363 public void addCallback(Callback callback) {
3364 }
3365
3366 public void removeCallback(Callback callback) {
3367 }
3368
3369 public void setFixedSize(int width, int height) {
3370 }
3371
3372 public void setSizeFromLayout() {
3373 }
3374
3375 public void setFormat(int format) {
3376 }
3377
3378 public void setType(int type) {
3379 }
3380
3381 public void setKeepScreenOn(boolean screenOn) {
3382 }
3383
3384 public Canvas lockCanvas() {
3385 return null;
3386 }
3387
3388 public Canvas lockCanvas(Rect dirty) {
3389 return null;
3390 }
3391
3392 public void unlockCanvasAndPost(Canvas canvas) {
3393 }
3394 public Rect getSurfaceFrame() {
3395 return null;
3396 }
3397 };
3398
3399 static RunQueue getRunQueue() {
3400 RunQueue rq = sRunQueues.get();
3401 if (rq != null) {
3402 return rq;
3403 }
3404 rq = new RunQueue();
3405 sRunQueues.set(rq);
3406 return rq;
3407 }
Romain Guy8506ab42009-06-11 17:35:47 -07003408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 /**
3410 * @hide
3411 */
3412 static final class RunQueue {
3413 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3414
3415 void post(Runnable action) {
3416 postDelayed(action, 0);
3417 }
3418
3419 void postDelayed(Runnable action, long delayMillis) {
3420 HandlerAction handlerAction = new HandlerAction();
3421 handlerAction.action = action;
3422 handlerAction.delay = delayMillis;
3423
3424 synchronized (mActions) {
3425 mActions.add(handlerAction);
3426 }
3427 }
3428
3429 void removeCallbacks(Runnable action) {
3430 final HandlerAction handlerAction = new HandlerAction();
3431 handlerAction.action = action;
3432
3433 synchronized (mActions) {
3434 final ArrayList<HandlerAction> actions = mActions;
3435
3436 while (actions.remove(handlerAction)) {
3437 // Keep going
3438 }
3439 }
3440 }
3441
3442 void executeActions(Handler handler) {
3443 synchronized (mActions) {
3444 final ArrayList<HandlerAction> actions = mActions;
3445 final int count = actions.size();
3446
3447 for (int i = 0; i < count; i++) {
3448 final HandlerAction handlerAction = actions.get(i);
3449 handler.postDelayed(handlerAction.action, handlerAction.delay);
3450 }
3451
Romain Guy15df6702009-08-17 20:17:30 -07003452 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 }
3454 }
3455
3456 private static class HandlerAction {
3457 Runnable action;
3458 long delay;
3459
3460 @Override
3461 public boolean equals(Object o) {
3462 if (this == o) return true;
3463 if (o == null || getClass() != o.getClass()) return false;
3464
3465 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 return !(action != null ? !action.equals(that.action) : that.action != null);
3467
3468 }
3469
3470 @Override
3471 public int hashCode() {
3472 int result = action != null ? action.hashCode() : 0;
3473 result = 31 * result + (int) (delay ^ (delay >>> 32));
3474 return result;
3475 }
3476 }
3477 }
3478
3479 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3480
3481 // inform skia to just abandon its texture cache IDs
3482 // doesn't call glDeleteTextures
3483 private static native void nativeAbandonGlCaches();
3484}