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