blob: c2c57bb00cc6b0f538ed0774a8a827b9da2674d3 [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;
Romain Guy2d4cff62010-04-09 15:39:00 -0700769 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 } 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
Romain Guy2e4f4262010-04-06 11:07:52 -0700855 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
856 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
857 frame.width() < desiredWindowWidth && frame.width() != mWidth)
858 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
859 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
861 final boolean computesInternalInsets =
862 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
863 boolean insetsPending = false;
864 int relayoutResult = 0;
865 if (mFirst || windowShouldResize || insetsChanged
866 || viewVisibilityChanged || params != null) {
867
868 if (viewVisibility == View.VISIBLE) {
869 // If this window is giving internal insets to the window
870 // manager, and it is being added or changing its visibility,
871 // then we want to first give the window manager "fake"
872 // insets to cause it to effectively ignore the content of
873 // the window during layout. This avoids it briefly causing
874 // other windows to resize/move based on the raw frame of the
875 // window, waiting until we can finish laying out this window
876 // and get back to the window manager with the ultimately
877 // computed insets.
878 insetsPending = computesInternalInsets
879 && (mFirst || viewVisibilityChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 if (mWindowAttributes.memoryType == WindowManager.LayoutParams.MEMORY_TYPE_GPU) {
882 if (params == null) {
883 params = mWindowAttributes;
884 }
885 mGlWanted = true;
886 }
887 }
888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 boolean initialized = false;
890 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700891 boolean visibleInsetsChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 try {
893 boolean hadSurface = mSurface.isValid();
894 int fl = 0;
895 if (params != null) {
896 fl = params.flags;
897 if (attachInfo.mKeepScreenOn) {
898 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
899 }
900 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700901 if (DEBUG_LAYOUT) {
902 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
903 host.mMeasuredHeight + ", params=" + params);
904 }
905 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 if (params != null) {
908 params.flags = fl;
909 }
910
911 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
912 + " content=" + mPendingContentInsets.toShortString()
913 + " visible=" + mPendingVisibleInsets.toShortString()
914 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700915
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700916 if (mPendingConfiguration.seq != 0) {
917 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
918 + mPendingConfiguration);
919 updateConfiguration(mPendingConfiguration, !mFirst);
920 mPendingConfiguration.seq = 0;
921 }
922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 contentInsetsChanged = !mPendingContentInsets.equals(
924 mAttachInfo.mContentInsets);
925 visibleInsetsChanged = !mPendingVisibleInsets.equals(
926 mAttachInfo.mVisibleInsets);
927 if (contentInsetsChanged) {
928 mAttachInfo.mContentInsets.set(mPendingContentInsets);
929 host.fitSystemWindows(mAttachInfo.mContentInsets);
930 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
931 + mAttachInfo.mContentInsets);
932 }
933 if (visibleInsetsChanged) {
934 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
935 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
936 + mAttachInfo.mVisibleInsets);
937 }
938
939 if (!hadSurface) {
940 if (mSurface.isValid()) {
941 // If we are creating a new surface, then we need to
942 // completely redraw it. Also, when we get to the
943 // point of drawing it we will hold off and schedule
944 // a new traversal instead. This is so we can tell the
945 // window manager about all of the windows being displayed
946 // before actually drawing them, so it can display then
947 // all at once.
948 newSurface = true;
949 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700950 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 if (mGlWanted && !mUseGL) {
953 initializeGL();
954 initialized = mGlCanvas != null;
955 }
956 }
957 } else if (!mSurface.isValid()) {
958 // If the surface has been removed, then reset the scroll
959 // positions.
960 mLastScrolledFocus = null;
961 mScrollY = mCurScrollY = 0;
962 if (mScroller != null) {
963 mScroller.abortAnimation();
964 }
965 }
966 } catch (RemoteException e) {
967 }
968 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700969 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970
971 attachInfo.mWindowLeft = frame.left;
972 attachInfo.mWindowTop = frame.top;
973
974 // !!FIXME!! This next section handles the case where we did not get the
975 // window size we asked for. We should avoid this by getting a maximum size from
976 // the window session beforehand.
977 mWidth = frame.width();
978 mHeight = frame.height();
979
980 if (initialized) {
Mitsuru Oshima61324e52009-07-21 15:40:36 -0700981 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
982 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 }
984
985 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700986 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
988 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
989 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
990 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
991
992 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
993 + mWidth + " measuredWidth=" + host.mMeasuredWidth
994 + " mHeight=" + mHeight
995 + " measuredHeight" + host.mMeasuredHeight
996 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 // Ask host how big it wants to be
999 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1000
1001 // Implementation of weights from WindowManager.LayoutParams
1002 // We just grow the dimensions as needed and re-measure if
1003 // needs be
1004 int width = host.mMeasuredWidth;
1005 int height = host.mMeasuredHeight;
1006 boolean measureAgain = false;
1007
1008 if (lp.horizontalWeight > 0.0f) {
1009 width += (int) ((mWidth - width) * lp.horizontalWeight);
1010 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1011 MeasureSpec.EXACTLY);
1012 measureAgain = true;
1013 }
1014 if (lp.verticalWeight > 0.0f) {
1015 height += (int) ((mHeight - height) * lp.verticalWeight);
1016 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1017 MeasureSpec.EXACTLY);
1018 measureAgain = true;
1019 }
1020
1021 if (measureAgain) {
1022 if (DEBUG_LAYOUT) Log.v(TAG,
1023 "And hey let's measure once more: width=" + width
1024 + " height=" + height);
1025 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1026 }
1027
1028 mLayoutRequested = true;
1029 }
1030 }
1031
1032 final boolean didLayout = mLayoutRequested;
1033 boolean triggerGlobalLayoutListener = didLayout
1034 || attachInfo.mRecomputeGlobalAttributes;
1035 if (didLayout) {
1036 mLayoutRequested = false;
1037 mScrollMayChange = true;
1038 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1039 "ViewRoot", "Laying out " + host + " to (" +
1040 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001041 long startTime = 0L;
1042 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 startTime = SystemClock.elapsedRealtime();
1044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1046
Romain Guy13922e02009-05-12 17:56:14 -07001047 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1048 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1049 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1050 + "please refer to the logs with the tag "
1051 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1052 }
1053 }
1054
1055 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1057 }
1058
1059 // By this point all views have been sized and positionned
1060 // We can compute the transparent area
1061
1062 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1063 // start out transparent
1064 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1065 host.getLocationInWindow(mTmpLocation);
1066 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1067 mTmpLocation[0] + host.mRight - host.mLeft,
1068 mTmpLocation[1] + host.mBottom - host.mTop);
1069
1070 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001071 if (mTranslator != null) {
1072 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1073 }
1074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1076 mPreviousTransparentRegion.set(mTransparentRegion);
1077 // reconfigure window manager
1078 try {
1079 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1080 } catch (RemoteException e) {
1081 }
1082 }
1083 }
1084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 if (DBG) {
1086 System.out.println("======================================");
1087 System.out.println("performTraversals -- after setFrame");
1088 host.debug();
1089 }
1090 }
1091
1092 if (triggerGlobalLayoutListener) {
1093 attachInfo.mRecomputeGlobalAttributes = false;
1094 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1095 }
1096
1097 if (computesInternalInsets) {
1098 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1099 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1100 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1101 givenContent.left = givenContent.top = givenContent.right
1102 = givenContent.bottom = givenVisible.left = givenVisible.top
1103 = givenVisible.right = givenVisible.bottom = 0;
1104 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001105 Rect contentInsets = insets.contentInsets;
1106 Rect visibleInsets = insets.visibleInsets;
1107 if (mTranslator != null) {
1108 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1109 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1112 mLastGivenInsets.set(insets);
1113 try {
1114 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001115 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 } catch (RemoteException e) {
1117 }
1118 }
1119 }
Romain Guy8506ab42009-06-11 17:35:47 -07001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (mFirst) {
1122 // handle first focus request
1123 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1124 + mView.hasFocus());
1125 if (mView != null) {
1126 if (!mView.hasFocus()) {
1127 mView.requestFocus(View.FOCUS_FORWARD);
1128 mFocusedView = mRealFocusedView = mView.findFocus();
1129 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1130 + mFocusedView);
1131 } else {
1132 mRealFocusedView = mView.findFocus();
1133 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1134 + mRealFocusedView);
1135 }
1136 }
1137 }
1138
1139 mFirst = false;
1140 mWillDrawSoon = false;
1141 mNewSurfaceNeeded = false;
1142 mViewVisibility = viewVisibility;
1143
1144 if (mAttachInfo.mHasWindowFocus) {
1145 final boolean imTarget = WindowManager.LayoutParams
1146 .mayUseInputMethod(mWindowAttributes.flags);
1147 if (imTarget != mLastWasImTarget) {
1148 mLastWasImTarget = imTarget;
1149 InputMethodManager imm = InputMethodManager.peekInstance();
1150 if (imm != null && imTarget) {
1151 imm.startGettingWindowFocus(mView);
1152 imm.onWindowFocus(mView, mView.findFocus(),
1153 mWindowAttributes.softInputMode,
1154 !mHasHadWindowFocus, mWindowAttributes.flags);
1155 }
1156 }
1157 }
Romain Guy8506ab42009-06-11 17:35:47 -07001158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1160
1161 if (!cancelDraw && !newSurface) {
1162 mFullRedrawNeeded = false;
1163 draw(fullRedrawNeeded);
1164
1165 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1166 || mReportNextDraw) {
1167 if (LOCAL_LOGV) {
1168 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1169 }
1170 mReportNextDraw = false;
1171 try {
1172 sWindowSession.finishDrawing(mWindow);
1173 } catch (RemoteException e) {
1174 }
1175 }
1176 } else {
1177 // We were supposed to report when we are done drawing. Since we canceled the
1178 // draw, remember it here.
1179 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1180 mReportNextDraw = true;
1181 }
1182 if (fullRedrawNeeded) {
1183 mFullRedrawNeeded = true;
1184 }
1185 // Try again
1186 scheduleTraversals();
1187 }
1188 }
1189
1190 public void requestTransparentRegion(View child) {
1191 // the test below should not fail unless someone is messing with us
1192 checkThread();
1193 if (mView == child) {
1194 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1195 // Need to make sure we re-evaluate the window attributes next
1196 // time around, to ensure the window has the correct format.
1197 mWindowAttributesChanged = true;
1198 }
1199 }
1200
1201 /**
1202 * Figures out the measure spec for the root view in a window based on it's
1203 * layout params.
1204 *
1205 * @param windowSize
1206 * The available width or height of the window
1207 *
1208 * @param rootDimension
1209 * The layout params for one dimension (width or height) of the
1210 * window.
1211 *
1212 * @return The measure spec to use to measure the root view.
1213 */
1214 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1215 int measureSpec;
1216 switch (rootDimension) {
1217
Romain Guy980a9382010-01-08 15:06:28 -08001218 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 // Window can't resize. Force root view to be windowSize.
1220 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1221 break;
1222 case ViewGroup.LayoutParams.WRAP_CONTENT:
1223 // Window can resize. Set max size for root view.
1224 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1225 break;
1226 default:
1227 // Window wants to be an exact size. Force root view to be that size.
1228 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1229 break;
1230 }
1231 return measureSpec;
1232 }
1233
1234 private void draw(boolean fullRedrawNeeded) {
1235 Surface surface = mSurface;
1236 if (surface == null || !surface.isValid()) {
1237 return;
1238 }
1239
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001240 if (!sFirstDrawComplete) {
1241 synchronized (sFirstDrawHandlers) {
1242 sFirstDrawComplete = true;
1243 for (int i=0; i<sFirstDrawHandlers.size(); i++) {
1244 post(sFirstDrawHandlers.get(i));
1245 }
1246 }
1247 }
1248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 scrollToRectOrFocus(null, false);
1250
1251 if (mAttachInfo.mViewScrollChanged) {
1252 mAttachInfo.mViewScrollChanged = false;
1253 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1254 }
Romain Guy8506ab42009-06-11 17:35:47 -07001255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001257 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 if (scrolling) {
1259 yoff = mScroller.getCurrY();
1260 } else {
1261 yoff = mScrollY;
1262 }
1263 if (mCurScrollY != yoff) {
1264 mCurScrollY = yoff;
1265 fullRedrawNeeded = true;
1266 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001267 float appScale = mAttachInfo.mApplicationScale;
1268 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269
1270 Rect dirty = mDirty;
1271 if (mUseGL) {
1272 if (!dirty.isEmpty()) {
1273 Canvas canvas = mGlCanvas;
Romain Guy5bcdff42009-05-14 21:27:18 -07001274 if (mGL != null && canvas != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 mGL.glDisable(GL_SCISSOR_TEST);
1276 mGL.glClearColor(0, 0, 0, 0);
1277 mGL.glClear(GL_COLOR_BUFFER_BIT);
1278 mGL.glEnable(GL_SCISSOR_TEST);
1279
1280 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
Romain Guy5bcdff42009-05-14 21:27:18 -07001281 mAttachInfo.mIgnoreDirtyState = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 mView.mPrivateFlags |= View.DRAWN;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001283
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001284 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1285 try {
1286 canvas.translate(0, -yoff);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001287 if (mTranslator != null) {
1288 mTranslator.translateCanvas(canvas);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001289 }
Dianne Hackborn0d221012009-07-29 15:41:19 -07001290 canvas.setScreenDensity(scalingRequired
1291 ? DisplayMetrics.DENSITY_DEVICE : 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001292 mView.draw(canvas);
Romain Guy13922e02009-05-12 17:56:14 -07001293 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1294 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1295 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001296 } finally {
1297 canvas.restoreToCount(saveCount);
1298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299
Romain Guy5bcdff42009-05-14 21:27:18 -07001300 mAttachInfo.mIgnoreDirtyState = false;
1301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
1303 checkEglErrors();
1304
Mike Reedfd716532009-10-12 14:42:56 -04001305 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 int now = (int)SystemClock.elapsedRealtime();
1307 if (sDrawTime != 0) {
1308 nativeShowFPS(canvas, now - sDrawTime);
1309 }
1310 sDrawTime = now;
1311 }
1312 }
1313 }
1314 if (scrolling) {
1315 mFullRedrawNeeded = true;
1316 scheduleTraversals();
1317 }
1318 return;
1319 }
1320
Romain Guy5bcdff42009-05-14 21:27:18 -07001321 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001322 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001323 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325
1326 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1327 Log.v("ViewRoot", "Draw " + mView + "/"
1328 + mWindowAttributes.getTitle()
1329 + ": dirty={" + dirty.left + "," + dirty.top
1330 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001331 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1332 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
1334
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001335 if (!dirty.isEmpty() || mIsAnimating) {
1336 Canvas canvas;
1337 try {
1338 int left = dirty.left;
1339 int top = dirty.top;
1340 int right = dirty.right;
1341 int bottom = dirty.bottom;
1342 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001343
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001344 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1345 bottom != dirty.bottom) {
1346 mAttachInfo.mIgnoreDirtyState = true;
1347 }
1348
1349 // TODO: Do this in native
1350 canvas.setDensity(mDensity);
1351 } catch (Surface.OutOfResourcesException e) {
1352 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1353 // TODO: we should ask the window manager to do something!
1354 // for now we just do nothing
1355 return;
1356 } catch (IllegalArgumentException e) {
1357 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1358 // TODO: we should ask the window manager to do something!
1359 // for now we just do nothing
1360 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001361 }
1362
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001363 try {
1364 if (!dirty.isEmpty() || mIsAnimating) {
1365 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001367 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1368 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1369 + canvas.getWidth() + ", h=" + canvas.getHeight());
1370 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001373 if (Config.DEBUG && ViewDebug.profileDrawing) {
1374 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001376
1377 // If this bitmap's format includes an alpha channel, we
1378 // need to clear it before drawing so that the child will
1379 // properly re-composite its drawing on a transparent
1380 // background. This automatically respects the clip/dirty region
1381 // or
1382 // If we are applying an offset, we need to clear the area
1383 // where the offset doesn't appear to avoid having garbage
1384 // left in the blank areas.
1385 if (!canvas.isOpaque() || yoff != 0) {
1386 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1387 }
1388
1389 dirty.setEmpty();
1390 mIsAnimating = false;
1391 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1392 mView.mPrivateFlags |= View.DRAWN;
1393
1394 if (DEBUG_DRAW) {
1395 Context cxt = mView.getContext();
1396 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1397 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1398 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1399 }
1400 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1401 try {
1402 canvas.translate(0, -yoff);
1403 if (mTranslator != null) {
1404 mTranslator.translateCanvas(canvas);
1405 }
1406 canvas.setScreenDensity(scalingRequired
1407 ? DisplayMetrics.DENSITY_DEVICE : 0);
1408 mView.draw(canvas);
1409 } finally {
1410 mAttachInfo.mIgnoreDirtyState = false;
1411 canvas.restoreToCount(saveCount);
1412 }
1413
1414 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1415 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1416 }
1417
1418 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1419 int now = (int)SystemClock.elapsedRealtime();
1420 if (sDrawTime != 0) {
1421 nativeShowFPS(canvas, now - sDrawTime);
1422 }
1423 sDrawTime = now;
1424 }
1425
1426 if (Config.DEBUG && ViewDebug.profileDrawing) {
1427 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001431 } finally {
1432 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435
1436 if (LOCAL_LOGV) {
1437 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1438 }
Romain Guy8506ab42009-06-11 17:35:47 -07001439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 if (scrolling) {
1441 mFullRedrawNeeded = true;
1442 scheduleTraversals();
1443 }
1444 }
1445
1446 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1447 final View.AttachInfo attachInfo = mAttachInfo;
1448 final Rect ci = attachInfo.mContentInsets;
1449 final Rect vi = attachInfo.mVisibleInsets;
1450 int scrollY = 0;
1451 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 if (vi.left > ci.left || vi.top > ci.top
1454 || vi.right > ci.right || vi.bottom > ci.bottom) {
1455 // We'll assume that we aren't going to change the scroll
1456 // offset, since we want to avoid that unless it is actually
1457 // going to make the focus visible... otherwise we scroll
1458 // all over the place.
1459 scrollY = mScrollY;
1460 // We can be called for two different situations: during a draw,
1461 // to update the scroll position if the focus has changed (in which
1462 // case 'rectangle' is null), or in response to a
1463 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1464 // is non-null and we just want to scroll to whatever that
1465 // rectangle is).
1466 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001467
1468 // When in touch mode, focus points to the previously focused view,
1469 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001470 // line checks whether the view is still in our hierarchy.
1471 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001472 mRealFocusedView = null;
1473 return false;
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 if (focus != mLastScrolledFocus) {
1477 // If the focus has changed, then ignore any requests to scroll
1478 // to a rectangle; first we want to make sure the entire focus
1479 // view is visible.
1480 rectangle = null;
1481 }
1482 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1483 + " rectangle=" + rectangle + " ci=" + ci
1484 + " vi=" + vi);
1485 if (focus == mLastScrolledFocus && !mScrollMayChange
1486 && rectangle == null) {
1487 // Optimization: if the focus hasn't changed since last
1488 // time, and no layout has happened, then just leave things
1489 // as they are.
1490 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1491 + mScrollY + " vi=" + vi.toShortString());
1492 } else if (focus != null) {
1493 // We need to determine if the currently focused view is
1494 // within the visible part of the window and, if not, apply
1495 // a pan so it can be seen.
1496 mLastScrolledFocus = focus;
1497 mScrollMayChange = false;
1498 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1499 // Try to find the rectangle from the focus view.
1500 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1501 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1502 + mView.getWidth() + " h=" + mView.getHeight()
1503 + " ci=" + ci.toShortString()
1504 + " vi=" + vi.toShortString());
1505 if (rectangle == null) {
1506 focus.getFocusedRect(mTempRect);
1507 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1508 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001509 if (mView instanceof ViewGroup) {
1510 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1511 focus, mTempRect);
1512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1514 "Focus in window: focusRect="
1515 + mTempRect.toShortString()
1516 + " visRect=" + mVisRect.toShortString());
1517 } else {
1518 mTempRect.set(rectangle);
1519 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1520 "Request scroll to rect: "
1521 + mTempRect.toShortString()
1522 + " visRect=" + mVisRect.toShortString());
1523 }
1524 if (mTempRect.intersect(mVisRect)) {
1525 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1526 "Focus window visible rect: "
1527 + mTempRect.toShortString());
1528 if (mTempRect.height() >
1529 (mView.getHeight()-vi.top-vi.bottom)) {
1530 // If the focus simply is not going to fit, then
1531 // best is probably just to leave things as-is.
1532 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1533 "Too tall; leaving scrollY=" + scrollY);
1534 } else if ((mTempRect.top-scrollY) < vi.top) {
1535 scrollY -= vi.top - (mTempRect.top-scrollY);
1536 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1537 "Top covered; scrollY=" + scrollY);
1538 } else if ((mTempRect.bottom-scrollY)
1539 > (mView.getHeight()-vi.bottom)) {
1540 scrollY += (mTempRect.bottom-scrollY)
1541 - (mView.getHeight()-vi.bottom);
1542 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1543 "Bottom covered; scrollY=" + scrollY);
1544 }
1545 handled = true;
1546 }
1547 }
1548 }
1549 }
Romain Guy8506ab42009-06-11 17:35:47 -07001550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 if (scrollY != mScrollY) {
1552 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1553 + mScrollY + " , new=" + scrollY);
1554 if (!immediate) {
1555 if (mScroller == null) {
1556 mScroller = new Scroller(mView.getContext());
1557 }
1558 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1559 } else if (mScroller != null) {
1560 mScroller.abortAnimation();
1561 }
1562 mScrollY = scrollY;
1563 }
Romain Guy8506ab42009-06-11 17:35:47 -07001564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 return handled;
1566 }
Romain Guy8506ab42009-06-11 17:35:47 -07001567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 public void requestChildFocus(View child, View focused) {
1569 checkThread();
1570 if (mFocusedView != focused) {
1571 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1572 scheduleTraversals();
1573 }
1574 mFocusedView = mRealFocusedView = focused;
1575 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1576 + mFocusedView);
1577 }
1578
1579 public void clearChildFocus(View child) {
1580 checkThread();
1581
1582 View oldFocus = mFocusedView;
1583
1584 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1585 mFocusedView = mRealFocusedView = null;
1586 if (mView != null && !mView.hasFocus()) {
1587 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1588 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1589 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1590 }
1591 } else if (oldFocus != null) {
1592 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1593 }
1594 }
1595
1596
1597 public void focusableViewAvailable(View v) {
1598 checkThread();
1599
1600 if (mView != null && !mView.hasFocus()) {
1601 v.requestFocus();
1602 } else {
1603 // the one case where will transfer focus away from the current one
1604 // is if the current view is a view group that prefers to give focus
1605 // to its children first AND the view is a descendant of it.
1606 mFocusedView = mView.findFocus();
1607 boolean descendantsHaveDibsOnFocus =
1608 (mFocusedView instanceof ViewGroup) &&
1609 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1610 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1611 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1612 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1613 v.requestFocus();
1614 }
1615 }
1616 }
1617
1618 public void recomputeViewAttributes(View child) {
1619 checkThread();
1620 if (mView == child) {
1621 mAttachInfo.mRecomputeGlobalAttributes = true;
1622 if (!mWillDrawSoon) {
1623 scheduleTraversals();
1624 }
1625 }
1626 }
1627
1628 void dispatchDetachedFromWindow() {
1629 if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
1630
1631 if (mView != null) {
1632 mView.dispatchDetachedFromWindow();
1633 }
1634
1635 mView = null;
1636 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001637 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638
1639 if (mUseGL) {
1640 destroyGL();
1641 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001642 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643
1644 try {
1645 sWindowSession.remove(mWindow);
1646 } catch (RemoteException e) {
1647 }
1648 }
Romain Guy8506ab42009-06-11 17:35:47 -07001649
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001650 void updateConfiguration(Configuration config, boolean force) {
1651 if (DEBUG_CONFIGURATION) Log.v(TAG,
1652 "Applying new config to window "
1653 + mWindowAttributes.getTitle()
1654 + ": " + config);
1655 synchronized (sConfigCallbacks) {
1656 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1657 sConfigCallbacks.get(i).onConfigurationChanged(config);
1658 }
1659 }
1660 if (mView != null) {
1661 // At this point the resources have been updated to
1662 // have the most recent config, whatever that is. Use
1663 // the on in them which may be newer.
1664 if (mView != null) {
1665 config = mView.getResources().getConfiguration();
1666 }
1667 if (force || mLastConfiguration.diff(config) != 0) {
1668 mLastConfiguration.setTo(config);
1669 mView.dispatchConfigurationChanged(config);
1670 }
1671 }
1672 }
1673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 /**
1675 * Return true if child is an ancestor of parent, (or equal to the parent).
1676 */
1677 private static boolean isViewDescendantOf(View child, View parent) {
1678 if (child == parent) {
1679 return true;
1680 }
1681
1682 final ViewParent theParent = child.getParent();
1683 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1684 }
1685
Romain Guycdb86672010-03-18 18:54:50 -07001686 private static void forceLayout(View view) {
1687 view.forceLayout();
1688 if (view instanceof ViewGroup) {
1689 ViewGroup group = (ViewGroup) view;
1690 final int count = group.getChildCount();
1691 for (int i = 0; i < count; i++) {
1692 forceLayout(group.getChildAt(i));
1693 }
1694 }
1695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696
1697 public final static int DO_TRAVERSAL = 1000;
1698 public final static int DIE = 1001;
1699 public final static int RESIZED = 1002;
1700 public final static int RESIZED_REPORT = 1003;
1701 public final static int WINDOW_FOCUS_CHANGED = 1004;
1702 public final static int DISPATCH_KEY = 1005;
1703 public final static int DISPATCH_POINTER = 1006;
1704 public final static int DISPATCH_TRACKBALL = 1007;
1705 public final static int DISPATCH_APP_VISIBILITY = 1008;
1706 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1707 public final static int FINISHED_EVENT = 1010;
1708 public final static int DISPATCH_KEY_FROM_IME = 1011;
1709 public final static int FINISH_INPUT_CONNECTION = 1012;
1710 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001711 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712
1713 @Override
1714 public void handleMessage(Message msg) {
1715 switch (msg.what) {
1716 case View.AttachInfo.INVALIDATE_MSG:
1717 ((View) msg.obj).invalidate();
1718 break;
1719 case View.AttachInfo.INVALIDATE_RECT_MSG:
1720 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1721 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1722 info.release();
1723 break;
1724 case DO_TRAVERSAL:
1725 if (mProfile) {
1726 Debug.startMethodTracing("ViewRoot");
1727 }
1728
1729 performTraversals();
1730
1731 if (mProfile) {
1732 Debug.stopMethodTracing();
1733 mProfile = false;
1734 }
1735 break;
1736 case FINISHED_EVENT:
1737 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1738 break;
1739 case DISPATCH_KEY:
1740 if (LOCAL_LOGV) Log.v(
1741 "ViewRoot", "Dispatching key "
1742 + msg.obj + " to " + mView);
1743 deliverKeyEvent((KeyEvent)msg.obj, true);
1744 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001745 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001747 boolean callWhenDone = msg.arg1 != 0;
1748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 if (event == null) {
1750 try {
Michael Chan53071d62009-05-13 17:29:48 -07001751 long timeBeforeGettingEvents;
1752 if (MEASURE_LATENCY) {
1753 timeBeforeGettingEvents = System.nanoTime();
1754 }
1755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001757
1758 if (MEASURE_LATENCY && event != null) {
1759 lt.sample("9 Client got events ", System.nanoTime() - event.getEventTimeNano());
1760 lt.sample("8 Client getting events ", timeBeforeGettingEvents - event.getEventTimeNano());
1761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 } catch (RemoteException e) {
1763 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001764 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001766 if (event != null && mTranslator != null) {
1767 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 try {
1770 boolean handled;
1771 if (mView != null && mAdded && event != null) {
1772
1773 // enter touch mode on the down
1774 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1775 if (isDown) {
1776 ensureTouchMode(true);
1777 }
1778 if(Config.LOGV) {
1779 captureMotionLog("captureDispatchPointer", event);
1780 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001781 if (mCurScrollY != 0) {
1782 event.offsetLocation(0, mCurScrollY);
1783 }
Michael Chan53071d62009-05-13 17:29:48 -07001784 if (MEASURE_LATENCY) {
1785 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
1786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001788 if (MEASURE_LATENCY) {
1789 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
1790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 if (!handled && isDown) {
1792 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1793
1794 final int edgeFlags = event.getEdgeFlags();
1795 int direction = View.FOCUS_UP;
1796 int x = (int)event.getX();
1797 int y = (int)event.getY();
1798 final int[] deltas = new int[2];
1799
1800 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1801 direction = View.FOCUS_DOWN;
1802 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1803 deltas[0] = edgeSlop;
1804 x += edgeSlop;
1805 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1806 deltas[0] = -edgeSlop;
1807 x -= edgeSlop;
1808 }
1809 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1810 direction = View.FOCUS_UP;
1811 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1812 deltas[0] = edgeSlop;
1813 x += edgeSlop;
1814 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1815 deltas[0] = -edgeSlop;
1816 x -= edgeSlop;
1817 }
1818 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1819 direction = View.FOCUS_RIGHT;
1820 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1821 direction = View.FOCUS_LEFT;
1822 }
1823
1824 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1825 View nearest = FocusFinder.getInstance().findNearestTouchable(
1826 ((ViewGroup) mView), x, y, direction, deltas);
1827 if (nearest != null) {
1828 event.offsetLocation(deltas[0], deltas[1]);
1829 event.setEdgeFlags(0);
1830 mView.dispatchTouchEvent(event);
1831 }
1832 }
1833 }
1834 }
1835 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001836 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 try {
1838 sWindowSession.finishKey(mWindow);
1839 } catch (RemoteException e) {
1840 }
1841 }
1842 if (event != null) {
1843 event.recycle();
1844 }
1845 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1846 // Let the exception fall through -- the looper will catch
1847 // it and take care of the bad app for us.
1848 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001849 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001851 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 break;
1853 case DISPATCH_APP_VISIBILITY:
1854 handleAppVisibility(msg.arg1 != 0);
1855 break;
1856 case DISPATCH_GET_NEW_SURFACE:
1857 handleGetNewSurface();
1858 break;
1859 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001860 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001863 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001864 && mPendingVisibleInsets.equals(ri.visibleInsets)
1865 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 break;
1867 }
1868 // fall through...
1869 case RESIZED_REPORT:
1870 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001871 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1872 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001873 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 mWinFrame.left = 0;
1876 mWinFrame.right = msg.arg1;
1877 mWinFrame.top = 0;
1878 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001879 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1880 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 if (msg.what == RESIZED_REPORT) {
1882 mReportNextDraw = true;
1883 }
Romain Guycdb86672010-03-18 18:54:50 -07001884
1885 if (mView != null) {
1886 forceLayout(mView);
1887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 requestLayout();
1889 }
1890 break;
1891 case WINDOW_FOCUS_CHANGED: {
1892 if (mAdded) {
1893 boolean hasWindowFocus = msg.arg1 != 0;
1894 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1895 if (hasWindowFocus) {
1896 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001897 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898
1899 if (mGlWanted) {
1900 checkEglErrors();
1901 // we lost the gl context, so recreate it.
1902 if (mGlWanted && !mUseGL) {
1903 initializeGL();
1904 if (mGlCanvas != null) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001905 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001906 mGlCanvas.setViewport(
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001907 (int) (mWidth * appScale + 0.5f),
1908 (int) (mHeight * appScale + 0.5f));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910 }
1911 }
1912 }
Romain Guy8506ab42009-06-11 17:35:47 -07001913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 mLastWasImTarget = WindowManager.LayoutParams
1915 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 InputMethodManager imm = InputMethodManager.peekInstance();
1918 if (mView != null) {
1919 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1920 imm.startGettingWindowFocus(mView);
1921 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001922 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 mView.dispatchWindowFocusChanged(hasWindowFocus);
1924 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 // Note: must be done after the focus change callbacks,
1927 // so all of the view state is set up correctly.
1928 if (hasWindowFocus) {
1929 if (imm != null && mLastWasImTarget) {
1930 imm.onWindowFocus(mView, mView.findFocus(),
1931 mWindowAttributes.softInputMode,
1932 !mHasHadWindowFocus, mWindowAttributes.flags);
1933 }
1934 // Clear the forward bit. We can just do this directly, since
1935 // the window manager doesn't care about it.
1936 mWindowAttributes.softInputMode &=
1937 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1938 ((WindowManager.LayoutParams)mView.getLayoutParams())
1939 .softInputMode &=
1940 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1941 mHasHadWindowFocus = true;
1942 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001943
1944 if (hasWindowFocus && mView != null) {
1945 sendAccessibilityEvents();
1946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
1948 } break;
1949 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001950 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001952 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 if (LOCAL_LOGV) Log.v(
1954 "ViewRoot", "Dispatching key "
1955 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001956 KeyEvent event = (KeyEvent)msg.obj;
1957 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1958 // The IME is trying to say this event is from the
1959 // system! Bad bad bad!
1960 event = KeyEvent.changeFlags(event,
1961 event.getFlags()&~KeyEvent.FLAG_FROM_SYSTEM);
1962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001964 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 case FINISH_INPUT_CONNECTION: {
1966 InputMethodManager imm = InputMethodManager.peekInstance();
1967 if (imm != null) {
1968 imm.reportFinishInputConnection((InputConnection)msg.obj);
1969 }
1970 } break;
1971 case CHECK_FOCUS: {
1972 InputMethodManager imm = InputMethodManager.peekInstance();
1973 if (imm != null) {
1974 imm.checkFocus();
1975 }
1976 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001977 case CLOSE_SYSTEM_DIALOGS: {
1978 if (mView != null) {
1979 mView.onCloseSystemDialogs((String)msg.obj);
1980 }
1981 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
1983 }
1984
1985 /**
1986 * Something in the current window tells us we need to change the touch mode. For
1987 * example, we are not in touch mode, and the user touches the screen.
1988 *
1989 * If the touch mode has changed, tell the window manager, and handle it locally.
1990 *
1991 * @param inTouchMode Whether we want to be in touch mode.
1992 * @return True if the touch mode changed and focus changed was changed as a result
1993 */
1994 boolean ensureTouchMode(boolean inTouchMode) {
1995 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1996 + "touch mode is " + mAttachInfo.mInTouchMode);
1997 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1998
1999 // tell the window manager
2000 try {
2001 sWindowSession.setInTouchMode(inTouchMode);
2002 } catch (RemoteException e) {
2003 throw new RuntimeException(e);
2004 }
2005
2006 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002007 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009
2010 /**
2011 * Ensure that the touch mode for this window is set, and if it is changing,
2012 * take the appropriate action.
2013 * @param inTouchMode Whether we want to be in touch mode.
2014 * @return True if the touch mode changed and focus changed was changed as a result
2015 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002016 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2018 + "touch mode is " + mAttachInfo.mInTouchMode);
2019
2020 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2021
2022 mAttachInfo.mInTouchMode = inTouchMode;
2023 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2024
Romain Guy2d4cff62010-04-09 15:39:00 -07002025 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027
2028 private boolean enterTouchMode() {
2029 if (mView != null) {
2030 if (mView.hasFocus()) {
2031 // note: not relying on mFocusedView here because this could
2032 // be when the window is first being added, and mFocused isn't
2033 // set yet.
2034 final View focused = mView.findFocus();
2035 if (focused != null && !focused.isFocusableInTouchMode()) {
2036
2037 final ViewGroup ancestorToTakeFocus =
2038 findAncestorToTakeFocusInTouchMode(focused);
2039 if (ancestorToTakeFocus != null) {
2040 // there is an ancestor that wants focus after its descendants that
2041 // is focusable in touch mode.. give it focus
2042 return ancestorToTakeFocus.requestFocus();
2043 } else {
2044 // nothing appropriate to have focus in touch mode, clear it out
2045 mView.unFocus();
2046 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2047 mFocusedView = null;
2048 return true;
2049 }
2050 }
2051 }
2052 }
2053 return false;
2054 }
2055
2056
2057 /**
2058 * Find an ancestor of focused that wants focus after its descendants and is
2059 * focusable in touch mode.
2060 * @param focused The currently focused view.
2061 * @return An appropriate view, or null if no such view exists.
2062 */
2063 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2064 ViewParent parent = focused.getParent();
2065 while (parent instanceof ViewGroup) {
2066 final ViewGroup vgParent = (ViewGroup) parent;
2067 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2068 && vgParent.isFocusableInTouchMode()) {
2069 return vgParent;
2070 }
2071 if (vgParent.isRootNamespace()) {
2072 return null;
2073 } else {
2074 parent = vgParent.getParent();
2075 }
2076 }
2077 return null;
2078 }
2079
2080 private boolean leaveTouchMode() {
2081 if (mView != null) {
2082 if (mView.hasFocus()) {
2083 // i learned the hard way to not trust mFocusedView :)
2084 mFocusedView = mView.findFocus();
2085 if (!(mFocusedView instanceof ViewGroup)) {
2086 // some view has focus, let it keep it
2087 return false;
2088 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2089 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2090 // some view group has focus, and doesn't prefer its children
2091 // over itself for focus, so let them keep it.
2092 return false;
2093 }
2094 }
2095
2096 // find the best view to give focus to in this brave new non-touch-mode
2097 // world
2098 final View focused = focusSearch(null, View.FOCUS_DOWN);
2099 if (focused != null) {
2100 return focused.requestFocus(View.FOCUS_DOWN);
2101 }
2102 }
2103 return false;
2104 }
2105
2106
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002107 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 if (event == null) {
2109 try {
2110 event = sWindowSession.getPendingTrackballMove(mWindow);
2111 } catch (RemoteException e) {
2112 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002113 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115
2116 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2117
2118 boolean handled = false;
2119 try {
2120 if (event == null) {
2121 handled = true;
2122 } else if (mView != null && mAdded) {
2123 handled = mView.dispatchTrackballEvent(event);
2124 if (!handled) {
2125 // we could do something here, like changing the focus
2126 // or something?
2127 }
2128 }
2129 } finally {
2130 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002131 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 try {
2133 sWindowSession.finishKey(mWindow);
2134 } catch (RemoteException e) {
2135 }
2136 }
2137 if (event != null) {
2138 event.recycle();
2139 }
2140 // If we reach this, we delivered a trackball event to mView and
2141 // mView consumed it. Because we will not translate the trackball
2142 // event into a key event, touch mode will not exit, so we exit
2143 // touch mode here.
2144 ensureTouchMode(false);
2145 //noinspection ReturnInsideFinallyBlock
2146 return;
2147 }
2148 // Let the exception fall through -- the looper will catch
2149 // it and take care of the bad app for us.
2150 }
2151
2152 final TrackballAxis x = mTrackballAxisX;
2153 final TrackballAxis y = mTrackballAxisY;
2154
2155 long curTime = SystemClock.uptimeMillis();
2156 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2157 // It has been too long since the last movement,
2158 // so restart at the beginning.
2159 x.reset(0);
2160 y.reset(0);
2161 mLastTrackballTime = curTime;
2162 }
2163
2164 try {
2165 final int action = event.getAction();
2166 final int metastate = event.getMetaState();
2167 switch (action) {
2168 case MotionEvent.ACTION_DOWN:
2169 x.reset(2);
2170 y.reset(2);
2171 deliverKeyEvent(new KeyEvent(curTime, curTime,
2172 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2173 0, metastate), false);
2174 break;
2175 case MotionEvent.ACTION_UP:
2176 x.reset(2);
2177 y.reset(2);
2178 deliverKeyEvent(new KeyEvent(curTime, curTime,
2179 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2180 0, metastate), false);
2181 break;
2182 }
2183
2184 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2185 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2186 + " move=" + event.getX()
2187 + " / Y=" + y.position + " step="
2188 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2189 + " move=" + event.getY());
2190 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2191 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2192
2193 // Generate DPAD events based on the trackball movement.
2194 // We pick the axis that has moved the most as the direction of
2195 // the DPAD. When we generate DPAD events for one axis, then the
2196 // other axis is reset -- we don't want to perform DPAD jumps due
2197 // to slight movements in the trackball when making major movements
2198 // along the other axis.
2199 int keycode = 0;
2200 int movement = 0;
2201 float accel = 1;
2202 if (xOff > yOff) {
2203 movement = x.generate((2/event.getXPrecision()));
2204 if (movement != 0) {
2205 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2206 : KeyEvent.KEYCODE_DPAD_LEFT;
2207 accel = x.acceleration;
2208 y.reset(2);
2209 }
2210 } else if (yOff > 0) {
2211 movement = y.generate((2/event.getYPrecision()));
2212 if (movement != 0) {
2213 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2214 : KeyEvent.KEYCODE_DPAD_UP;
2215 accel = y.acceleration;
2216 x.reset(2);
2217 }
2218 }
2219
2220 if (keycode != 0) {
2221 if (movement < 0) movement = -movement;
2222 int accelMovement = (int)(movement * accel);
2223 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2224 + " accelMovement=" + accelMovement
2225 + " accel=" + accel);
2226 if (accelMovement > movement) {
2227 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2228 + keycode);
2229 movement--;
2230 deliverKeyEvent(new KeyEvent(curTime, curTime,
2231 KeyEvent.ACTION_MULTIPLE, keycode,
2232 accelMovement-movement, metastate), false);
2233 }
2234 while (movement > 0) {
2235 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2236 + keycode);
2237 movement--;
2238 curTime = SystemClock.uptimeMillis();
2239 deliverKeyEvent(new KeyEvent(curTime, curTime,
2240 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2241 deliverKeyEvent(new KeyEvent(curTime, curTime,
2242 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2243 }
2244 mLastTrackballTime = curTime;
2245 }
2246 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002247 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 try {
2249 sWindowSession.finishKey(mWindow);
2250 } catch (RemoteException e) {
2251 }
2252 if (event != null) {
2253 event.recycle();
2254 }
2255 }
2256 // Let the exception fall through -- the looper will catch
2257 // it and take care of the bad app for us.
2258 }
2259 }
2260
2261 /**
2262 * @param keyCode The key code
2263 * @return True if the key is directional.
2264 */
2265 static boolean isDirectional(int keyCode) {
2266 switch (keyCode) {
2267 case KeyEvent.KEYCODE_DPAD_LEFT:
2268 case KeyEvent.KEYCODE_DPAD_RIGHT:
2269 case KeyEvent.KEYCODE_DPAD_UP:
2270 case KeyEvent.KEYCODE_DPAD_DOWN:
2271 return true;
2272 }
2273 return false;
2274 }
2275
2276 /**
2277 * Returns true if this key is a keyboard key.
2278 * @param keyEvent The key event.
2279 * @return whether this key is a keyboard key.
2280 */
2281 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2282 final int convertedKey = keyEvent.getUnicodeChar();
2283 return convertedKey > 0;
2284 }
2285
2286
2287
2288 /**
2289 * See if the key event means we should leave touch mode (and leave touch
2290 * mode if so).
2291 * @param event The key event.
2292 * @return Whether this key event should be consumed (meaning the act of
2293 * leaving touch mode alone is considered the event).
2294 */
2295 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002296 final int action = event.getAction();
2297 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 return false;
2299 }
2300 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2301 return false;
2302 }
2303
2304 // only relevant if we are in touch mode
2305 if (!mAttachInfo.mInTouchMode) {
2306 return false;
2307 }
2308
2309 // if something like an edit text has focus and the user is typing,
2310 // leave touch mode
2311 //
2312 // note: the condition of not being a keyboard key is kind of a hacky
2313 // approximation of whether we think the focused view will want the
2314 // key; if we knew for sure whether the focused view would consume
2315 // the event, that would be better.
2316 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2317 mFocusedView = mView.findFocus();
2318 if ((mFocusedView instanceof ViewGroup)
2319 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2320 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2321 // something has focus, but is holding it weakly as a container
2322 return false;
2323 }
2324 if (ensureTouchMode(false)) {
2325 throw new IllegalStateException("should not have changed focus "
2326 + "when leaving touch mode while a view has focus.");
2327 }
2328 return false;
2329 }
2330
2331 if (isDirectional(event.getKeyCode())) {
2332 // no view has focus, so we leave touch mode (and find something
2333 // to give focus to). the event is consumed if we were able to
2334 // find something to give focus to.
2335 return ensureTouchMode(false);
2336 }
2337 return false;
2338 }
2339
2340 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002341 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 */
2343 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002344 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 if (ev == null ||
2346 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2347 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
Romain Guy8506ab42009-06-11 17:35:47 -07002349
2350 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 sb.append(ev.getDownTime()).append(',');
2352 sb.append(ev.getEventTime()).append(',');
2353 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002354 sb.append(ev.getX()).append(',');
2355 sb.append(ev.getY()).append(',');
2356 sb.append(ev.getPressure()).append(',');
2357 sb.append(ev.getSize()).append(',');
2358 sb.append(ev.getMetaState()).append(',');
2359 sb.append(ev.getXPrecision()).append(',');
2360 sb.append(ev.getYPrecision()).append(',');
2361 sb.append(ev.getDeviceId()).append(',');
2362 sb.append(ev.getEdgeFlags());
2363 Log.d(TAG, sb.toString());
2364 }
2365 /**
2366 * log motion events
2367 */
2368 private static void captureKeyLog(String subTag, KeyEvent ev) {
2369 //check dynamic switch
2370 if (ev == null ||
2371 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2372 return;
2373 }
2374 StringBuilder sb = new StringBuilder(subTag + ": ");
2375 sb.append(ev.getDownTime()).append(',');
2376 sb.append(ev.getEventTime()).append(',');
2377 sb.append(ev.getAction()).append(',');
2378 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 sb.append(ev.getRepeatCount()).append(',');
2380 sb.append(ev.getMetaState()).append(',');
2381 sb.append(ev.getDeviceId()).append(',');
2382 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002383 Log.d(TAG, sb.toString());
2384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385
2386 int enqueuePendingEvent(Object event, boolean sendDone) {
2387 int seq = mPendingEventSeq+1;
2388 if (seq < 0) seq = 0;
2389 mPendingEventSeq = seq;
2390 mPendingEvents.put(seq, event);
2391 return sendDone ? seq : -seq;
2392 }
2393
2394 Object retrievePendingEvent(int seq) {
2395 if (seq < 0) seq = -seq;
2396 Object event = mPendingEvents.get(seq);
2397 if (event != null) {
2398 mPendingEvents.remove(seq);
2399 }
2400 return event;
2401 }
Romain Guy8506ab42009-06-11 17:35:47 -07002402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2404 // If mView is null, we just consume the key event because it doesn't
2405 // make sense to do anything else with it.
2406 boolean handled = mView != null
2407 ? mView.dispatchKeyEventPreIme(event) : true;
2408 if (handled) {
2409 if (sendDone) {
2410 if (LOCAL_LOGV) Log.v(
2411 "ViewRoot", "Telling window manager key is finished");
2412 try {
2413 sWindowSession.finishKey(mWindow);
2414 } catch (RemoteException e) {
2415 }
2416 }
2417 return;
2418 }
2419 // If it is possible for this window to interact with the input
2420 // method window, then we want to first dispatch our key events
2421 // to the input method.
2422 if (mLastWasImTarget) {
2423 InputMethodManager imm = InputMethodManager.peekInstance();
2424 if (imm != null && mView != null) {
2425 int seq = enqueuePendingEvent(event, sendDone);
2426 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2427 + seq + " event=" + event);
2428 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2429 mInputMethodCallback);
2430 return;
2431 }
2432 }
2433 deliverKeyEventToViewHierarchy(event, sendDone);
2434 }
2435
2436 void handleFinishedEvent(int seq, boolean handled) {
2437 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2438 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2439 + " handled=" + handled + " event=" + event);
2440 if (event != null) {
2441 final boolean sendDone = seq >= 0;
2442 if (!handled) {
2443 deliverKeyEventToViewHierarchy(event, sendDone);
2444 return;
2445 } else if (sendDone) {
2446 if (LOCAL_LOGV) Log.v(
2447 "ViewRoot", "Telling window manager key is finished");
2448 try {
2449 sWindowSession.finishKey(mWindow);
2450 } catch (RemoteException e) {
2451 }
2452 } else {
2453 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2454 + " handled=" + handled + " ev=" + event
2455 + ") neither delivering nor finishing key");
2456 }
2457 }
2458 }
Romain Guy8506ab42009-06-11 17:35:47 -07002459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2461 try {
2462 if (mView != null && mAdded) {
2463 final int action = event.getAction();
2464 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2465
2466 if (checkForLeavingTouchModeAndConsume(event)) {
2467 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002468 }
2469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 if (Config.LOGV) {
2471 captureKeyLog("captureDispatchKeyEvent", event);
2472 }
2473 boolean keyHandled = mView.dispatchKeyEvent(event);
2474
2475 if (!keyHandled && isDown) {
2476 int direction = 0;
2477 switch (event.getKeyCode()) {
2478 case KeyEvent.KEYCODE_DPAD_LEFT:
2479 direction = View.FOCUS_LEFT;
2480 break;
2481 case KeyEvent.KEYCODE_DPAD_RIGHT:
2482 direction = View.FOCUS_RIGHT;
2483 break;
2484 case KeyEvent.KEYCODE_DPAD_UP:
2485 direction = View.FOCUS_UP;
2486 break;
2487 case KeyEvent.KEYCODE_DPAD_DOWN:
2488 direction = View.FOCUS_DOWN;
2489 break;
2490 }
2491
2492 if (direction != 0) {
2493
2494 View focused = mView != null ? mView.findFocus() : null;
2495 if (focused != null) {
2496 View v = focused.focusSearch(direction);
2497 boolean focusPassed = false;
2498 if (v != null && v != focused) {
2499 // do the math the get the interesting rect
2500 // of previous focused into the coord system of
2501 // newly focused view
2502 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002503 if (mView instanceof ViewGroup) {
2504 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2505 focused, mTempRect);
2506 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2507 v, mTempRect);
2508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 focusPassed = v.requestFocus(direction, mTempRect);
2510 }
2511
2512 if (!focusPassed) {
2513 mView.dispatchUnhandledMove(focused, direction);
2514 } else {
2515 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2516 }
2517 }
2518 }
2519 }
2520 }
2521
2522 } finally {
2523 if (sendDone) {
2524 if (LOCAL_LOGV) Log.v(
2525 "ViewRoot", "Telling window manager key is finished");
2526 try {
2527 sWindowSession.finishKey(mWindow);
2528 } catch (RemoteException e) {
2529 }
2530 }
2531 // Let the exception fall through -- the looper will catch
2532 // it and take care of the bad app for us.
2533 }
2534 }
2535
2536 private AudioManager getAudioManager() {
2537 if (mView == null) {
2538 throw new IllegalStateException("getAudioManager called when there is no mView");
2539 }
2540 if (mAudioManager == null) {
2541 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2542 }
2543 return mAudioManager;
2544 }
2545
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002546 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2547 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002548
2549 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002550 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002551 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002552 restore = true;
2553 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002554 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002555 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002556 if (params != null) {
2557 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002558 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002559 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002560 int relayoutResult = sWindowSession.relayout(
2561 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002562 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2563 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002564 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002565 mPendingContentInsets, mPendingVisibleInsets,
2566 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002567 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002568 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002569 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002570
2571 if (mTranslator != null) {
2572 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2573 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2574 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002575 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002576 return relayoutResult;
2577 }
Romain Guy8506ab42009-06-11 17:35:47 -07002578
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002579 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 * {@inheritDoc}
2581 */
2582 public void playSoundEffect(int effectId) {
2583 checkThread();
2584
2585 final AudioManager audioManager = getAudioManager();
2586
2587 switch (effectId) {
2588 case SoundEffectConstants.CLICK:
2589 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2590 return;
2591 case SoundEffectConstants.NAVIGATION_DOWN:
2592 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2593 return;
2594 case SoundEffectConstants.NAVIGATION_LEFT:
2595 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2596 return;
2597 case SoundEffectConstants.NAVIGATION_RIGHT:
2598 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2599 return;
2600 case SoundEffectConstants.NAVIGATION_UP:
2601 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2602 return;
2603 default:
2604 throw new IllegalArgumentException("unknown effect id " + effectId +
2605 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2606 }
2607 }
2608
2609 /**
2610 * {@inheritDoc}
2611 */
2612 public boolean performHapticFeedback(int effectId, boolean always) {
2613 try {
2614 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2615 } catch (RemoteException e) {
2616 return false;
2617 }
2618 }
2619
2620 /**
2621 * {@inheritDoc}
2622 */
2623 public View focusSearch(View focused, int direction) {
2624 checkThread();
2625 if (!(mView instanceof ViewGroup)) {
2626 return null;
2627 }
2628 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2629 }
2630
2631 public void debug() {
2632 mView.debug();
2633 }
2634
2635 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002636 if (immediate) {
2637 doDie();
2638 } else {
2639 sendEmptyMessage(DIE);
2640 }
2641 }
2642
2643 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 checkThread();
2645 if (Config.LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
2646 synchronized (this) {
2647 if (mAdded && !mFirst) {
2648 int viewVisibility = mView.getVisibility();
2649 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2650 if (mWindowAttributesChanged || viewVisibilityChanged) {
2651 // If layout params have been changed, first give them
2652 // to the window manager to make sure it has the correct
2653 // animation info.
2654 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002655 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2656 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 sWindowSession.finishDrawing(mWindow);
2658 }
2659 } catch (RemoteException e) {
2660 }
2661 }
2662
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002663 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
2665 if (mAdded) {
2666 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002667 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 }
2669 }
2670 }
2671
2672 public void dispatchFinishedEvent(int seq, boolean handled) {
2673 Message msg = obtainMessage(FINISHED_EVENT);
2674 msg.arg1 = seq;
2675 msg.arg2 = handled ? 1 : 0;
2676 sendMessage(msg);
2677 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002680 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2682 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2683 + " visibleInsets=" + visibleInsets.toShortString()
2684 + " reportDraw=" + reportDraw);
2685 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002686 if (mTranslator != null) {
2687 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2688 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2689 w *= mTranslator.applicationInvertedScale;
2690 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002691 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002692 msg.arg1 = w;
2693 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002694 ResizedInfo ri = new ResizedInfo();
2695 ri.coveredInsets = new Rect(coveredInsets);
2696 ri.visibleInsets = new Rect(visibleInsets);
2697 ri.newConfig = newConfig;
2698 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 sendMessage(msg);
2700 }
2701
2702 public void dispatchKey(KeyEvent event) {
2703 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2704 //noinspection ConstantConditions
2705 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2706 if (Config.LOGD) Log.d("keydisp",
2707 "===================================================");
2708 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2709 debug();
2710
2711 if (Config.LOGD) Log.d("keydisp",
2712 "===================================================");
2713 }
2714 }
2715
2716 Message msg = obtainMessage(DISPATCH_KEY);
2717 msg.obj = event;
2718
2719 if (LOCAL_LOGV) Log.v(
2720 "ViewRoot", "sending key " + event + " to " + mView);
2721
2722 sendMessageAtTime(msg, event.getEventTime());
2723 }
2724
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002725 public void dispatchPointer(MotionEvent event, long eventTime,
2726 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 Message msg = obtainMessage(DISPATCH_POINTER);
2728 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002729 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 sendMessageAtTime(msg, eventTime);
2731 }
2732
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002733 public void dispatchTrackball(MotionEvent event, long eventTime,
2734 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2736 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002737 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 sendMessageAtTime(msg, eventTime);
2739 }
2740
2741 public void dispatchAppVisibility(boolean visible) {
2742 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2743 msg.arg1 = visible ? 1 : 0;
2744 sendMessage(msg);
2745 }
2746
2747 public void dispatchGetNewSurface() {
2748 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2749 sendMessage(msg);
2750 }
2751
2752 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2753 Message msg = Message.obtain();
2754 msg.what = WINDOW_FOCUS_CHANGED;
2755 msg.arg1 = hasFocus ? 1 : 0;
2756 msg.arg2 = inTouchMode ? 1 : 0;
2757 sendMessage(msg);
2758 }
2759
Dianne Hackbornffa42482009-09-23 22:20:11 -07002760 public void dispatchCloseSystemDialogs(String reason) {
2761 Message msg = Message.obtain();
2762 msg.what = CLOSE_SYSTEM_DIALOGS;
2763 msg.obj = reason;
2764 sendMessage(msg);
2765 }
2766
svetoslavganov75986cf2009-05-14 22:28:01 -07002767 /**
2768 * The window is getting focus so if there is anything focused/selected
2769 * send an {@link AccessibilityEvent} to announce that.
2770 */
2771 private void sendAccessibilityEvents() {
2772 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2773 return;
2774 }
2775 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2776 View focusedView = mView.findFocus();
2777 if (focusedView != null && focusedView != mView) {
2778 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2779 }
2780 }
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 public boolean showContextMenuForChild(View originalView) {
2783 return false;
2784 }
2785
2786 public void createContextMenu(ContextMenu menu) {
2787 }
2788
2789 public void childDrawableStateChanged(View child) {
2790 }
2791
2792 protected Rect getWindowFrame() {
2793 return mWinFrame;
2794 }
2795
2796 void checkThread() {
2797 if (mThread != Thread.currentThread()) {
2798 throw new CalledFromWrongThreadException(
2799 "Only the original thread that created a view hierarchy can touch its views.");
2800 }
2801 }
2802
2803 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2804 // ViewRoot never intercepts touch event, so this can be a no-op
2805 }
2806
2807 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2808 boolean immediate) {
2809 return scrollToRectOrFocus(rectangle, immediate);
2810 }
Romain Guy8506ab42009-06-11 17:35:47 -07002811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 static class InputMethodCallback extends IInputMethodCallback.Stub {
2813 private WeakReference<ViewRoot> mViewRoot;
2814
2815 public InputMethodCallback(ViewRoot viewRoot) {
2816 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2817 }
Romain Guy8506ab42009-06-11 17:35:47 -07002818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 public void finishedEvent(int seq, boolean handled) {
2820 final ViewRoot viewRoot = mViewRoot.get();
2821 if (viewRoot != null) {
2822 viewRoot.dispatchFinishedEvent(seq, handled);
2823 }
2824 }
2825
2826 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2827 // Stub -- not for use in the client.
2828 }
2829 }
Romain Guy8506ab42009-06-11 17:35:47 -07002830
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002831 static class EventCompletion extends Handler {
2832 final IWindow mWindow;
2833 final KeyEvent mKeyEvent;
2834 final boolean mIsPointer;
2835 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002836
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002837 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2838 boolean isPointer, MotionEvent motion) {
2839 super(looper);
2840 mWindow = window;
2841 mKeyEvent = key;
2842 mIsPointer = isPointer;
2843 mMotionEvent = motion;
2844 sendEmptyMessage(0);
2845 }
Romain Guy8506ab42009-06-11 17:35:47 -07002846
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002847 @Override
2848 public void handleMessage(Message msg) {
2849 if (mKeyEvent != null) {
2850 try {
2851 sWindowSession.finishKey(mWindow);
2852 } catch (RemoteException e) {
2853 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002854 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002855 boolean didFinish;
2856 MotionEvent event = mMotionEvent;
2857 if (event == null) {
2858 try {
2859 event = sWindowSession.getPendingPointerMove(mWindow);
2860 } catch (RemoteException e) {
2861 }
2862 didFinish = true;
2863 } else {
2864 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2865 }
2866 if (!didFinish) {
2867 try {
2868 sWindowSession.finishKey(mWindow);
2869 } catch (RemoteException e) {
2870 }
2871 }
2872 } else {
2873 MotionEvent event = mMotionEvent;
2874 if (event == null) {
2875 try {
2876 event = sWindowSession.getPendingTrackballMove(mWindow);
2877 } catch (RemoteException e) {
2878 }
2879 } else {
2880 try {
2881 sWindowSession.finishKey(mWindow);
2882 } catch (RemoteException e) {
2883 }
2884 }
2885 }
2886 }
2887 }
Romain Guy8506ab42009-06-11 17:35:47 -07002888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002890 private final WeakReference<ViewRoot> mViewRoot;
2891 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002893 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002895 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 }
2897
2898 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002899 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 final ViewRoot viewRoot = mViewRoot.get();
2901 if (viewRoot != null) {
2902 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002903 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 }
2905 }
2906
2907 public void dispatchKey(KeyEvent event) {
2908 final ViewRoot viewRoot = mViewRoot.get();
2909 if (viewRoot != null) {
2910 viewRoot.dispatchKey(event);
2911 } else {
2912 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002913 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 }
2915 }
2916
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002917 public void dispatchPointer(MotionEvent event, long eventTime,
2918 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002920 if (viewRoot != null) {
2921 if (MEASURE_LATENCY) {
2922 // Note: eventTime is in milliseconds
2923 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2924 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002925 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002926 } else {
2927 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929 }
2930
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002931 public void dispatchTrackball(MotionEvent event, long eventTime,
2932 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 final ViewRoot viewRoot = mViewRoot.get();
2934 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002935 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002936 } else {
2937 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 }
2939 }
2940
2941 public void dispatchAppVisibility(boolean visible) {
2942 final ViewRoot viewRoot = mViewRoot.get();
2943 if (viewRoot != null) {
2944 viewRoot.dispatchAppVisibility(visible);
2945 }
2946 }
2947
2948 public void dispatchGetNewSurface() {
2949 final ViewRoot viewRoot = mViewRoot.get();
2950 if (viewRoot != null) {
2951 viewRoot.dispatchGetNewSurface();
2952 }
2953 }
2954
2955 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2956 final ViewRoot viewRoot = mViewRoot.get();
2957 if (viewRoot != null) {
2958 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2959 }
2960 }
2961
2962 private static int checkCallingPermission(String permission) {
2963 if (!Process.supportsProcesses()) {
2964 return PackageManager.PERMISSION_GRANTED;
2965 }
2966
2967 try {
2968 return ActivityManagerNative.getDefault().checkPermission(
2969 permission, Binder.getCallingPid(), Binder.getCallingUid());
2970 } catch (RemoteException e) {
2971 return PackageManager.PERMISSION_DENIED;
2972 }
2973 }
2974
2975 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2976 final ViewRoot viewRoot = mViewRoot.get();
2977 if (viewRoot != null) {
2978 final View view = viewRoot.mView;
2979 if (view != null) {
2980 if (checkCallingPermission(Manifest.permission.DUMP) !=
2981 PackageManager.PERMISSION_GRANTED) {
2982 throw new SecurityException("Insufficient permissions to invoke"
2983 + " executeCommand() from pid=" + Binder.getCallingPid()
2984 + ", uid=" + Binder.getCallingUid());
2985 }
2986
2987 OutputStream clientStream = null;
2988 try {
2989 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2990 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2991 } catch (IOException e) {
2992 e.printStackTrace();
2993 } finally {
2994 if (clientStream != null) {
2995 try {
2996 clientStream.close();
2997 } catch (IOException e) {
2998 e.printStackTrace();
2999 }
3000 }
3001 }
3002 }
3003 }
3004 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003005
Dianne Hackbornffa42482009-09-23 22:20:11 -07003006 public void closeSystemDialogs(String reason) {
3007 final ViewRoot viewRoot = mViewRoot.get();
3008 if (viewRoot != null) {
3009 viewRoot.dispatchCloseSystemDialogs(reason);
3010 }
3011 }
3012
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003013 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3014 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003015 if (sync) {
3016 try {
3017 sWindowSession.wallpaperOffsetsComplete(asBinder());
3018 } catch (RemoteException e) {
3019 }
3020 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003021 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003022
3023 public void dispatchWallpaperCommand(String action, int x, int y,
3024 int z, Bundle extras, boolean sync) {
3025 if (sync) {
3026 try {
3027 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3028 } catch (RemoteException e) {
3029 }
3030 }
3031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 }
3033
3034 /**
3035 * Maintains state information for a single trackball axis, generating
3036 * discrete (DPAD) movements based on raw trackball motion.
3037 */
3038 static final class TrackballAxis {
3039 /**
3040 * The maximum amount of acceleration we will apply.
3041 */
3042 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 /**
3045 * The maximum amount of time (in milliseconds) between events in order
3046 * for us to consider the user to be doing fast trackball movements,
3047 * and thus apply an acceleration.
3048 */
3049 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 /**
3052 * Scaling factor to the time (in milliseconds) between events to how
3053 * much to multiple/divide the current acceleration. When movement
3054 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3055 * FAST_MOVE_TIME it divides it.
3056 */
3057 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 float position;
3060 float absPosition;
3061 float acceleration = 1;
3062 long lastMoveTime = 0;
3063 int step;
3064 int dir;
3065 int nonAccelMovement;
3066
3067 void reset(int _step) {
3068 position = 0;
3069 acceleration = 1;
3070 lastMoveTime = 0;
3071 step = _step;
3072 dir = 0;
3073 }
3074
3075 /**
3076 * Add trackball movement into the state. If the direction of movement
3077 * has been reversed, the state is reset before adding the
3078 * movement (so that you don't have to compensate for any previously
3079 * collected movement before see the result of the movement in the
3080 * new direction).
3081 *
3082 * @return Returns the absolute value of the amount of movement
3083 * collected so far.
3084 */
3085 float collect(float off, long time, String axis) {
3086 long normTime;
3087 if (off > 0) {
3088 normTime = (long)(off * FAST_MOVE_TIME);
3089 if (dir < 0) {
3090 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3091 position = 0;
3092 step = 0;
3093 acceleration = 1;
3094 lastMoveTime = 0;
3095 }
3096 dir = 1;
3097 } else if (off < 0) {
3098 normTime = (long)((-off) * FAST_MOVE_TIME);
3099 if (dir > 0) {
3100 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3101 position = 0;
3102 step = 0;
3103 acceleration = 1;
3104 lastMoveTime = 0;
3105 }
3106 dir = -1;
3107 } else {
3108 normTime = 0;
3109 }
Romain Guy8506ab42009-06-11 17:35:47 -07003110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 // The number of milliseconds between each movement that is
3112 // considered "normal" and will not result in any acceleration
3113 // or deceleration, scaled by the offset we have here.
3114 if (normTime > 0) {
3115 long delta = time - lastMoveTime;
3116 lastMoveTime = time;
3117 float acc = acceleration;
3118 if (delta < normTime) {
3119 // The user is scrolling rapidly, so increase acceleration.
3120 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3121 if (scale > 1) acc *= scale;
3122 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3123 + off + " normTime=" + normTime + " delta=" + delta
3124 + " scale=" + scale + " acc=" + acc);
3125 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3126 } else {
3127 // The user is scrolling slowly, so decrease acceleration.
3128 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3129 if (scale > 1) acc /= scale;
3130 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3131 + off + " normTime=" + normTime + " delta=" + delta
3132 + " scale=" + scale + " acc=" + acc);
3133 acceleration = acc > 1 ? acc : 1;
3134 }
3135 }
3136 position += off;
3137 return (absPosition = Math.abs(position));
3138 }
3139
3140 /**
3141 * Generate the number of discrete movement events appropriate for
3142 * the currently collected trackball movement.
3143 *
3144 * @param precision The minimum movement required to generate the
3145 * first discrete movement.
3146 *
3147 * @return Returns the number of discrete movements, either positive
3148 * or negative, or 0 if there is not enough trackball movement yet
3149 * for a discrete movement.
3150 */
3151 int generate(float precision) {
3152 int movement = 0;
3153 nonAccelMovement = 0;
3154 do {
3155 final int dir = position >= 0 ? 1 : -1;
3156 switch (step) {
3157 // If we are going to execute the first step, then we want
3158 // to do this as soon as possible instead of waiting for
3159 // a full movement, in order to make things look responsive.
3160 case 0:
3161 if (absPosition < precision) {
3162 return movement;
3163 }
3164 movement += dir;
3165 nonAccelMovement += dir;
3166 step = 1;
3167 break;
3168 // If we have generated the first movement, then we need
3169 // to wait for the second complete trackball motion before
3170 // generating the second discrete movement.
3171 case 1:
3172 if (absPosition < 2) {
3173 return movement;
3174 }
3175 movement += dir;
3176 nonAccelMovement += dir;
3177 position += dir > 0 ? -2 : 2;
3178 absPosition = Math.abs(position);
3179 step = 2;
3180 break;
3181 // After the first two, we generate discrete movements
3182 // consistently with the trackball, applying an acceleration
3183 // if the trackball is moving quickly. This is a simple
3184 // acceleration on top of what we already compute based
3185 // on how quickly the wheel is being turned, to apply
3186 // a longer increasing acceleration to continuous movement
3187 // in one direction.
3188 default:
3189 if (absPosition < 1) {
3190 return movement;
3191 }
3192 movement += dir;
3193 position += dir >= 0 ? -1 : 1;
3194 absPosition = Math.abs(position);
3195 float acc = acceleration;
3196 acc *= 1.1f;
3197 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3198 break;
3199 }
3200 } while (true);
3201 }
3202 }
3203
3204 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3205 public CalledFromWrongThreadException(String msg) {
3206 super(msg);
3207 }
3208 }
3209
3210 private SurfaceHolder mHolder = new SurfaceHolder() {
3211 // we only need a SurfaceHolder for opengl. it would be nice
3212 // to implement everything else though, especially the callback
3213 // support (opengl doesn't make use of it right now, but eventually
3214 // will).
3215 public Surface getSurface() {
3216 return mSurface;
3217 }
3218
3219 public boolean isCreating() {
3220 return false;
3221 }
3222
3223 public void addCallback(Callback callback) {
3224 }
3225
3226 public void removeCallback(Callback callback) {
3227 }
3228
3229 public void setFixedSize(int width, int height) {
3230 }
3231
3232 public void setSizeFromLayout() {
3233 }
3234
3235 public void setFormat(int format) {
3236 }
3237
3238 public void setType(int type) {
3239 }
3240
3241 public void setKeepScreenOn(boolean screenOn) {
3242 }
3243
3244 public Canvas lockCanvas() {
3245 return null;
3246 }
3247
3248 public Canvas lockCanvas(Rect dirty) {
3249 return null;
3250 }
3251
3252 public void unlockCanvasAndPost(Canvas canvas) {
3253 }
3254 public Rect getSurfaceFrame() {
3255 return null;
3256 }
3257 };
3258
3259 static RunQueue getRunQueue() {
3260 RunQueue rq = sRunQueues.get();
3261 if (rq != null) {
3262 return rq;
3263 }
3264 rq = new RunQueue();
3265 sRunQueues.set(rq);
3266 return rq;
3267 }
Romain Guy8506ab42009-06-11 17:35:47 -07003268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 /**
3270 * @hide
3271 */
3272 static final class RunQueue {
3273 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3274
3275 void post(Runnable action) {
3276 postDelayed(action, 0);
3277 }
3278
3279 void postDelayed(Runnable action, long delayMillis) {
3280 HandlerAction handlerAction = new HandlerAction();
3281 handlerAction.action = action;
3282 handlerAction.delay = delayMillis;
3283
3284 synchronized (mActions) {
3285 mActions.add(handlerAction);
3286 }
3287 }
3288
3289 void removeCallbacks(Runnable action) {
3290 final HandlerAction handlerAction = new HandlerAction();
3291 handlerAction.action = action;
3292
3293 synchronized (mActions) {
3294 final ArrayList<HandlerAction> actions = mActions;
3295
3296 while (actions.remove(handlerAction)) {
3297 // Keep going
3298 }
3299 }
3300 }
3301
3302 void executeActions(Handler handler) {
3303 synchronized (mActions) {
3304 final ArrayList<HandlerAction> actions = mActions;
3305 final int count = actions.size();
3306
3307 for (int i = 0; i < count; i++) {
3308 final HandlerAction handlerAction = actions.get(i);
3309 handler.postDelayed(handlerAction.action, handlerAction.delay);
3310 }
3311
Romain Guy15df6702009-08-17 20:17:30 -07003312 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 }
3314 }
3315
3316 private static class HandlerAction {
3317 Runnable action;
3318 long delay;
3319
3320 @Override
3321 public boolean equals(Object o) {
3322 if (this == o) return true;
3323 if (o == null || getClass() != o.getClass()) return false;
3324
3325 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 return !(action != null ? !action.equals(that.action) : that.action != null);
3327
3328 }
3329
3330 @Override
3331 public int hashCode() {
3332 int result = action != null ? action.hashCode() : 0;
3333 result = 31 * result + (int) (delay ^ (delay >>> 32));
3334 return result;
3335 }
3336 }
3337 }
3338
3339 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3340
3341 // inform skia to just abandon its texture cache IDs
3342 // doesn't call glDeleteTextures
3343 private static native void nativeAbandonGlCaches();
3344}