blob: ed83bca73933b08b08e3deb53f2480e0e58356db [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
19import com.android.internal.view.IInputMethodCallback;
20import com.android.internal.view.IInputMethodSession;
21
22import android.graphics.Canvas;
23import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.graphics.PorterDuff;
25import android.graphics.Rect;
26import android.graphics.Region;
27import android.os.*;
28import android.os.Process;
29import android.os.SystemProperties;
30import android.util.AndroidRuntimeException;
31import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070032import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.util.Log;
34import android.util.EventLog;
35import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070037import android.view.accessibility.AccessibilityEvent;
38import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.view.inputmethod.InputConnection;
40import android.view.inputmethod.InputMethodManager;
41import android.widget.Scroller;
42import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070043import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080044import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070045import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080046import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.Context;
48import android.app.ActivityManagerNative;
49import android.Manifest;
50import android.media.AudioManager;
51
52import java.lang.ref.WeakReference;
53import java.io.IOException;
54import java.io.OutputStream;
55import java.util.ArrayList;
56
57import javax.microedition.khronos.egl.*;
58import javax.microedition.khronos.opengles.*;
59import static javax.microedition.khronos.opengles.GL10.*;
60
61/**
62 * The top of a view hierarchy, implementing the needed protocol between View
63 * and the WindowManager. This is for the most part an internal implementation
64 * detail of {@link WindowManagerImpl}.
65 *
66 * {@hide}
67 */
68@SuppressWarnings({"EmptyCatchBlock"})
69public final class ViewRoot extends Handler implements ViewParent,
70 View.AttachInfo.Callbacks {
71 private static final String TAG = "ViewRoot";
72 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040073 private static final boolean SHOW_FPS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 @SuppressWarnings({"ConstantConditionalExpression"})
75 private static final boolean LOCAL_LOGV = false ? Config.LOGD : Config.LOGV;
76 /** @noinspection PointlessBooleanExpression*/
77 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
78 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
79 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
80 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
81 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
82 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070083 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 private static final boolean WATCH_POINTER = false;
85
Michael Chan53071d62009-05-13 17:29:48 -070086 private static final boolean MEASURE_LATENCY = false;
87 private static LatencyTimer lt;
88
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 /**
90 * Maximum time we allow the user to roll the trackball enough to generate
91 * a key event, before resetting the counters.
92 */
93 static final int MAX_TRACKBALL_DELAY = 250;
94
95 static long sInstanceCount = 0;
96
97 static IWindowSession sWindowSession;
98
99 static final Object mStaticInit = new Object();
100 static boolean mInitialized = false;
101
102 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
103
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800104 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
105 static boolean sFirstDrawComplete = false;
106
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800107 static final ArrayList<ComponentCallbacks> sConfigCallbacks
108 = new ArrayList<ComponentCallbacks>();
109
Romain Guy8506ab42009-06-11 17:35:47 -0700110 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 long mLastTrackballTime = 0;
113 final TrackballAxis mTrackballAxisX = new TrackballAxis();
114 final TrackballAxis mTrackballAxisY = new TrackballAxis();
115
116 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 final InputMethodCallback mInputMethodCallback;
119 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
120 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 final Thread mThread;
123
124 final WindowLeaked mLocation;
125
126 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
127
128 final W mWindow;
129
130 View mView;
131 View mFocusedView;
132 View mRealFocusedView; // this is not set to null in touch mode
133 int mViewVisibility;
134 boolean mAppVisible = true;
135
136 final Region mTransparentRegion;
137 final Region mPreviousTransparentRegion;
138
139 int mWidth;
140 int mHeight;
141 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700142 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700143
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700144 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 final View.AttachInfo mAttachInfo;
147
148 final Rect mTempRect; // used in the transaction to not thrash the heap.
149 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
151 boolean mTraversalScheduled;
152 boolean mWillDrawSoon;
153 boolean mLayoutRequested;
154 boolean mFirst;
155 boolean mReportNextDraw;
156 boolean mFullRedrawNeeded;
157 boolean mNewSurfaceNeeded;
158 boolean mHasHadWindowFocus;
159 boolean mLastWasImTarget;
160
161 boolean mWindowAttributesChanged = false;
162
163 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700164 // Surface can never be reassigned or cleared (use Surface.clear()).
165 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
167 boolean mAdded;
168 boolean mAddedTouchMode;
169
170 /*package*/ int mAddNesting;
171
172 // These are accessed by multiple threads.
173 final Rect mWinFrame; // frame given by window manager.
174
175 final Rect mPendingVisibleInsets = new Rect();
176 final Rect mPendingContentInsets = new Rect();
177 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
178 = new ViewTreeObserver.InternalInsetsInfo();
179
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700180 final Configuration mLastConfiguration = new Configuration();
181 final Configuration mPendingConfiguration = new Configuration();
182
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800183 class ResizedInfo {
184 Rect coveredInsets;
185 Rect visibleInsets;
186 Configuration newConfig;
187 }
188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 boolean mScrollMayChange;
190 int mSoftInputMode;
191 View mLastScrolledFocus;
192 int mScrollY;
193 int mCurScrollY;
194 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 EGL10 mEgl;
197 EGLDisplay mEglDisplay;
198 EGLContext mEglContext;
199 EGLSurface mEglSurface;
200 GL11 mGL;
201 Canvas mGlCanvas;
202 boolean mUseGL;
203 boolean mGlWanted;
204
Romain Guy8506ab42009-06-11 17:35:47 -0700205 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
207 /**
208 * see {@link #playSoundEffect(int)}
209 */
210 AudioManager mAudioManager;
211
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700212 private final int mDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700214 public static IWindowSession getWindowSession(Looper mainLooper) {
215 synchronized (mStaticInit) {
216 if (!mInitialized) {
217 try {
218 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
219 sWindowSession = IWindowManager.Stub.asInterface(
220 ServiceManager.getService("window"))
221 .openSession(imm.getClient(), imm.getInputContext());
222 mInitialized = true;
223 } catch (RemoteException e) {
224 }
225 }
226 return sWindowSession;
227 }
228 }
229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 public ViewRoot(Context context) {
231 super();
232
Michael Chan53071d62009-05-13 17:29:48 -0700233 if (MEASURE_LATENCY && lt == null) {
234 lt = new LatencyTimer(100, 1000);
235 }
236
Carl Shapiro82fe5642010-02-24 00:14:23 -0800237 // For debug only
238 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Initialize the statics when this class is first instantiated. This is
241 // done here instead of in the static block because Zygote does not
242 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700243 getWindowSession(context.getMainLooper());
244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 mThread = Thread.currentThread();
246 mLocation = new WindowLeaked(null);
247 mLocation.fillInStackTrace();
248 mWidth = -1;
249 mHeight = -1;
250 mDirty = new Rect();
251 mTempRect = new Rect();
252 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700254 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 mInputMethodCallback = new InputMethodCallback(this);
256 mViewVisibility = View.GONE;
257 mTransparentRegion = new Region();
258 mPreviousTransparentRegion = new Region();
259 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 mAdded = false;
261 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
262 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700263 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 }
265
Carl Shapiro82fe5642010-02-24 00:14:23 -0800266 // For debug only
267 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 @Override
269 protected void finalize() throws Throwable {
270 super.finalize();
271 --sInstanceCount;
272 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800273 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 public static long getInstanceCount() {
276 return sInstanceCount;
277 }
278
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800279 public static void addFirstDrawHandler(Runnable callback) {
280 synchronized (sFirstDrawHandlers) {
281 if (!sFirstDrawComplete) {
282 sFirstDrawHandlers.add(callback);
283 }
284 }
285 }
286
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800287 public static void addConfigCallback(ComponentCallbacks callback) {
288 synchronized (sConfigCallbacks) {
289 sConfigCallbacks.add(callback);
290 }
291 }
292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 // FIXME for perf testing only
294 private boolean mProfile = false;
295
296 /**
297 * Call this to profile the next traversal call.
298 * FIXME for perf testing only. Remove eventually
299 */
300 public void profile() {
301 mProfile = true;
302 }
303
304 /**
305 * Indicates whether we are in touch mode. Calling this method triggers an IPC
306 * call and should be avoided whenever possible.
307 *
308 * @return True, if the device is in touch mode, false otherwise.
309 *
310 * @hide
311 */
312 static boolean isInTouchMode() {
313 if (mInitialized) {
314 try {
315 return sWindowSession.getInTouchMode();
316 } catch (RemoteException e) {
317 }
318 }
319 return false;
320 }
321
322 private void initializeGL() {
323 initializeGLInner();
324 int err = mEgl.eglGetError();
325 if (err != EGL10.EGL_SUCCESS) {
326 // give-up on using GL
327 destroyGL();
328 mGlWanted = false;
329 }
330 }
331
332 private void initializeGLInner() {
333 final EGL10 egl = (EGL10) EGLContext.getEGL();
334 mEgl = egl;
335
336 /*
337 * Get to the default display.
338 */
339 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
340 mEglDisplay = eglDisplay;
341
342 /*
343 * We can now initialize EGL for that display
344 */
345 int[] version = new int[2];
346 egl.eglInitialize(eglDisplay, version);
347
348 /*
349 * Specify a configuration for our opengl session
350 * and grab the first configuration that matches is
351 */
352 final int[] configSpec = {
353 EGL10.EGL_RED_SIZE, 5,
354 EGL10.EGL_GREEN_SIZE, 6,
355 EGL10.EGL_BLUE_SIZE, 5,
356 EGL10.EGL_DEPTH_SIZE, 0,
357 EGL10.EGL_NONE
358 };
359 final EGLConfig[] configs = new EGLConfig[1];
360 final int[] num_config = new int[1];
361 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, num_config);
362 final EGLConfig config = configs[0];
363
364 /*
365 * Create an OpenGL ES context. This must be done only once, an
366 * OpenGL context is a somewhat heavy object.
367 */
368 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
369 EGL10.EGL_NO_CONTEXT, null);
370 mEglContext = context;
371
372 /*
373 * Create an EGL surface we can render into.
374 */
375 final EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
376 mEglSurface = surface;
377
378 /*
379 * Before we can issue GL commands, we need to make sure
380 * the context is current and bound to a surface.
381 */
382 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
383
384 /*
385 * Get to the appropriate GL interface.
386 * This is simply done by casting the GL context to either
387 * GL10 or GL11.
388 */
389 final GL11 gl = (GL11) context.getGL();
390 mGL = gl;
391 mGlCanvas = new Canvas(gl);
392 mUseGL = true;
393 }
394
395 private void destroyGL() {
396 // inform skia that the context is gone
397 nativeAbandonGlCaches();
398
399 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
400 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
401 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
402 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
403 mEgl.eglTerminate(mEglDisplay);
404 mEglContext = null;
405 mEglSurface = null;
406 mEglDisplay = null;
407 mEgl = null;
408 mGlCanvas = null;
409 mGL = null;
410 mUseGL = false;
411 }
412
413 private void checkEglErrors() {
414 if (mUseGL) {
415 int err = mEgl.eglGetError();
416 if (err != EGL10.EGL_SUCCESS) {
417 // something bad has happened revert to
418 // normal rendering.
419 destroyGL();
420 if (err != EGL11.EGL_CONTEXT_LOST) {
421 // we'll try again if it was context lost
422 mGlWanted = false;
423 }
424 }
425 }
426 }
427
428 /**
429 * We have one child
430 */
431 public void setView(View view, WindowManager.LayoutParams attrs,
432 View panelParentView) {
433 synchronized (this) {
434 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700435 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700436 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700437 attrs = mWindowAttributes;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700438 Resources resources = mView.getContext().getResources();
439 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700440 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700441
442 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700443 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
444 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700445 }
446
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700447 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700448 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700449 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700450 attrs.backup();
451 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700452 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700453 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
454
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700455 if (!compatibilityInfo.supportsScreen()) {
456 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
457 }
458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 mSoftInputMode = attrs.softInputMode;
460 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700462 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700463 mAttachInfo.mApplicationScale =
464 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 if (panelParentView != null) {
466 mAttachInfo.mPanelParentWindowToken
467 = panelParentView.getApplicationWindowToken();
468 }
469 mAdded = true;
470 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 // Schedule the first layout -before- adding to the window
473 // manager, to make sure we do the relayout before receiving
474 // any other events from the system.
475 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700477 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 getHostVisibility(), mAttachInfo.mContentInsets);
479 } catch (RemoteException e) {
480 mAdded = false;
481 mView = null;
482 mAttachInfo.mRootView = null;
483 unscheduleTraversals();
484 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700485 } finally {
486 if (restore) {
487 attrs.restore();
488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700490
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700491 if (mTranslator != null) {
492 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 mPendingContentInsets.set(mAttachInfo.mContentInsets);
495 mPendingVisibleInsets.set(0, 0, 0, 0);
496 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
497 if (res < WindowManagerImpl.ADD_OKAY) {
498 mView = null;
499 mAttachInfo.mRootView = null;
500 mAdded = false;
501 unscheduleTraversals();
502 switch (res) {
503 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
504 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
505 throw new WindowManagerImpl.BadTokenException(
506 "Unable to add window -- token " + attrs.token
507 + " is not valid; is your activity running?");
508 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
509 throw new WindowManagerImpl.BadTokenException(
510 "Unable to add window -- token " + attrs.token
511 + " is not for an application");
512 case WindowManagerImpl.ADD_APP_EXITING:
513 throw new WindowManagerImpl.BadTokenException(
514 "Unable to add window -- app for token " + attrs.token
515 + " is exiting");
516 case WindowManagerImpl.ADD_DUPLICATE_ADD:
517 throw new WindowManagerImpl.BadTokenException(
518 "Unable to add window -- window " + mWindow
519 + " has already been added");
520 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
521 // Silently ignore -- we would have just removed it
522 // right away, anyway.
523 return;
524 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
525 throw new WindowManagerImpl.BadTokenException(
526 "Unable to add window " + mWindow +
527 " -- another window of this type already exists");
528 case WindowManagerImpl.ADD_PERMISSION_DENIED:
529 throw new WindowManagerImpl.BadTokenException(
530 "Unable to add window " + mWindow +
531 " -- permission denied for this window type");
532 }
533 throw new RuntimeException(
534 "Unable to add window -- unknown error code " + res);
535 }
536 view.assignParent(this);
537 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
538 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
539 }
540 }
541 }
542
543 public View getView() {
544 return mView;
545 }
546
547 final WindowLeaked getLocation() {
548 return mLocation;
549 }
550
551 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
552 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700553 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700554 // preserve compatible window flag if exists.
555 int compatibleWindowFlag =
556 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700558 mWindowAttributes.flags |= compatibleWindowFlag;
559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 if (newView) {
561 mSoftInputMode = attrs.softInputMode;
562 requestLayout();
563 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700564 // Don't lose the mode we last auto-computed.
565 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
566 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
567 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
568 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
569 | (oldSoftInputMode
570 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 mWindowAttributesChanged = true;
573 scheduleTraversals();
574 }
575 }
576
577 void handleAppVisibility(boolean visible) {
578 if (mAppVisible != visible) {
579 mAppVisible = visible;
580 scheduleTraversals();
581 }
582 }
583
584 void handleGetNewSurface() {
585 mNewSurfaceNeeded = true;
586 mFullRedrawNeeded = true;
587 scheduleTraversals();
588 }
589
590 /**
591 * {@inheritDoc}
592 */
593 public void requestLayout() {
594 checkThread();
595 mLayoutRequested = true;
596 scheduleTraversals();
597 }
598
599 /**
600 * {@inheritDoc}
601 */
602 public boolean isLayoutRequested() {
603 return mLayoutRequested;
604 }
605
606 public void invalidateChild(View child, Rect dirty) {
607 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700608 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
609 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700611 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700612 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700613 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700614 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700615 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700616 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700617 }
Romain Guy1e095972009-07-07 11:22:45 -0700618 if (mAttachInfo.mScalingRequired) {
619 dirty.inset(-1, -1);
620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 }
622 mDirty.union(dirty);
623 if (!mWillDrawSoon) {
624 scheduleTraversals();
625 }
626 }
627
628 public ViewParent getParent() {
629 return null;
630 }
631
632 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
633 invalidateChild(null, dirty);
634 return null;
635 }
636
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700637 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 if (child != mView) {
639 throw new RuntimeException("child is not mine, honest!");
640 }
641 // Note: don't apply scroll offset, because we want to know its
642 // visibility in the virtual canvas being given to the view hierarchy.
643 return r.intersect(0, 0, mWidth, mHeight);
644 }
645
646 public void bringChildToFront(View child) {
647 }
648
649 public void scheduleTraversals() {
650 if (!mTraversalScheduled) {
651 mTraversalScheduled = true;
652 sendEmptyMessage(DO_TRAVERSAL);
653 }
654 }
655
656 public void unscheduleTraversals() {
657 if (mTraversalScheduled) {
658 mTraversalScheduled = false;
659 removeMessages(DO_TRAVERSAL);
660 }
661 }
662
663 int getHostVisibility() {
664 return mAppVisible ? mView.getVisibility() : View.GONE;
665 }
Romain Guy8506ab42009-06-11 17:35:47 -0700666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 private void performTraversals() {
668 // cache mView since it is used so much below...
669 final View host = mView;
670
671 if (DBG) {
672 System.out.println("======================================");
673 System.out.println("performTraversals");
674 host.debug();
675 }
676
677 if (host == null || !mAdded)
678 return;
679
680 mTraversalScheduled = false;
681 mWillDrawSoon = true;
682 boolean windowResizesToFitContent = false;
683 boolean fullRedrawNeeded = mFullRedrawNeeded;
684 boolean newSurface = false;
685 WindowManager.LayoutParams lp = mWindowAttributes;
686
687 int desiredWindowWidth;
688 int desiredWindowHeight;
689 int childWidthMeasureSpec;
690 int childHeightMeasureSpec;
691
692 final View.AttachInfo attachInfo = mAttachInfo;
693
694 final int viewVisibility = getHostVisibility();
695 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
696 || mNewSurfaceNeeded;
697
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700698 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 WindowManager.LayoutParams params = null;
701 if (mWindowAttributesChanged) {
702 mWindowAttributesChanged = false;
703 params = lp;
704 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700705 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 if (mFirst) {
707 fullRedrawNeeded = true;
708 mLayoutRequested = true;
709
Romain Guy8506ab42009-06-11 17:35:47 -0700710 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700711 mView.getContext().getResources().getDisplayMetrics();
712 desiredWindowWidth = packageMetrics.widthPixels;
713 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714
715 // For the very first time, tell the view hierarchy that it
716 // is attached to the window. Note that at this point the surface
717 // object is not initialized to its backing store, but soon it
718 // will be (assuming the window is visible).
719 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700720 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 attachInfo.mHasWindowFocus = false;
722 attachInfo.mWindowVisibility = viewVisibility;
723 attachInfo.mRecomputeGlobalAttributes = false;
724 attachInfo.mKeepScreenOn = false;
725 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700726 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700731 desiredWindowWidth = frame.width();
732 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
734 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700735 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 fullRedrawNeeded = true;
737 mLayoutRequested = true;
738 windowResizesToFitContent = true;
739 }
740 }
741
742 if (viewVisibilityChanged) {
743 attachInfo.mWindowVisibility = viewVisibility;
744 host.dispatchWindowVisibilityChanged(viewVisibility);
745 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
746 if (mUseGL) {
747 destroyGL();
748 }
749 }
750 if (viewVisibility == View.GONE) {
751 // After making a window gone, we will count it as being
752 // shown for the first time the next time it gets focus.
753 mHasHadWindowFocus = false;
754 }
755 }
756
757 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700760 // Execute enqueued actions on every layout in case a view that was detached
761 // enqueued an action after being detached
762 getRunQueue().executeActions(attachInfo.mHandler);
763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 if (mFirst) {
765 host.fitSystemWindows(mAttachInfo.mContentInsets);
766 // make sure touch mode code executes by setting cached value
767 // to opposite of the added touch mode.
768 mAttachInfo.mInTouchMode = !mAddedTouchMode;
769 ensureTouchModeLocally(mAddedTouchMode);
770 } else {
771 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
772 mAttachInfo.mContentInsets.set(mPendingContentInsets);
773 host.fitSystemWindows(mAttachInfo.mContentInsets);
774 insetsChanged = true;
775 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
776 + mAttachInfo.mContentInsets);
777 }
778 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
779 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
780 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
781 + mAttachInfo.mVisibleInsets);
782 }
783 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
784 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
785 windowResizesToFitContent = true;
786
Romain Guy8506ab42009-06-11 17:35:47 -0700787 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700788 mView.getContext().getResources().getDisplayMetrics();
789 desiredWindowWidth = packageMetrics.widthPixels;
790 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792 }
793
794 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
795 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
796
797 // Ask host how big it wants to be
798 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
799 "Measuring " + host + " in display " + desiredWindowWidth
800 + "x" + desiredWindowHeight + "...");
801 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
802
803 if (DBG) {
804 System.out.println("======================================");
805 System.out.println("performTraversals -- after measure");
806 host.debug();
807 }
808 }
809
810 if (attachInfo.mRecomputeGlobalAttributes) {
811 //Log.i(TAG, "Computing screen on!");
812 attachInfo.mRecomputeGlobalAttributes = false;
813 boolean oldVal = attachInfo.mKeepScreenOn;
814 attachInfo.mKeepScreenOn = false;
815 host.dispatchCollectViewAttributes(0);
816 if (attachInfo.mKeepScreenOn != oldVal) {
817 params = lp;
818 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
819 }
820 }
821
822 if (mFirst || attachInfo.mViewVisibilityChanged) {
823 attachInfo.mViewVisibilityChanged = false;
824 int resizeMode = mSoftInputMode &
825 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
826 // If we are in auto resize mode, then we need to determine
827 // what mode to use now.
828 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
829 final int N = attachInfo.mScrollContainers.size();
830 for (int i=0; i<N; i++) {
831 if (attachInfo.mScrollContainers.get(i).isShown()) {
832 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
833 }
834 }
835 if (resizeMode == 0) {
836 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
837 }
838 if ((lp.softInputMode &
839 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
840 lp.softInputMode = (lp.softInputMode &
841 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
842 resizeMode;
843 params = lp;
844 }
845 }
846 }
Romain Guy8506ab42009-06-11 17:35:47 -0700847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
849 if (!PixelFormat.formatHasAlpha(params.format)) {
850 params.format = PixelFormat.TRANSLUCENT;
851 }
852 }
853
854 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
855 && (mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight);
856
857 final boolean computesInternalInsets =
858 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
859 boolean insetsPending = false;
860 int relayoutResult = 0;
861 if (mFirst || windowShouldResize || insetsChanged
862 || viewVisibilityChanged || params != null) {
863
864 if (viewVisibility == View.VISIBLE) {
865 // If this window is giving internal insets to the window
866 // manager, and it is being added or changing its visibility,
867 // then we want to first give the window manager "fake"
868 // insets to cause it to effectively ignore the content of
869 // the window during layout. This avoids it briefly causing
870 // other windows to resize/move based on the raw frame of the
871 // window, waiting until we can finish laying out this window
872 // and get back to the window manager with the ultimately
873 // computed insets.
874 insetsPending = computesInternalInsets
875 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
878 if (params == null) {
879 params = mWindowAttributes;
880 }
881 mGlWanted = true;
882 }
883 }
884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 boolean initialized = false;
886 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700887 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 try {
889 boolean hadSurface = mSurface.isValid();
890 int fl = 0;
891 if (params != null) {
892 fl = params.flags;
893 if (attachInfo.mKeepScreenOn) {
894 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
895 }
896 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700897 if (DEBUG_LAYOUT) {
898 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
899 host.mMeasuredHeight + ", params=" + params);
900 }
901 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 if (params != null) {
904 params.flags = fl;
905 }
906
907 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
908 + " content=" + mPendingContentInsets.toShortString()
909 + " visible=" + mPendingVisibleInsets.toShortString()
910 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700911
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700912 if (mPendingConfiguration.seq != 0) {
913 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
914 + mPendingConfiguration);
915 updateConfiguration(mPendingConfiguration, !mFirst);
916 mPendingConfiguration.seq = 0;
917 }
918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 contentInsetsChanged = !mPendingContentInsets.equals(
920 mAttachInfo.mContentInsets);
921 visibleInsetsChanged = !mPendingVisibleInsets.equals(
922 mAttachInfo.mVisibleInsets);
923 if (contentInsetsChanged) {
924 mAttachInfo.mContentInsets.set(mPendingContentInsets);
925 host.fitSystemWindows(mAttachInfo.mContentInsets);
926 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
927 + mAttachInfo.mContentInsets);
928 }
929 if (visibleInsetsChanged) {
930 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
931 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
932 + mAttachInfo.mVisibleInsets);
933 }
934
935 if (!hadSurface) {
936 if (mSurface.isValid()) {
937 // If we are creating a new surface, then we need to
938 // completely redraw it. Also, when we get to the
939 // point of drawing it we will hold off and schedule
940 // a new traversal instead. This is so we can tell the
941 // window manager about all of the windows being displayed
942 // before actually drawing them, so it can display then
943 // all at once.
944 newSurface = true;
945 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700946 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 if (mGlWanted && !mUseGL) {
949 initializeGL();
950 initialized = mGlCanvas != null;
951 }
952 }
953 } else if (!mSurface.isValid()) {
954 // If the surface has been removed, then reset the scroll
955 // positions.
956 mLastScrolledFocus = null;
957 mScrollY = mCurScrollY = 0;
958 if (mScroller != null) {
959 mScroller.abortAnimation();
960 }
961 }
962 } catch (RemoteException e) {
963 }
964 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700965 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966
967 attachInfo.mWindowLeft = frame.left;
968 attachInfo.mWindowTop = frame.top;
969
970 // !!FIXME!! This next section handles the case where we did not get the
971 // window size we asked for. We should avoid this by getting a maximum size from
972 // the window session beforehand.
973 mWidth = frame.width();
974 mHeight = frame.height();
975
976 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -0700977 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
978 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
980
981 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
982 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
983 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
984 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
985 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
986 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
987
988 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
989 + mWidth + " measuredWidth=" + host.mMeasuredWidth
990 + " mHeight=" + mHeight
991 + " measuredHeight" + host.mMeasuredHeight
992 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 // Ask host how big it wants to be
995 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
996
997 // Implementation of weights from WindowManager.LayoutParams
998 // We just grow the dimensions as needed and re-measure if
999 // needs be
1000 int width = host.mMeasuredWidth;
1001 int height = host.mMeasuredHeight;
1002 boolean measureAgain = false;
1003
1004 if (lp.horizontalWeight > 0.0f) {
1005 width += (int) ((mWidth - width) * lp.horizontalWeight);
1006 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1007 MeasureSpec.EXACTLY);
1008 measureAgain = true;
1009 }
1010 if (lp.verticalWeight > 0.0f) {
1011 height += (int) ((mHeight - height) * lp.verticalWeight);
1012 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1013 MeasureSpec.EXACTLY);
1014 measureAgain = true;
1015 }
1016
1017 if (measureAgain) {
1018 if (DEBUG_LAYOUT) Log.v(TAG,
1019 "And hey let's measure once more: width=" + width
1020 + " height=" + height);
1021 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1022 }
1023
1024 mLayoutRequested = true;
1025 }
1026 }
1027
1028 final boolean didLayout = mLayoutRequested;
1029 boolean triggerGlobalLayoutListener = didLayout
1030 || attachInfo.mRecomputeGlobalAttributes;
1031 if (didLayout) {
1032 mLayoutRequested = false;
1033 mScrollMayChange = true;
1034 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1035 "ViewRoot", "Laying out " + host + " to (" +
1036 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001037 long startTime = 0L;
1038 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 startTime = SystemClock.elapsedRealtime();
1040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1042
Romain Guy13922e02009-05-12 17:56:14 -07001043 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1044 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1045 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1046 + "please refer to the logs with the tag "
1047 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1048 }
1049 }
1050
1051 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1053 }
1054
1055 // By this point all views have been sized and positionned
1056 // We can compute the transparent area
1057
1058 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1059 // start out transparent
1060 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1061 host.getLocationInWindow(mTmpLocation);
1062 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1063 mTmpLocation[0] + host.mRight - host.mLeft,
1064 mTmpLocation[1] + host.mBottom - host.mTop);
1065
1066 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001067 if (mTranslator != null) {
1068 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1069 }
1070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1072 mPreviousTransparentRegion.set(mTransparentRegion);
1073 // reconfigure window manager
1074 try {
1075 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1076 } catch (RemoteException e) {
1077 }
1078 }
1079 }
1080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 if (DBG) {
1082 System.out.println("======================================");
1083 System.out.println("performTraversals -- after setFrame");
1084 host.debug();
1085 }
1086 }
1087
1088 if (triggerGlobalLayoutListener) {
1089 attachInfo.mRecomputeGlobalAttributes = false;
1090 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1091 }
1092
1093 if (computesInternalInsets) {
1094 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1095 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1096 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1097 givenContent.left = givenContent.top = givenContent.right
1098 = givenContent.bottom = givenVisible.left = givenVisible.top
1099 = givenVisible.right = givenVisible.bottom = 0;
1100 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001101 Rect contentInsets = insets.contentInsets;
1102 Rect visibleInsets = insets.visibleInsets;
1103 if (mTranslator != null) {
1104 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1105 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1108 mLastGivenInsets.set(insets);
1109 try {
1110 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001111 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 } catch (RemoteException e) {
1113 }
1114 }
1115 }
Romain Guy8506ab42009-06-11 17:35:47 -07001116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 if (mFirst) {
1118 // handle first focus request
1119 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1120 + mView.hasFocus());
1121 if (mView != null) {
1122 if (!mView.hasFocus()) {
1123 mView.requestFocus(View.FOCUS_FORWARD);
1124 mFocusedView = mRealFocusedView = mView.findFocus();
1125 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1126 + mFocusedView);
1127 } else {
1128 mRealFocusedView = mView.findFocus();
1129 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1130 + mRealFocusedView);
1131 }
1132 }
1133 }
1134
1135 mFirst = false;
1136 mWillDrawSoon = false;
1137 mNewSurfaceNeeded = false;
1138 mViewVisibility = viewVisibility;
1139
1140 if (mAttachInfo.mHasWindowFocus) {
1141 final boolean imTarget = WindowManager.LayoutParams
1142 .mayUseInputMethod(mWindowAttributes.flags);
1143 if (imTarget != mLastWasImTarget) {
1144 mLastWasImTarget = imTarget;
1145 InputMethodManager imm = InputMethodManager.peekInstance();
1146 if (imm != null && imTarget) {
1147 imm.startGettingWindowFocus(mView);
1148 imm.onWindowFocus(mView, mView.findFocus(),
1149 mWindowAttributes.softInputMode,
1150 !mHasHadWindowFocus, mWindowAttributes.flags);
1151 }
1152 }
1153 }
Romain Guy8506ab42009-06-11 17:35:47 -07001154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1156
1157 if (!cancelDraw && !newSurface) {
1158 mFullRedrawNeeded = false;
1159 draw(fullRedrawNeeded);
1160
1161 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1162 || mReportNextDraw) {
1163 if (LOCAL_LOGV) {
1164 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1165 }
1166 mReportNextDraw = false;
1167 try {
1168 sWindowSession.finishDrawing(mWindow);
1169 } catch (RemoteException e) {
1170 }
1171 }
1172 } else {
1173 // We were supposed to report when we are done drawing. Since we canceled the
1174 // draw, remember it here.
1175 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1176 mReportNextDraw = true;
1177 }
1178 if (fullRedrawNeeded) {
1179 mFullRedrawNeeded = true;
1180 }
1181 // Try again
1182 scheduleTraversals();
1183 }
1184 }
1185
1186 public void requestTransparentRegion(View child) {
1187 // the test below should not fail unless someone is messing with us
1188 checkThread();
1189 if (mView == child) {
1190 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1191 // Need to make sure we re-evaluate the window attributes next
1192 // time around, to ensure the window has the correct format.
1193 mWindowAttributesChanged = true;
1194 }
1195 }
1196
1197 /**
1198 * Figures out the measure spec for the root view in a window based on it's
1199 * layout params.
1200 *
1201 * @param windowSize
1202 * The available width or height of the window
1203 *
1204 * @param rootDimension
1205 * The layout params for one dimension (width or height) of the
1206 * window.
1207 *
1208 * @return The measure spec to use to measure the root view.
1209 */
1210 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1211 int measureSpec;
1212 switch (rootDimension) {
1213
Romain Guy980a9382010-01-08 15:06:28 -08001214 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 // Window can't resize. Force root view to be windowSize.
1216 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1217 break;
1218 case ViewGroup.LayoutParams.WRAP_CONTENT:
1219 // Window can resize. Set max size for root view.
1220 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1221 break;
1222 default:
1223 // Window wants to be an exact size. Force root view to be that size.
1224 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1225 break;
1226 }
1227 return measureSpec;
1228 }
1229
1230 private void draw(boolean fullRedrawNeeded) {
1231 Surface surface = mSurface;
1232 if (surface == null || !surface.isValid()) {
1233 return;
1234 }
1235
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001236 if (!sFirstDrawComplete) {
1237 synchronized (sFirstDrawHandlers) {
1238 sFirstDrawComplete = true;
1239 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1240 post(sFirstDrawHandlers.get(i));
1241 }
1242 }
1243 }
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 scrollToRectOrFocus(null, false);
1246
1247 if (mAttachInfo.mViewScrollChanged) {
1248 mAttachInfo.mViewScrollChanged = false;
1249 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1250 }
Romain Guy8506ab42009-06-11 17:35:47 -07001251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001253 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 if (scrolling) {
1255 yoff = mScroller.getCurrY();
1256 } else {
1257 yoff = mScrollY;
1258 }
1259 if (mCurScrollY != yoff) {
1260 mCurScrollY = yoff;
1261 fullRedrawNeeded = true;
1262 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001263 float appScale = mAttachInfo.mApplicationScale;
1264 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265
1266 Rect dirty = mDirty;
1267 if (mUseGL) {
1268 if (!dirty.isEmpty()) {
1269 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001270 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 mGL.glDisable(GL_SCISSOR_TEST);
1272 mGL.glClearColor(0, 0, 0, 0);
1273 mGL.glClear(GL_COLOR_BUFFER_BIT);
1274 mGL.glEnable(GL_SCISSOR_TEST);
1275
1276 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001277 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001279
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001280 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1281 try {
1282 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001283 if (mTranslator != null) {
1284 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001285 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001286 canvas.setScreenDensity(scalingRequired
1287 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001288 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001289 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1290 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1291 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001292 } finally {
1293 canvas.restoreToCount(saveCount);
1294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295
Romain Guy5bcdff42009-05-14 21:27:18 -07001296 mAttachInfo.mIgnoreDirtyState = false;
1297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1299 checkEglErrors();
1300
Mike Reedfd716532009-10-12 14:42:56 -04001301 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 int now = (int)SystemClock.elapsedRealtime();
1303 if (sDrawTime != 0) {
1304 nativeShowFPS(canvas, now - sDrawTime);
1305 }
1306 sDrawTime = now;
1307 }
1308 }
1309 }
1310 if (scrolling) {
1311 mFullRedrawNeeded = true;
1312 scheduleTraversals();
1313 }
1314 return;
1315 }
1316
Romain Guy5bcdff42009-05-14 21:27:18 -07001317 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001318 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001319 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321
1322 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1323 Log.v("ViewRoot", "Draw " + mView + "/"
1324 + mWindowAttributes.getTitle()
1325 + ": dirty={" + dirty.left + "," + dirty.top
1326 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001327 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1328 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330
1331 Canvas canvas;
1332 try {
Romain Guy5bcdff42009-05-14 21:27:18 -07001333 int left = dirty.left;
1334 int top = dirty.top;
1335 int right = dirty.right;
1336 int bottom = dirty.bottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001338
1339 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1340 bottom != dirty.bottom) {
1341 mAttachInfo.mIgnoreDirtyState = true;
1342 }
1343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 // TODO: Do this in native
Dianne Hackborn11ea3342009-07-22 21:48:55 -07001345 canvas.setDensity(mDensity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 } catch (Surface.OutOfResourcesException e) {
1347 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1348 // TODO: we should ask the window manager to do something!
1349 // for now we just do nothing
1350 return;
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001351 } catch (IllegalArgumentException e) {
1352 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1353 // TODO: we should ask the window manager to do something!
1354 // for now we just do nothing
1355 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357
1358 try {
Romain Guybb93d552009-03-24 21:04:15 -07001359 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy13922e02009-05-12 17:56:14 -07001360 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361
1362 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1363 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1364 + canvas.getWidth() + ", h=" + canvas.getHeight());
1365 //canvas.drawARGB(255, 255, 0, 0);
1366 }
1367
Romain Guy13922e02009-05-12 17:56:14 -07001368 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 startTime = SystemClock.elapsedRealtime();
1370 }
1371
1372 // If this bitmap's format includes an alpha channel, we
1373 // need to clear it before drawing so that the child will
1374 // properly re-composite its drawing on a transparent
1375 // background. This automatically respects the clip/dirty region
Romain Guy5bcdff42009-05-14 21:27:18 -07001376 // or
1377 // If we are applying an offset, we need to clear the area
1378 // where the offset doesn't appear to avoid having garbage
1379 // left in the blank areas.
1380 if (!canvas.isOpaque() || yoff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1382 }
1383
1384 dirty.setEmpty();
Romain Guybb93d552009-03-24 21:04:15 -07001385 mIsAnimating = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001387 mView.mPrivateFlags |= View.DRAWN;
1388
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001389 if (DEBUG_DRAW) {
Romain Guy5bcdff42009-05-14 21:27:18 -07001390 Context cxt = mView.getContext();
1391 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -07001392 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1393 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001394 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001395 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001396 try {
1397 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001398 if (mTranslator != null) {
1399 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001400 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001401 canvas.setScreenDensity(scalingRequired
1402 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001403 mView.draw(canvas);
1404 } finally {
Romain Guy5bcdff42009-05-14 21:27:18 -07001405 mAttachInfo.mIgnoreDirtyState = false;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001406 canvas.restoreToCount(saveCount);
1407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408
Romain Guy5bcdff42009-05-14 21:27:18 -07001409 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1410 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1411 }
1412
Mike Reedfd716532009-10-12 14:42:56 -04001413 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 int now = (int)SystemClock.elapsedRealtime();
1415 if (sDrawTime != 0) {
1416 nativeShowFPS(canvas, now - sDrawTime);
1417 }
1418 sDrawTime = now;
1419 }
1420
Romain Guy13922e02009-05-12 17:56:14 -07001421 if (Config.DEBUG && ViewDebug.profileDrawing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1423 }
1424 }
Romain Guy8506ab42009-06-11 17:35:47 -07001425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 } finally {
1427 surface.unlockCanvasAndPost(canvas);
1428 }
1429
1430 if (LOCAL_LOGV) {
1431 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1432 }
Romain Guy8506ab42009-06-11 17:35:47 -07001433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 if (scrolling) {
1435 mFullRedrawNeeded = true;
1436 scheduleTraversals();
1437 }
1438 }
1439
1440 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1441 final View.AttachInfo attachInfo = mAttachInfo;
1442 final Rect ci = attachInfo.mContentInsets;
1443 final Rect vi = attachInfo.mVisibleInsets;
1444 int scrollY = 0;
1445 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 if (vi.left > ci.left || vi.top > ci.top
1448 || vi.right > ci.right || vi.bottom > ci.bottom) {
1449 // We'll assume that we aren't going to change the scroll
1450 // offset, since we want to avoid that unless it is actually
1451 // going to make the focus visible... otherwise we scroll
1452 // all over the place.
1453 scrollY = mScrollY;
1454 // We can be called for two different situations: during a draw,
1455 // to update the scroll position if the focus has changed (in which
1456 // case 'rectangle' is null), or in response to a
1457 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1458 // is non-null and we just want to scroll to whatever that
1459 // rectangle is).
1460 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001461
1462 // When in touch mode, focus points to the previously focused view,
1463 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001464 // line checks whether the view is still in our hierarchy.
1465 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001466 mRealFocusedView = null;
1467 return false;
1468 }
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 if (focus != mLastScrolledFocus) {
1471 // If the focus has changed, then ignore any requests to scroll
1472 // to a rectangle; first we want to make sure the entire focus
1473 // view is visible.
1474 rectangle = null;
1475 }
1476 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1477 + " rectangle=" + rectangle + " ci=" + ci
1478 + " vi=" + vi);
1479 if (focus == mLastScrolledFocus && !mScrollMayChange
1480 && rectangle == null) {
1481 // Optimization: if the focus hasn't changed since last
1482 // time, and no layout has happened, then just leave things
1483 // as they are.
1484 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1485 + mScrollY + " vi=" + vi.toShortString());
1486 } else if (focus != null) {
1487 // We need to determine if the currently focused view is
1488 // within the visible part of the window and, if not, apply
1489 // a pan so it can be seen.
1490 mLastScrolledFocus = focus;
1491 mScrollMayChange = false;
1492 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1493 // Try to find the rectangle from the focus view.
1494 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1495 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1496 + mView.getWidth() + " h=" + mView.getHeight()
1497 + " ci=" + ci.toShortString()
1498 + " vi=" + vi.toShortString());
1499 if (rectangle == null) {
1500 focus.getFocusedRect(mTempRect);
1501 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1502 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001503 if (mView instanceof ViewGroup) {
1504 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1505 focus, mTempRect);
1506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1508 "Focus in window: focusRect="
1509 + mTempRect.toShortString()
1510 + " visRect=" + mVisRect.toShortString());
1511 } else {
1512 mTempRect.set(rectangle);
1513 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1514 "Request scroll to rect: "
1515 + mTempRect.toShortString()
1516 + " visRect=" + mVisRect.toShortString());
1517 }
1518 if (mTempRect.intersect(mVisRect)) {
1519 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1520 "Focus window visible rect: "
1521 + mTempRect.toShortString());
1522 if (mTempRect.height() >
1523 (mView.getHeight()-vi.top-vi.bottom)) {
1524 // If the focus simply is not going to fit, then
1525 // best is probably just to leave things as-is.
1526 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1527 "Too tall; leaving scrollY=" + scrollY);
1528 } else if ((mTempRect.top-scrollY) < vi.top) {
1529 scrollY -= vi.top - (mTempRect.top-scrollY);
1530 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1531 "Top covered; scrollY=" + scrollY);
1532 } else if ((mTempRect.bottom-scrollY)
1533 > (mView.getHeight()-vi.bottom)) {
1534 scrollY += (mTempRect.bottom-scrollY)
1535 - (mView.getHeight()-vi.bottom);
1536 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1537 "Bottom covered; scrollY=" + scrollY);
1538 }
1539 handled = true;
1540 }
1541 }
1542 }
1543 }
Romain Guy8506ab42009-06-11 17:35:47 -07001544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 if (scrollY != mScrollY) {
1546 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1547 + mScrollY + " , new=" + scrollY);
1548 if (!immediate) {
1549 if (mScroller == null) {
1550 mScroller = new Scroller(mView.getContext());
1551 }
1552 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1553 } else if (mScroller != null) {
1554 mScroller.abortAnimation();
1555 }
1556 mScrollY = scrollY;
1557 }
Romain Guy8506ab42009-06-11 17:35:47 -07001558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 return handled;
1560 }
Romain Guy8506ab42009-06-11 17:35:47 -07001561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 public void requestChildFocus(View child, View focused) {
1563 checkThread();
1564 if (mFocusedView != focused) {
1565 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1566 scheduleTraversals();
1567 }
1568 mFocusedView = mRealFocusedView = focused;
1569 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1570 + mFocusedView);
1571 }
1572
1573 public void clearChildFocus(View child) {
1574 checkThread();
1575
1576 View oldFocus = mFocusedView;
1577
1578 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1579 mFocusedView = mRealFocusedView = null;
1580 if (mView != null && !mView.hasFocus()) {
1581 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1582 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1583 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1584 }
1585 } else if (oldFocus != null) {
1586 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1587 }
1588 }
1589
1590
1591 public void focusableViewAvailable(View v) {
1592 checkThread();
1593
1594 if (mView != null && !mView.hasFocus()) {
1595 v.requestFocus();
1596 } else {
1597 // the one case where will transfer focus away from the current one
1598 // is if the current view is a view group that prefers to give focus
1599 // to its children first AND the view is a descendant of it.
1600 mFocusedView = mView.findFocus();
1601 boolean descendantsHaveDibsOnFocus =
1602 (mFocusedView instanceof ViewGroup) &&
1603 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1604 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1605 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1606 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1607 v.requestFocus();
1608 }
1609 }
1610 }
1611
1612 public void recomputeViewAttributes(View child) {
1613 checkThread();
1614 if (mView == child) {
1615 mAttachInfo.mRecomputeGlobalAttributes = true;
1616 if (!mWillDrawSoon) {
1617 scheduleTraversals();
1618 }
1619 }
1620 }
1621
1622 void dispatchDetachedFromWindow() {
1623 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1624
1625 if (mView != null) {
1626 mView.dispatchDetachedFromWindow();
1627 }
1628
1629 mView = null;
1630 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001631 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632
1633 if (mUseGL) {
1634 destroyGL();
1635 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001636 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637
1638 try {
1639 sWindowSession.remove(mWindow);
1640 } catch (RemoteException e) {
1641 }
1642 }
Romain Guy8506ab42009-06-11 17:35:47 -07001643
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001644 void updateConfiguration(Configuration config, boolean force) {
1645 if (DEBUG_CONFIGURATION) Log.v(TAG,
1646 "Applying new config to window "
1647 + mWindowAttributes.getTitle()
1648 + ": " + config);
1649 synchronized (sConfigCallbacks) {
1650 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1651 sConfigCallbacks.get(i).onConfigurationChanged(config);
1652 }
1653 }
1654 if (mView != null) {
1655 // At this point the resources have been updated to
1656 // have the most recent config, whatever that is. Use
1657 // the on in them which may be newer.
1658 if (mView != null) {
1659 config = mView.getResources().getConfiguration();
1660 }
1661 if (force || mLastConfiguration.diff(config) != 0) {
1662 mLastConfiguration.setTo(config);
1663 mView.dispatchConfigurationChanged(config);
1664 }
1665 }
1666 }
1667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 /**
1669 * Return true if child is an ancestor of parent, (or equal to the parent).
1670 */
1671 private static boolean isViewDescendantOf(View child, View parent) {
1672 if (child == parent) {
1673 return true;
1674 }
1675
1676 final ViewParent theParent = child.getParent();
1677 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1678 }
1679
Romain Guycdb86672010-03-18 18:54:50 -07001680 private static void forceLayout(View view) {
1681 view.forceLayout();
1682 if (view instanceof ViewGroup) {
1683 ViewGroup group = (ViewGroup) view;
1684 final int count = group.getChildCount();
1685 for (int i = 0; i < count; i++) {
1686 forceLayout(group.getChildAt(i));
1687 }
1688 }
1689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690
1691 public final static int DO_TRAVERSAL = 1000;
1692 public final static int DIE = 1001;
1693 public final static int RESIZED = 1002;
1694 public final static int RESIZED_REPORT = 1003;
1695 public final static int WINDOW_FOCUS_CHANGED = 1004;
1696 public final static int DISPATCH_KEY = 1005;
1697 public final static int DISPATCH_POINTER = 1006;
1698 public final static int DISPATCH_TRACKBALL = 1007;
1699 public final static int DISPATCH_APP_VISIBILITY = 1008;
1700 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1701 public final static int FINISHED_EVENT = 1010;
1702 public final static int DISPATCH_KEY_FROM_IME = 1011;
1703 public final static int FINISH_INPUT_CONNECTION = 1012;
1704 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001705 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706
1707 @Override
1708 public void handleMessage(Message msg) {
1709 switch (msg.what) {
1710 case View.AttachInfo.INVALIDATE_MSG:
1711 ((View) msg.obj).invalidate();
1712 break;
1713 case View.AttachInfo.INVALIDATE_RECT_MSG:
1714 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1715 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1716 info.release();
1717 break;
1718 case DO_TRAVERSAL:
1719 if (mProfile) {
1720 Debug.startMethodTracing("ViewRoot");
1721 }
1722
1723 performTraversals();
1724
1725 if (mProfile) {
1726 Debug.stopMethodTracing();
1727 mProfile = false;
1728 }
1729 break;
1730 case FINISHED_EVENT:
1731 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1732 break;
1733 case DISPATCH_KEY:
1734 if (LOCAL_LOGV) Log.v(
1735 "ViewRoot", "Dispatching key "
1736 + msg.obj + " to " + mView);
1737 deliverKeyEvent((KeyEvent)msg.obj, true);
1738 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001739 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001741 boolean callWhenDone = msg.arg1 != 0;
1742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 if (event == null) {
1744 try {
Michael Chan53071d62009-05-13 17:29:48 -07001745 long timeBeforeGettingEvents;
1746 if (MEASURE_LATENCY) {
1747 timeBeforeGettingEvents = System.nanoTime();
1748 }
1749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001751
1752 if (MEASURE_LATENCY && event != null) {
1753 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1754 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 } catch (RemoteException e) {
1757 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001758 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001760 if (event != null && mTranslator != null) {
1761 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 try {
1764 boolean handled;
1765 if (mView != null && mAdded && event != null) {
1766
1767 // enter touch mode on the down
1768 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1769 if (isDown) {
1770 ensureTouchMode(true);
1771 }
1772 if(Config.LOGV) {
1773 captureMotionLog("captureDispatchPointer", event);
1774 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001775 if (mCurScrollY != 0) {
1776 event.offsetLocation(0, mCurScrollY);
1777 }
Michael Chan53071d62009-05-13 17:29:48 -07001778 if (MEASURE_LATENCY) {
1779 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001782 if (MEASURE_LATENCY) {
1783 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 if (!handled && isDown) {
1786 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1787
1788 final int edgeFlags = event.getEdgeFlags();
1789 int direction = View.FOCUS_UP;
1790 int x = (int)event.getX();
1791 int y = (int)event.getY();
1792 final int[] deltas = new int[2];
1793
1794 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1795 direction = View.FOCUS_DOWN;
1796 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1797 deltas[0] = edgeSlop;
1798 x += edgeSlop;
1799 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1800 deltas[0] = -edgeSlop;
1801 x -= edgeSlop;
1802 }
1803 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1804 direction = View.FOCUS_UP;
1805 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1806 deltas[0] = edgeSlop;
1807 x += edgeSlop;
1808 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1809 deltas[0] = -edgeSlop;
1810 x -= edgeSlop;
1811 }
1812 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1813 direction = View.FOCUS_RIGHT;
1814 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1815 direction = View.FOCUS_LEFT;
1816 }
1817
1818 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1819 View nearest = FocusFinder.getInstance().findNearestTouchable(
1820 ((ViewGroup) mView), x, y, direction, deltas);
1821 if (nearest != null) {
1822 event.offsetLocation(deltas[0], deltas[1]);
1823 event.setEdgeFlags(0);
1824 mView.dispatchTouchEvent(event);
1825 }
1826 }
1827 }
1828 }
1829 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001830 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 try {
1832 sWindowSession.finishKey(mWindow);
1833 } catch (RemoteException e) {
1834 }
1835 }
1836 if (event != null) {
1837 event.recycle();
1838 }
1839 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1840 // Let the exception fall through -- the looper will catch
1841 // it and take care of the bad app for us.
1842 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001843 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001845 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 break;
1847 case DISPATCH_APP_VISIBILITY:
1848 handleAppVisibility(msg.arg1 != 0);
1849 break;
1850 case DISPATCH_GET_NEW_SURFACE:
1851 handleGetNewSurface();
1852 break;
1853 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001854 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001857 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001858 && mPendingVisibleInsets.equals(ri.visibleInsets)
1859 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 break;
1861 }
1862 // fall through...
1863 case RESIZED_REPORT:
1864 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001865 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1866 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001867 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 mWinFrame.left = 0;
1870 mWinFrame.right = msg.arg1;
1871 mWinFrame.top = 0;
1872 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001873 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1874 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 if (msg.what == RESIZED_REPORT) {
1876 mReportNextDraw = true;
1877 }
Romain Guycdb86672010-03-18 18:54:50 -07001878
1879 if (mView != null) {
1880 forceLayout(mView);
1881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 requestLayout();
1883 }
1884 break;
1885 case WINDOW_FOCUS_CHANGED: {
1886 if (mAdded) {
1887 boolean hasWindowFocus = msg.arg1 != 0;
1888 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1889 if (hasWindowFocus) {
1890 boolean inTouchMode = msg.arg2 != 0;
1891 ensureTouchModeLocally(inTouchMode);
1892
1893 if (mGlWanted) {
1894 checkEglErrors();
1895 // we lost the gl context, so recreate it.
1896 if (mGlWanted && !mUseGL) {
1897 initializeGL();
1898 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001899 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001900 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001901 (int) (mWidth * appScale + 0.5f),
1902 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
1904 }
1905 }
1906 }
Romain Guy8506ab42009-06-11 17:35:47 -07001907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 mLastWasImTarget = WindowManager.LayoutParams
1909 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 InputMethodManager imm = InputMethodManager.peekInstance();
1912 if (mView != null) {
1913 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1914 imm.startGettingWindowFocus(mView);
1915 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001916 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 mView.dispatchWindowFocusChanged(hasWindowFocus);
1918 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 // Note: must be done after the focus change callbacks,
1921 // so all of the view state is set up correctly.
1922 if (hasWindowFocus) {
1923 if (imm != null && mLastWasImTarget) {
1924 imm.onWindowFocus(mView, mView.findFocus(),
1925 mWindowAttributes.softInputMode,
1926 !mHasHadWindowFocus, mWindowAttributes.flags);
1927 }
1928 // Clear the forward bit. We can just do this directly, since
1929 // the window manager doesn't care about it.
1930 mWindowAttributes.softInputMode &=
1931 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1932 ((WindowManager.LayoutParams)mView.getLayoutParams())
1933 .softInputMode &=
1934 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1935 mHasHadWindowFocus = true;
1936 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001937
1938 if (hasWindowFocus && mView != null) {
1939 sendAccessibilityEvents();
1940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942 } break;
1943 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001944 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001946 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 if (LOCAL_LOGV) Log.v(
1948 "ViewRoot", "Dispatching key "
1949 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001950 KeyEvent event = (KeyEvent)msg.obj;
1951 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1952 // The IME is trying to say this event is from the
1953 // system! Bad bad bad!
1954 event = KeyEvent.changeFlags(event,
1955 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001958 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 case FINISH_INPUT_CONNECTION: {
1960 InputMethodManager imm = InputMethodManager.peekInstance();
1961 if (imm != null) {
1962 imm.reportFinishInputConnection((InputConnection)msg.obj);
1963 }
1964 } break;
1965 case CHECK_FOCUS: {
1966 InputMethodManager imm = InputMethodManager.peekInstance();
1967 if (imm != null) {
1968 imm.checkFocus();
1969 }
1970 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001971 case CLOSE_SYSTEM_DIALOGS: {
1972 if (mView != null) {
1973 mView.onCloseSystemDialogs((String)msg.obj);
1974 }
1975 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977 }
1978
1979 /**
1980 * Something in the current window tells us we need to change the touch mode. For
1981 * example, we are not in touch mode, and the user touches the screen.
1982 *
1983 * If the touch mode has changed, tell the window manager, and handle it locally.
1984 *
1985 * @param inTouchMode Whether we want to be in touch mode.
1986 * @return True if the touch mode changed and focus changed was changed as a result
1987 */
1988 boolean ensureTouchMode(boolean inTouchMode) {
1989 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1990 + "touch mode is " + mAttachInfo.mInTouchMode);
1991 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1992
1993 // tell the window manager
1994 try {
1995 sWindowSession.setInTouchMode(inTouchMode);
1996 } catch (RemoteException e) {
1997 throw new RuntimeException(e);
1998 }
1999
2000 // handle the change
2001 return ensureTouchModeLocally(inTouchMode);
2002 }
2003
2004 /**
2005 * Ensure that the touch mode for this window is set, and if it is changing,
2006 * take the appropriate action.
2007 * @param inTouchMode Whether we want to be in touch mode.
2008 * @return True if the touch mode changed and focus changed was changed as a result
2009 */
2010 private boolean ensureTouchModeLocally(boolean inTouchMode) {
2011 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2012 + "touch mode is " + mAttachInfo.mInTouchMode);
2013
2014 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2015
2016 mAttachInfo.mInTouchMode = inTouchMode;
2017 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2018
2019 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
2020 }
2021
2022 private boolean enterTouchMode() {
2023 if (mView != null) {
2024 if (mView.hasFocus()) {
2025 // note: not relying on mFocusedView here because this could
2026 // be when the window is first being added, and mFocused isn't
2027 // set yet.
2028 final View focused = mView.findFocus();
2029 if (focused != null && !focused.isFocusableInTouchMode()) {
2030
2031 final ViewGroup ancestorToTakeFocus =
2032 findAncestorToTakeFocusInTouchMode(focused);
2033 if (ancestorToTakeFocus != null) {
2034 // there is an ancestor that wants focus after its descendants that
2035 // is focusable in touch mode.. give it focus
2036 return ancestorToTakeFocus.requestFocus();
2037 } else {
2038 // nothing appropriate to have focus in touch mode, clear it out
2039 mView.unFocus();
2040 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2041 mFocusedView = null;
2042 return true;
2043 }
2044 }
2045 }
2046 }
2047 return false;
2048 }
2049
2050
2051 /**
2052 * Find an ancestor of focused that wants focus after its descendants and is
2053 * focusable in touch mode.
2054 * @param focused The currently focused view.
2055 * @return An appropriate view, or null if no such view exists.
2056 */
2057 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2058 ViewParent parent = focused.getParent();
2059 while (parent instanceof ViewGroup) {
2060 final ViewGroup vgParent = (ViewGroup) parent;
2061 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2062 && vgParent.isFocusableInTouchMode()) {
2063 return vgParent;
2064 }
2065 if (vgParent.isRootNamespace()) {
2066 return null;
2067 } else {
2068 parent = vgParent.getParent();
2069 }
2070 }
2071 return null;
2072 }
2073
2074 private boolean leaveTouchMode() {
2075 if (mView != null) {
2076 if (mView.hasFocus()) {
2077 // i learned the hard way to not trust mFocusedView :)
2078 mFocusedView = mView.findFocus();
2079 if (!(mFocusedView instanceof ViewGroup)) {
2080 // some view has focus, let it keep it
2081 return false;
2082 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2083 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2084 // some view group has focus, and doesn't prefer its children
2085 // over itself for focus, so let them keep it.
2086 return false;
2087 }
2088 }
2089
2090 // find the best view to give focus to in this brave new non-touch-mode
2091 // world
2092 final View focused = focusSearch(null, View.FOCUS_DOWN);
2093 if (focused != null) {
2094 return focused.requestFocus(View.FOCUS_DOWN);
2095 }
2096 }
2097 return false;
2098 }
2099
2100
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002101 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 if (event == null) {
2103 try {
2104 event = sWindowSession.getPendingTrackballMove(mWindow);
2105 } catch (RemoteException e) {
2106 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002107 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109
2110 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2111
2112 boolean handled = false;
2113 try {
2114 if (event == null) {
2115 handled = true;
2116 } else if (mView != null && mAdded) {
2117 handled = mView.dispatchTrackballEvent(event);
2118 if (!handled) {
2119 // we could do something here, like changing the focus
2120 // or something?
2121 }
2122 }
2123 } finally {
2124 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002125 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 try {
2127 sWindowSession.finishKey(mWindow);
2128 } catch (RemoteException e) {
2129 }
2130 }
2131 if (event != null) {
2132 event.recycle();
2133 }
2134 // If we reach this, we delivered a trackball event to mView and
2135 // mView consumed it. Because we will not translate the trackball
2136 // event into a key event, touch mode will not exit, so we exit
2137 // touch mode here.
2138 ensureTouchMode(false);
2139 //noinspection ReturnInsideFinallyBlock
2140 return;
2141 }
2142 // Let the exception fall through -- the looper will catch
2143 // it and take care of the bad app for us.
2144 }
2145
2146 final TrackballAxis x = mTrackballAxisX;
2147 final TrackballAxis y = mTrackballAxisY;
2148
2149 long curTime = SystemClock.uptimeMillis();
2150 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2151 // It has been too long since the last movement,
2152 // so restart at the beginning.
2153 x.reset(0);
2154 y.reset(0);
2155 mLastTrackballTime = curTime;
2156 }
2157
2158 try {
2159 final int action = event.getAction();
2160 final int metastate = event.getMetaState();
2161 switch (action) {
2162 case MotionEvent.ACTION_DOWN:
2163 x.reset(2);
2164 y.reset(2);
2165 deliverKeyEvent(new KeyEvent(curTime, curTime,
2166 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2167 0, metastate), false);
2168 break;
2169 case MotionEvent.ACTION_UP:
2170 x.reset(2);
2171 y.reset(2);
2172 deliverKeyEvent(new KeyEvent(curTime, curTime,
2173 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2174 0, metastate), false);
2175 break;
2176 }
2177
2178 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2179 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2180 + " move=" + event.getX()
2181 + " / Y=" + y.position + " step="
2182 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2183 + " move=" + event.getY());
2184 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2185 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2186
2187 // Generate DPAD events based on the trackball movement.
2188 // We pick the axis that has moved the most as the direction of
2189 // the DPAD. When we generate DPAD events for one axis, then the
2190 // other axis is reset -- we don't want to perform DPAD jumps due
2191 // to slight movements in the trackball when making major movements
2192 // along the other axis.
2193 int keycode = 0;
2194 int movement = 0;
2195 float accel = 1;
2196 if (xOff > yOff) {
2197 movement = x.generate((2/event.getXPrecision()));
2198 if (movement != 0) {
2199 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2200 : KeyEvent.KEYCODE_DPAD_LEFT;
2201 accel = x.acceleration;
2202 y.reset(2);
2203 }
2204 } else if (yOff > 0) {
2205 movement = y.generate((2/event.getYPrecision()));
2206 if (movement != 0) {
2207 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2208 : KeyEvent.KEYCODE_DPAD_UP;
2209 accel = y.acceleration;
2210 x.reset(2);
2211 }
2212 }
2213
2214 if (keycode != 0) {
2215 if (movement < 0) movement = -movement;
2216 int accelMovement = (int)(movement * accel);
2217 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2218 + " accelMovement=" + accelMovement
2219 + " accel=" + accel);
2220 if (accelMovement > movement) {
2221 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2222 + keycode);
2223 movement--;
2224 deliverKeyEvent(new KeyEvent(curTime, curTime,
2225 KeyEvent.ACTION_MULTIPLE, keycode,
2226 accelMovement-movement, metastate), false);
2227 }
2228 while (movement > 0) {
2229 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2230 + keycode);
2231 movement--;
2232 curTime = SystemClock.uptimeMillis();
2233 deliverKeyEvent(new KeyEvent(curTime, curTime,
2234 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2235 deliverKeyEvent(new KeyEvent(curTime, curTime,
2236 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2237 }
2238 mLastTrackballTime = curTime;
2239 }
2240 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002241 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 try {
2243 sWindowSession.finishKey(mWindow);
2244 } catch (RemoteException e) {
2245 }
2246 if (event != null) {
2247 event.recycle();
2248 }
2249 }
2250 // Let the exception fall through -- the looper will catch
2251 // it and take care of the bad app for us.
2252 }
2253 }
2254
2255 /**
2256 * @param keyCode The key code
2257 * @return True if the key is directional.
2258 */
2259 static boolean isDirectional(int keyCode) {
2260 switch (keyCode) {
2261 case KeyEvent.KEYCODE_DPAD_LEFT:
2262 case KeyEvent.KEYCODE_DPAD_RIGHT:
2263 case KeyEvent.KEYCODE_DPAD_UP:
2264 case KeyEvent.KEYCODE_DPAD_DOWN:
2265 return true;
2266 }
2267 return false;
2268 }
2269
2270 /**
2271 * Returns true if this key is a keyboard key.
2272 * @param keyEvent The key event.
2273 * @return whether this key is a keyboard key.
2274 */
2275 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2276 final int convertedKey = keyEvent.getUnicodeChar();
2277 return convertedKey > 0;
2278 }
2279
2280
2281
2282 /**
2283 * See if the key event means we should leave touch mode (and leave touch
2284 * mode if so).
2285 * @param event The key event.
2286 * @return Whether this key event should be consumed (meaning the act of
2287 * leaving touch mode alone is considered the event).
2288 */
2289 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002290 final int action = event.getAction();
2291 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 return false;
2293 }
2294 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2295 return false;
2296 }
2297
2298 // only relevant if we are in touch mode
2299 if (!mAttachInfo.mInTouchMode) {
2300 return false;
2301 }
2302
2303 // if something like an edit text has focus and the user is typing,
2304 // leave touch mode
2305 //
2306 // note: the condition of not being a keyboard key is kind of a hacky
2307 // approximation of whether we think the focused view will want the
2308 // key; if we knew for sure whether the focused view would consume
2309 // the event, that would be better.
2310 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2311 mFocusedView = mView.findFocus();
2312 if ((mFocusedView instanceof ViewGroup)
2313 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2314 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2315 // something has focus, but is holding it weakly as a container
2316 return false;
2317 }
2318 if (ensureTouchMode(false)) {
2319 throw new IllegalStateException("should not have changed focus "
2320 + "when leaving touch mode while a view has focus.");
2321 }
2322 return false;
2323 }
2324
2325 if (isDirectional(event.getKeyCode())) {
2326 // no view has focus, so we leave touch mode (and find something
2327 // to give focus to). the event is consumed if we were able to
2328 // find something to give focus to.
2329 return ensureTouchMode(false);
2330 }
2331 return false;
2332 }
2333
2334 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002335 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 */
2337 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002338 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 if (ev == null ||
2340 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2341 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 }
Romain Guy8506ab42009-06-11 17:35:47 -07002343
2344 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 sb.append(ev.getDownTime()).append(',');
2346 sb.append(ev.getEventTime()).append(',');
2347 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002348 sb.append(ev.getX()).append(',');
2349 sb.append(ev.getY()).append(',');
2350 sb.append(ev.getPressure()).append(',');
2351 sb.append(ev.getSize()).append(',');
2352 sb.append(ev.getMetaState()).append(',');
2353 sb.append(ev.getXPrecision()).append(',');
2354 sb.append(ev.getYPrecision()).append(',');
2355 sb.append(ev.getDeviceId()).append(',');
2356 sb.append(ev.getEdgeFlags());
2357 Log.d(TAG, sb.toString());
2358 }
2359 /**
2360 * log motion events
2361 */
2362 private static void captureKeyLog(String subTag, KeyEvent ev) {
2363 //check dynamic switch
2364 if (ev == null ||
2365 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2366 return;
2367 }
2368 StringBuilder sb = new StringBuilder(subTag + ": ");
2369 sb.append(ev.getDownTime()).append(',');
2370 sb.append(ev.getEventTime()).append(',');
2371 sb.append(ev.getAction()).append(',');
2372 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 sb.append(ev.getRepeatCount()).append(',');
2374 sb.append(ev.getMetaState()).append(',');
2375 sb.append(ev.getDeviceId()).append(',');
2376 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002377 Log.d(TAG, sb.toString());
2378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379
2380 int enqueuePendingEvent(Object event, boolean sendDone) {
2381 int seq = mPendingEventSeq+1;
2382 if (seq < 0) seq = 0;
2383 mPendingEventSeq = seq;
2384 mPendingEvents.put(seq, event);
2385 return sendDone ? seq : -seq;
2386 }
2387
2388 Object retrievePendingEvent(int seq) {
2389 if (seq < 0) seq = -seq;
2390 Object event = mPendingEvents.get(seq);
2391 if (event != null) {
2392 mPendingEvents.remove(seq);
2393 }
2394 return event;
2395 }
Romain Guy8506ab42009-06-11 17:35:47 -07002396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2398 // If mView is null, we just consume the key event because it doesn't
2399 // make sense to do anything else with it.
2400 boolean handled = mView != null
2401 ? mView.dispatchKeyEventPreIme(event) : true;
2402 if (handled) {
2403 if (sendDone) {
2404 if (LOCAL_LOGV) Log.v(
2405 "ViewRoot", "Telling window manager key is finished");
2406 try {
2407 sWindowSession.finishKey(mWindow);
2408 } catch (RemoteException e) {
2409 }
2410 }
2411 return;
2412 }
2413 // If it is possible for this window to interact with the input
2414 // method window, then we want to first dispatch our key events
2415 // to the input method.
2416 if (mLastWasImTarget) {
2417 InputMethodManager imm = InputMethodManager.peekInstance();
2418 if (imm != null && mView != null) {
2419 int seq = enqueuePendingEvent(event, sendDone);
2420 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2421 + seq + " event=" + event);
2422 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2423 mInputMethodCallback);
2424 return;
2425 }
2426 }
2427 deliverKeyEventToViewHierarchy(event, sendDone);
2428 }
2429
2430 void handleFinishedEvent(int seq, boolean handled) {
2431 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2432 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2433 + " handled=" + handled + " event=" + event);
2434 if (event != null) {
2435 final boolean sendDone = seq >= 0;
2436 if (!handled) {
2437 deliverKeyEventToViewHierarchy(event, sendDone);
2438 return;
2439 } else if (sendDone) {
2440 if (LOCAL_LOGV) Log.v(
2441 "ViewRoot", "Telling window manager key is finished");
2442 try {
2443 sWindowSession.finishKey(mWindow);
2444 } catch (RemoteException e) {
2445 }
2446 } else {
2447 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2448 + " handled=" + handled + " ev=" + event
2449 + ") neither delivering nor finishing key");
2450 }
2451 }
2452 }
Romain Guy8506ab42009-06-11 17:35:47 -07002453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2455 try {
2456 if (mView != null && mAdded) {
2457 final int action = event.getAction();
2458 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2459
2460 if (checkForLeavingTouchModeAndConsume(event)) {
2461 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002462 }
2463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 if (Config.LOGV) {
2465 captureKeyLog("captureDispatchKeyEvent", event);
2466 }
2467 boolean keyHandled = mView.dispatchKeyEvent(event);
2468
2469 if (!keyHandled && isDown) {
2470 int direction = 0;
2471 switch (event.getKeyCode()) {
2472 case KeyEvent.KEYCODE_DPAD_LEFT:
2473 direction = View.FOCUS_LEFT;
2474 break;
2475 case KeyEvent.KEYCODE_DPAD_RIGHT:
2476 direction = View.FOCUS_RIGHT;
2477 break;
2478 case KeyEvent.KEYCODE_DPAD_UP:
2479 direction = View.FOCUS_UP;
2480 break;
2481 case KeyEvent.KEYCODE_DPAD_DOWN:
2482 direction = View.FOCUS_DOWN;
2483 break;
2484 }
2485
2486 if (direction != 0) {
2487
2488 View focused = mView != null ? mView.findFocus() : null;
2489 if (focused != null) {
2490 View v = focused.focusSearch(direction);
2491 boolean focusPassed = false;
2492 if (v != null && v != focused) {
2493 // do the math the get the interesting rect
2494 // of previous focused into the coord system of
2495 // newly focused view
2496 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002497 if (mView instanceof ViewGroup) {
2498 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2499 focused, mTempRect);
2500 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2501 v, mTempRect);
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 focusPassed = v.requestFocus(direction, mTempRect);
2504 }
2505
2506 if (!focusPassed) {
2507 mView.dispatchUnhandledMove(focused, direction);
2508 } else {
2509 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2510 }
2511 }
2512 }
2513 }
2514 }
2515
2516 } finally {
2517 if (sendDone) {
2518 if (LOCAL_LOGV) Log.v(
2519 "ViewRoot", "Telling window manager key is finished");
2520 try {
2521 sWindowSession.finishKey(mWindow);
2522 } catch (RemoteException e) {
2523 }
2524 }
2525 // Let the exception fall through -- the looper will catch
2526 // it and take care of the bad app for us.
2527 }
2528 }
2529
2530 private AudioManager getAudioManager() {
2531 if (mView == null) {
2532 throw new IllegalStateException("getAudioManager called when there is no mView");
2533 }
2534 if (mAudioManager == null) {
2535 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2536 }
2537 return mAudioManager;
2538 }
2539
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002540 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2541 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002542
2543 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002544 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002545 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002546 restore = true;
2547 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002548 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002549 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002550 if (params != null) {
2551 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002552 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002553 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002554 int relayoutResult = sWindowSession.relayout(
2555 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002556 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2557 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002558 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002559 mPendingContentInsets, mPendingVisibleInsets,
2560 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002561 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002562 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002563 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002564
2565 if (mTranslator != null) {
2566 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2567 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2568 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002569 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002570 return relayoutResult;
2571 }
Romain Guy8506ab42009-06-11 17:35:47 -07002572
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002573 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 * {@inheritDoc}
2575 */
2576 public void playSoundEffect(int effectId) {
2577 checkThread();
2578
2579 final AudioManager audioManager = getAudioManager();
2580
2581 switch (effectId) {
2582 case SoundEffectConstants.CLICK:
2583 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2584 return;
2585 case SoundEffectConstants.NAVIGATION_DOWN:
2586 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2587 return;
2588 case SoundEffectConstants.NAVIGATION_LEFT:
2589 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2590 return;
2591 case SoundEffectConstants.NAVIGATION_RIGHT:
2592 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2593 return;
2594 case SoundEffectConstants.NAVIGATION_UP:
2595 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2596 return;
2597 default:
2598 throw new IllegalArgumentException("unknown effect id " + effectId +
2599 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2600 }
2601 }
2602
2603 /**
2604 * {@inheritDoc}
2605 */
2606 public boolean performHapticFeedback(int effectId, boolean always) {
2607 try {
2608 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2609 } catch (RemoteException e) {
2610 return false;
2611 }
2612 }
2613
2614 /**
2615 * {@inheritDoc}
2616 */
2617 public View focusSearch(View focused, int direction) {
2618 checkThread();
2619 if (!(mView instanceof ViewGroup)) {
2620 return null;
2621 }
2622 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2623 }
2624
2625 public void debug() {
2626 mView.debug();
2627 }
2628
2629 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002630 if (immediate) {
2631 doDie();
2632 } else {
2633 sendEmptyMessage(DIE);
2634 }
2635 }
2636
2637 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 checkThread();
2639 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2640 synchronized (this) {
2641 if (mAdded && !mFirst) {
2642 int viewVisibility = mView.getVisibility();
2643 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2644 if (mWindowAttributesChanged || viewVisibilityChanged) {
2645 // If layout params have been changed, first give them
2646 // to the window manager to make sure it has the correct
2647 // animation info.
2648 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002649 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2650 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 sWindowSession.finishDrawing(mWindow);
2652 }
2653 } catch (RemoteException e) {
2654 }
2655 }
2656
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002657 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 }
2659 if (mAdded) {
2660 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002661 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 }
2663 }
2664 }
2665
2666 public void dispatchFinishedEvent(int seq, boolean handled) {
2667 Message msg = obtainMessage(FINISHED_EVENT);
2668 msg.arg1 = seq;
2669 msg.arg2 = handled ? 1 : 0;
2670 sendMessage(msg);
2671 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002674 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2676 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2677 + " visibleInsets=" + visibleInsets.toShortString()
2678 + " reportDraw=" + reportDraw);
2679 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002680 if (mTranslator != null) {
2681 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2682 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2683 w *= mTranslator.applicationInvertedScale;
2684 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002685 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002686 msg.arg1 = w;
2687 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002688 ResizedInfo ri = new ResizedInfo();
2689 ri.coveredInsets = new Rect(coveredInsets);
2690 ri.visibleInsets = new Rect(visibleInsets);
2691 ri.newConfig = newConfig;
2692 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 sendMessage(msg);
2694 }
2695
2696 public void dispatchKey(KeyEvent event) {
2697 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2698 //noinspection ConstantConditions
2699 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2700 if (Config.LOGD) Log.d("keydisp",
2701 "===================================================");
2702 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2703 debug();
2704
2705 if (Config.LOGD) Log.d("keydisp",
2706 "===================================================");
2707 }
2708 }
2709
2710 Message msg = obtainMessage(DISPATCH_KEY);
2711 msg.obj = event;
2712
2713 if (LOCAL_LOGV) Log.v(
2714 "ViewRoot", "sending key " + event + " to " + mView);
2715
2716 sendMessageAtTime(msg, event.getEventTime());
2717 }
2718
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002719 public void dispatchPointer(MotionEvent event, long eventTime,
2720 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 Message msg = obtainMessage(DISPATCH_POINTER);
2722 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002723 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 sendMessageAtTime(msg, eventTime);
2725 }
2726
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002727 public void dispatchTrackball(MotionEvent event, long eventTime,
2728 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2730 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002731 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 sendMessageAtTime(msg, eventTime);
2733 }
2734
2735 public void dispatchAppVisibility(boolean visible) {
2736 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2737 msg.arg1 = visible ? 1 : 0;
2738 sendMessage(msg);
2739 }
2740
2741 public void dispatchGetNewSurface() {
2742 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2743 sendMessage(msg);
2744 }
2745
2746 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2747 Message msg = Message.obtain();
2748 msg.what = WINDOW_FOCUS_CHANGED;
2749 msg.arg1 = hasFocus ? 1 : 0;
2750 msg.arg2 = inTouchMode ? 1 : 0;
2751 sendMessage(msg);
2752 }
2753
Dianne Hackbornffa42482009-09-23 22:20:11 -07002754 public void dispatchCloseSystemDialogs(String reason) {
2755 Message msg = Message.obtain();
2756 msg.what = CLOSE_SYSTEM_DIALOGS;
2757 msg.obj = reason;
2758 sendMessage(msg);
2759 }
2760
svetoslavganov75986cf2009-05-14 22:28:01 -07002761 /**
2762 * The window is getting focus so if there is anything focused/selected
2763 * send an {@link AccessibilityEvent} to announce that.
2764 */
2765 private void sendAccessibilityEvents() {
2766 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2767 return;
2768 }
2769 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2770 View focusedView = mView.findFocus();
2771 if (focusedView != null && focusedView != mView) {
2772 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2773 }
2774 }
2775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 public boolean showContextMenuForChild(View originalView) {
2777 return false;
2778 }
2779
2780 public void createContextMenu(ContextMenu menu) {
2781 }
2782
2783 public void childDrawableStateChanged(View child) {
2784 }
2785
2786 protected Rect getWindowFrame() {
2787 return mWinFrame;
2788 }
2789
2790 void checkThread() {
2791 if (mThread != Thread.currentThread()) {
2792 throw new CalledFromWrongThreadException(
2793 "Only the original thread that created a view hierarchy can touch its views.");
2794 }
2795 }
2796
2797 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2798 // ViewRoot never intercepts touch event, so this can be a no-op
2799 }
2800
2801 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2802 boolean immediate) {
2803 return scrollToRectOrFocus(rectangle, immediate);
2804 }
Romain Guy8506ab42009-06-11 17:35:47 -07002805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 static class InputMethodCallback extends IInputMethodCallback.Stub {
2807 private WeakReference<ViewRoot> mViewRoot;
2808
2809 public InputMethodCallback(ViewRoot viewRoot) {
2810 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2811 }
Romain Guy8506ab42009-06-11 17:35:47 -07002812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 public void finishedEvent(int seq, boolean handled) {
2814 final ViewRoot viewRoot = mViewRoot.get();
2815 if (viewRoot != null) {
2816 viewRoot.dispatchFinishedEvent(seq, handled);
2817 }
2818 }
2819
2820 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2821 // Stub -- not for use in the client.
2822 }
2823 }
Romain Guy8506ab42009-06-11 17:35:47 -07002824
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002825 static class EventCompletion extends Handler {
2826 final IWindow mWindow;
2827 final KeyEvent mKeyEvent;
2828 final boolean mIsPointer;
2829 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002830
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002831 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2832 boolean isPointer, MotionEvent motion) {
2833 super(looper);
2834 mWindow = window;
2835 mKeyEvent = key;
2836 mIsPointer = isPointer;
2837 mMotionEvent = motion;
2838 sendEmptyMessage(0);
2839 }
Romain Guy8506ab42009-06-11 17:35:47 -07002840
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002841 @Override
2842 public void handleMessage(Message msg) {
2843 if (mKeyEvent != null) {
2844 try {
2845 sWindowSession.finishKey(mWindow);
2846 } catch (RemoteException e) {
2847 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002848 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002849 boolean didFinish;
2850 MotionEvent event = mMotionEvent;
2851 if (event == null) {
2852 try {
2853 event = sWindowSession.getPendingPointerMove(mWindow);
2854 } catch (RemoteException e) {
2855 }
2856 didFinish = true;
2857 } else {
2858 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2859 }
2860 if (!didFinish) {
2861 try {
2862 sWindowSession.finishKey(mWindow);
2863 } catch (RemoteException e) {
2864 }
2865 }
2866 } else {
2867 MotionEvent event = mMotionEvent;
2868 if (event == null) {
2869 try {
2870 event = sWindowSession.getPendingTrackballMove(mWindow);
2871 } catch (RemoteException e) {
2872 }
2873 } else {
2874 try {
2875 sWindowSession.finishKey(mWindow);
2876 } catch (RemoteException e) {
2877 }
2878 }
2879 }
2880 }
2881 }
Romain Guy8506ab42009-06-11 17:35:47 -07002882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002884 private final WeakReference<ViewRoot> mViewRoot;
2885 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002887 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002889 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 }
2891
2892 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002893 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 final ViewRoot viewRoot = mViewRoot.get();
2895 if (viewRoot != null) {
2896 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002897 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 }
2899 }
2900
2901 public void dispatchKey(KeyEvent event) {
2902 final ViewRoot viewRoot = mViewRoot.get();
2903 if (viewRoot != null) {
2904 viewRoot.dispatchKey(event);
2905 } else {
2906 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002907 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 }
2909 }
2910
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002911 public void dispatchPointer(MotionEvent event, long eventTime,
2912 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002914 if (viewRoot != null) {
2915 if (MEASURE_LATENCY) {
2916 // Note: eventTime is in milliseconds
2917 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2918 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002919 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002920 } else {
2921 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 }
2923 }
2924
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002925 public void dispatchTrackball(MotionEvent event, long eventTime,
2926 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 final ViewRoot viewRoot = mViewRoot.get();
2928 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002929 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002930 } else {
2931 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 }
2933 }
2934
2935 public void dispatchAppVisibility(boolean visible) {
2936 final ViewRoot viewRoot = mViewRoot.get();
2937 if (viewRoot != null) {
2938 viewRoot.dispatchAppVisibility(visible);
2939 }
2940 }
2941
2942 public void dispatchGetNewSurface() {
2943 final ViewRoot viewRoot = mViewRoot.get();
2944 if (viewRoot != null) {
2945 viewRoot.dispatchGetNewSurface();
2946 }
2947 }
2948
2949 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2950 final ViewRoot viewRoot = mViewRoot.get();
2951 if (viewRoot != null) {
2952 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2953 }
2954 }
2955
2956 private static int checkCallingPermission(String permission) {
2957 if (!Process.supportsProcesses()) {
2958 return PackageManager.PERMISSION_GRANTED;
2959 }
2960
2961 try {
2962 return ActivityManagerNative.getDefault().checkPermission(
2963 permission, Binder.getCallingPid(), Binder.getCallingUid());
2964 } catch (RemoteException e) {
2965 return PackageManager.PERMISSION_DENIED;
2966 }
2967 }
2968
2969 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2970 final ViewRoot viewRoot = mViewRoot.get();
2971 if (viewRoot != null) {
2972 final View view = viewRoot.mView;
2973 if (view != null) {
2974 if (checkCallingPermission(Manifest.permission.DUMP) !=
2975 PackageManager.PERMISSION_GRANTED) {
2976 throw new SecurityException("Insufficient permissions to invoke"
2977 + " executeCommand() from pid=" + Binder.getCallingPid()
2978 + ", uid=" + Binder.getCallingUid());
2979 }
2980
2981 OutputStream clientStream = null;
2982 try {
2983 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2984 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2985 } catch (IOException e) {
2986 e.printStackTrace();
2987 } finally {
2988 if (clientStream != null) {
2989 try {
2990 clientStream.close();
2991 } catch (IOException e) {
2992 e.printStackTrace();
2993 }
2994 }
2995 }
2996 }
2997 }
2998 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002999
Dianne Hackbornffa42482009-09-23 22:20:11 -07003000 public void closeSystemDialogs(String reason) {
3001 final ViewRoot viewRoot = mViewRoot.get();
3002 if (viewRoot != null) {
3003 viewRoot.dispatchCloseSystemDialogs(reason);
3004 }
3005 }
3006
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003007 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3008 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003009 if (sync) {
3010 try {
3011 sWindowSession.wallpaperOffsetsComplete(asBinder());
3012 } catch (RemoteException e) {
3013 }
3014 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003015 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003016
3017 public void dispatchWallpaperCommand(String action, int x, int y,
3018 int z, Bundle extras, boolean sync) {
3019 if (sync) {
3020 try {
3021 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3022 } catch (RemoteException e) {
3023 }
3024 }
3025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 }
3027
3028 /**
3029 * Maintains state information for a single trackball axis, generating
3030 * discrete (DPAD) movements based on raw trackball motion.
3031 */
3032 static final class TrackballAxis {
3033 /**
3034 * The maximum amount of acceleration we will apply.
3035 */
3036 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 /**
3039 * The maximum amount of time (in milliseconds) between events in order
3040 * for us to consider the user to be doing fast trackball movements,
3041 * and thus apply an acceleration.
3042 */
3043 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 /**
3046 * Scaling factor to the time (in milliseconds) between events to how
3047 * much to multiple/divide the current acceleration. When movement
3048 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3049 * FAST_MOVE_TIME it divides it.
3050 */
3051 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 float position;
3054 float absPosition;
3055 float acceleration = 1;
3056 long lastMoveTime = 0;
3057 int step;
3058 int dir;
3059 int nonAccelMovement;
3060
3061 void reset(int _step) {
3062 position = 0;
3063 acceleration = 1;
3064 lastMoveTime = 0;
3065 step = _step;
3066 dir = 0;
3067 }
3068
3069 /**
3070 * Add trackball movement into the state. If the direction of movement
3071 * has been reversed, the state is reset before adding the
3072 * movement (so that you don't have to compensate for any previously
3073 * collected movement before see the result of the movement in the
3074 * new direction).
3075 *
3076 * @return Returns the absolute value of the amount of movement
3077 * collected so far.
3078 */
3079 float collect(float off, long time, String axis) {
3080 long normTime;
3081 if (off > 0) {
3082 normTime = (long)(off * FAST_MOVE_TIME);
3083 if (dir < 0) {
3084 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3085 position = 0;
3086 step = 0;
3087 acceleration = 1;
3088 lastMoveTime = 0;
3089 }
3090 dir = 1;
3091 } else if (off < 0) {
3092 normTime = (long)((-off) * FAST_MOVE_TIME);
3093 if (dir > 0) {
3094 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3095 position = 0;
3096 step = 0;
3097 acceleration = 1;
3098 lastMoveTime = 0;
3099 }
3100 dir = -1;
3101 } else {
3102 normTime = 0;
3103 }
Romain Guy8506ab42009-06-11 17:35:47 -07003104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 // The number of milliseconds between each movement that is
3106 // considered "normal" and will not result in any acceleration
3107 // or deceleration, scaled by the offset we have here.
3108 if (normTime > 0) {
3109 long delta = time - lastMoveTime;
3110 lastMoveTime = time;
3111 float acc = acceleration;
3112 if (delta < normTime) {
3113 // The user is scrolling rapidly, so increase acceleration.
3114 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3115 if (scale > 1) acc *= scale;
3116 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3117 + off + " normTime=" + normTime + " delta=" + delta
3118 + " scale=" + scale + " acc=" + acc);
3119 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3120 } else {
3121 // The user is scrolling slowly, so decrease acceleration.
3122 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3123 if (scale > 1) acc /= scale;
3124 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3125 + off + " normTime=" + normTime + " delta=" + delta
3126 + " scale=" + scale + " acc=" + acc);
3127 acceleration = acc > 1 ? acc : 1;
3128 }
3129 }
3130 position += off;
3131 return (absPosition = Math.abs(position));
3132 }
3133
3134 /**
3135 * Generate the number of discrete movement events appropriate for
3136 * the currently collected trackball movement.
3137 *
3138 * @param precision The minimum movement required to generate the
3139 * first discrete movement.
3140 *
3141 * @return Returns the number of discrete movements, either positive
3142 * or negative, or 0 if there is not enough trackball movement yet
3143 * for a discrete movement.
3144 */
3145 int generate(float precision) {
3146 int movement = 0;
3147 nonAccelMovement = 0;
3148 do {
3149 final int dir = position >= 0 ? 1 : -1;
3150 switch (step) {
3151 // If we are going to execute the first step, then we want
3152 // to do this as soon as possible instead of waiting for
3153 // a full movement, in order to make things look responsive.
3154 case 0:
3155 if (absPosition < precision) {
3156 return movement;
3157 }
3158 movement += dir;
3159 nonAccelMovement += dir;
3160 step = 1;
3161 break;
3162 // If we have generated the first movement, then we need
3163 // to wait for the second complete trackball motion before
3164 // generating the second discrete movement.
3165 case 1:
3166 if (absPosition < 2) {
3167 return movement;
3168 }
3169 movement += dir;
3170 nonAccelMovement += dir;
3171 position += dir > 0 ? -2 : 2;
3172 absPosition = Math.abs(position);
3173 step = 2;
3174 break;
3175 // After the first two, we generate discrete movements
3176 // consistently with the trackball, applying an acceleration
3177 // if the trackball is moving quickly. This is a simple
3178 // acceleration on top of what we already compute based
3179 // on how quickly the wheel is being turned, to apply
3180 // a longer increasing acceleration to continuous movement
3181 // in one direction.
3182 default:
3183 if (absPosition < 1) {
3184 return movement;
3185 }
3186 movement += dir;
3187 position += dir >= 0 ? -1 : 1;
3188 absPosition = Math.abs(position);
3189 float acc = acceleration;
3190 acc *= 1.1f;
3191 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3192 break;
3193 }
3194 } while (true);
3195 }
3196 }
3197
3198 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3199 public CalledFromWrongThreadException(String msg) {
3200 super(msg);
3201 }
3202 }
3203
3204 private SurfaceHolder mHolder = new SurfaceHolder() {
3205 // we only need a SurfaceHolder for opengl. it would be nice
3206 // to implement everything else though, especially the callback
3207 // support (opengl doesn't make use of it right now, but eventually
3208 // will).
3209 public Surface getSurface() {
3210 return mSurface;
3211 }
3212
3213 public boolean isCreating() {
3214 return false;
3215 }
3216
3217 public void addCallback(Callback callback) {
3218 }
3219
3220 public void removeCallback(Callback callback) {
3221 }
3222
3223 public void setFixedSize(int width, int height) {
3224 }
3225
3226 public void setSizeFromLayout() {
3227 }
3228
3229 public void setFormat(int format) {
3230 }
3231
3232 public void setType(int type) {
3233 }
3234
3235 public void setKeepScreenOn(boolean screenOn) {
3236 }
3237
3238 public Canvas lockCanvas() {
3239 return null;
3240 }
3241
3242 public Canvas lockCanvas(Rect dirty) {
3243 return null;
3244 }
3245
3246 public void unlockCanvasAndPost(Canvas canvas) {
3247 }
3248 public Rect getSurfaceFrame() {
3249 return null;
3250 }
3251 };
3252
3253 static RunQueue getRunQueue() {
3254 RunQueue rq = sRunQueues.get();
3255 if (rq != null) {
3256 return rq;
3257 }
3258 rq = new RunQueue();
3259 sRunQueues.set(rq);
3260 return rq;
3261 }
Romain Guy8506ab42009-06-11 17:35:47 -07003262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 /**
3264 * @hide
3265 */
3266 static final class RunQueue {
3267 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3268
3269 void post(Runnable action) {
3270 postDelayed(action, 0);
3271 }
3272
3273 void postDelayed(Runnable action, long delayMillis) {
3274 HandlerAction handlerAction = new HandlerAction();
3275 handlerAction.action = action;
3276 handlerAction.delay = delayMillis;
3277
3278 synchronized (mActions) {
3279 mActions.add(handlerAction);
3280 }
3281 }
3282
3283 void removeCallbacks(Runnable action) {
3284 final HandlerAction handlerAction = new HandlerAction();
3285 handlerAction.action = action;
3286
3287 synchronized (mActions) {
3288 final ArrayList<HandlerAction> actions = mActions;
3289
3290 while (actions.remove(handlerAction)) {
3291 // Keep going
3292 }
3293 }
3294 }
3295
3296 void executeActions(Handler handler) {
3297 synchronized (mActions) {
3298 final ArrayList<HandlerAction> actions = mActions;
3299 final int count = actions.size();
3300
3301 for (int i = 0; i < count; i++) {
3302 final HandlerAction handlerAction = actions.get(i);
3303 handler.postDelayed(handlerAction.action, handlerAction.delay);
3304 }
3305
Romain Guy15df6702009-08-17 20:17:30 -07003306 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 }
3308 }
3309
3310 private static class HandlerAction {
3311 Runnable action;
3312 long delay;
3313
3314 @Override
3315 public boolean equals(Object o) {
3316 if (this == o) return true;
3317 if (o == null || getClass() != o.getClass()) return false;
3318
3319 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 return !(action != null ? !action.equals(that.action) : that.action != null);
3321
3322 }
3323
3324 @Override
3325 public int hashCode() {
3326 int result = action != null ? action.hashCode() : 0;
3327 result = 31 * result + (int) (delay ^ (delay >>> 32));
3328 return result;
3329 }
3330 }
3331 }
3332
3333 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3334
3335 // inform skia to just abandon its texture cache IDs
3336 // doesn't call glDeleteTextures
3337 private static native void nativeAbandonGlCaches();
3338}