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