blob: 19d78111c1bf88d0079da8309813b9db8f9f0efe [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
Romain Guy6b7bd242010-10-06 19:49:23 -070019import android.Manifest;
20import android.app.ActivityManagerNative;
21import android.content.ClipDescription;
22import android.content.ComponentCallbacks;
23import android.content.Context;
24import android.content.pm.PackageManager;
25import android.content.res.CompatibilityInfo;
26import android.content.res.Configuration;
27import android.content.res.Resources;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080028import android.graphics.Bitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.graphics.Canvas;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080030import android.graphics.Paint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070032import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070033import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070034import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.graphics.Rect;
36import android.graphics.Region;
Romain Guy6b7bd242010-10-06 19:49:23 -070037import android.media.AudioManager;
38import android.os.Binder;
39import android.os.Bundle;
40import android.os.Debug;
41import android.os.Handler;
42import android.os.LatencyTimer;
43import android.os.Looper;
44import android.os.Message;
45import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070047import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.os.SystemClock;
50import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.util.AndroidRuntimeException;
52import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070053import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070055import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070056import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.util.SparseArray;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080058import android.util.TypedValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070060import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityManager;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080062import android.view.animation.AccelerateDecelerateInterpolator;
63import android.view.animation.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.inputmethod.InputConnection;
65import android.view.inputmethod.InputMethodManager;
66import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070067import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070068import com.android.internal.view.BaseSurfaceHolder;
69import com.android.internal.view.IInputMethodCallback;
70import com.android.internal.view.IInputMethodSession;
71import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.io.IOException;
74import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070075import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.ArrayList;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078/**
79 * The top of a view hierarchy, implementing the needed protocol between View
80 * and the WindowManager. This is for the most part an internal implementation
81 * detail of {@link WindowManagerImpl}.
82 *
83 * {@hide}
84 */
Romain Guy812ccbe2010-06-01 14:07:24 -070085@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
Dianne Hackborn0f761d62010-11-30 22:06:10 -080086public final class ViewRoot extends Handler implements ViewParent,
87 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final String TAG = "ViewRoot";
89 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040090 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070091 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 /** @noinspection PointlessBooleanExpression*/
93 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
94 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080095 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
97 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
98 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
99 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700100 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final boolean WATCH_POINTER = false;
102
Michael Chan53071d62009-05-13 17:29:48 -0700103 private static final boolean MEASURE_LATENCY = false;
104 private static LatencyTimer lt;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 /**
107 * Maximum time we allow the user to roll the trackball enough to generate
108 * a key event, before resetting the counters.
109 */
110 static final int MAX_TRACKBALL_DELAY = 250;
111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 static IWindowSession sWindowSession;
113
114 static final Object mStaticInit = new Object();
115 static boolean mInitialized = false;
116
117 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
118
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800119 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
120 static boolean sFirstDrawComplete = false;
121
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800122 static final ArrayList<ComponentCallbacks> sConfigCallbacks
123 = new ArrayList<ComponentCallbacks>();
124
Romain Guy8506ab42009-06-11 17:35:47 -0700125 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 long mLastTrackballTime = 0;
128 final TrackballAxis mTrackballAxisX = new TrackballAxis();
129 final TrackballAxis mTrackballAxisY = new TrackballAxis();
130
131 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700132
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800133 final TypedValue mTmpValue = new TypedValue();
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 final InputMethodCallback mInputMethodCallback;
136 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
137 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 final Thread mThread;
140
141 final WindowLeaked mLocation;
142
143 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
144
145 final W mWindow;
146
147 View mView;
148 View mFocusedView;
149 View mRealFocusedView; // this is not set to null in touch mode
150 int mViewVisibility;
151 boolean mAppVisible = true;
152
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700153 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700154 BaseSurfaceHolder mSurfaceHolder;
155 boolean mIsCreating;
156 boolean mDrawingAllowed;
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 final Region mTransparentRegion;
159 final Region mPreviousTransparentRegion;
160
161 int mWidth;
162 int mHeight;
Romain Guy7d7b5492011-01-24 16:33:45 -0800163 Rect mDirty;
164 final Rect mCurrentDirty = new Rect();
165 final Rect mPreviousDirty = new Rect();
Romain Guybb93d552009-03-24 21:04:15 -0700166 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700167
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700168 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700171 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700172 InputQueue.Callback mInputQueueCallback;
173 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700174 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 final Rect mTempRect; // used in the transaction to not thrash the heap.
177 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
179 boolean mTraversalScheduled;
180 boolean mWillDrawSoon;
181 boolean mLayoutRequested;
182 boolean mFirst;
183 boolean mReportNextDraw;
184 boolean mFullRedrawNeeded;
185 boolean mNewSurfaceNeeded;
186 boolean mHasHadWindowFocus;
187 boolean mLastWasImTarget;
188
189 boolean mWindowAttributesChanged = false;
190
191 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700192 // Surface can never be reassigned or cleared (use Surface.clear()).
193 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
195 boolean mAdded;
196 boolean mAddedTouchMode;
197
198 /*package*/ int mAddNesting;
199
200 // These are accessed by multiple threads.
201 final Rect mWinFrame; // frame given by window manager.
202
203 final Rect mPendingVisibleInsets = new Rect();
204 final Rect mPendingContentInsets = new Rect();
205 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
206 = new ViewTreeObserver.InternalInsetsInfo();
207
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700208 final Configuration mLastConfiguration = new Configuration();
209 final Configuration mPendingConfiguration = new Configuration();
210
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800211 class ResizedInfo {
212 Rect coveredInsets;
213 Rect visibleInsets;
214 Configuration newConfig;
215 }
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 boolean mScrollMayChange;
218 int mSoftInputMode;
219 View mLastScrolledFocus;
220 int mScrollY;
221 int mCurScrollY;
222 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800223 Bitmap mResizeBitmap;
224 long mResizeBitmapStartTime;
225 int mResizeBitmapDuration;
226 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700227
Romain Guy8506ab42009-06-11 17:35:47 -0700228 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Christopher Tatea53146c2010-09-07 11:57:52 -0700230 /* Drag/drop */
231 ClipDescription mDragDescription;
232 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800233 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700234 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700235 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 /**
238 * see {@link #playSoundEffect(int)}
239 */
240 AudioManager mAudioManager;
241
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700242 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700243
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700244 public static IWindowSession getWindowSession(Looper mainLooper) {
245 synchronized (mStaticInit) {
246 if (!mInitialized) {
247 try {
248 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
249 sWindowSession = IWindowManager.Stub.asInterface(
250 ServiceManager.getService("window"))
251 .openSession(imm.getClient(), imm.getInputContext());
252 mInitialized = true;
253 } catch (RemoteException e) {
254 }
255 }
256 return sWindowSession;
257 }
258 }
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 public ViewRoot(Context context) {
261 super();
262
Romain Guy812ccbe2010-06-01 14:07:24 -0700263 if (MEASURE_LATENCY) {
264 if (lt == null) {
265 lt = new LatencyTimer(100, 1000);
266 }
Michael Chan53071d62009-05-13 17:29:48 -0700267 }
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // Initialize the statics when this class is first instantiated. This is
270 // done here instead of in the static block because Zygote does not
271 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700272 getWindowSession(context.getMainLooper());
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 mThread = Thread.currentThread();
275 mLocation = new WindowLeaked(null);
276 mLocation.fillInStackTrace();
277 mWidth = -1;
278 mHeight = -1;
279 mDirty = new Rect();
280 mTempRect = new Rect();
281 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700283 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 mInputMethodCallback = new InputMethodCallback(this);
285 mViewVisibility = View.GONE;
286 mTransparentRegion = new Region();
287 mPreviousTransparentRegion = new Region();
288 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 mAdded = false;
290 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
291 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700292 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700293 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 }
295
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800296 public static void addFirstDrawHandler(Runnable callback) {
297 synchronized (sFirstDrawHandlers) {
298 if (!sFirstDrawComplete) {
299 sFirstDrawHandlers.add(callback);
300 }
301 }
302 }
303
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800304 public static void addConfigCallback(ComponentCallbacks callback) {
305 synchronized (sConfigCallbacks) {
306 sConfigCallbacks.add(callback);
307 }
308 }
309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 // FIXME for perf testing only
311 private boolean mProfile = false;
312
313 /**
314 * Call this to profile the next traversal call.
315 * FIXME for perf testing only. Remove eventually
316 */
317 public void profile() {
318 mProfile = true;
319 }
320
321 /**
322 * Indicates whether we are in touch mode. Calling this method triggers an IPC
323 * call and should be avoided whenever possible.
324 *
325 * @return True, if the device is in touch mode, false otherwise.
326 *
327 * @hide
328 */
329 static boolean isInTouchMode() {
330 if (mInitialized) {
331 try {
332 return sWindowSession.getInTouchMode();
333 } catch (RemoteException e) {
334 }
335 }
336 return false;
337 }
338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 /**
340 * We have one child
341 */
Romain Guye4d01122010-06-16 18:44:05 -0700342 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 synchronized (this) {
344 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700345 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700346 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700347 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700348 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700349
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700350 if (view instanceof RootViewSurfaceTaker) {
351 mSurfaceHolderCallback =
352 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
353 if (mSurfaceHolderCallback != null) {
354 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700355 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700356 }
357 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800358
359 // If the application owns the surface, don't enable hardware acceleration
360 if (mSurfaceHolder == null) {
361 enableHardwareAcceleration(attrs);
362 }
363
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700364 Resources resources = mView.getContext().getResources();
365 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700366 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700367
368 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700369 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
370 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700371 }
372
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700373 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700374 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700375 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700376 attrs.backup();
377 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700378 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700379 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
380
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700381 if (!compatibilityInfo.supportsScreen()) {
382 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
383 }
384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 mSoftInputMode = attrs.softInputMode;
386 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700388 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700389 mAttachInfo.mApplicationScale =
390 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 if (panelParentView != null) {
392 mAttachInfo.mPanelParentWindowToken
393 = panelParentView.getApplicationWindowToken();
394 }
395 mAdded = true;
396 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 // Schedule the first layout -before- adding to the window
399 // manager, to make sure we do the relayout before receiving
400 // any other events from the system.
401 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700402 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700404 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700405 getHostVisibility(), mAttachInfo.mContentInsets,
406 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 } catch (RemoteException e) {
408 mAdded = false;
409 mView = null;
410 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700411 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700412 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 unscheduleTraversals();
414 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700415 } finally {
416 if (restore) {
417 attrs.restore();
418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700421 if (mTranslator != null) {
422 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 mPendingContentInsets.set(mAttachInfo.mContentInsets);
425 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800426 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 if (res < WindowManagerImpl.ADD_OKAY) {
428 mView = null;
429 mAttachInfo.mRootView = null;
430 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700431 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 unscheduleTraversals();
433 switch (res) {
434 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
435 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
436 throw new WindowManagerImpl.BadTokenException(
437 "Unable to add window -- token " + attrs.token
438 + " is not valid; is your activity running?");
439 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
440 throw new WindowManagerImpl.BadTokenException(
441 "Unable to add window -- token " + attrs.token
442 + " is not for an application");
443 case WindowManagerImpl.ADD_APP_EXITING:
444 throw new WindowManagerImpl.BadTokenException(
445 "Unable to add window -- app for token " + attrs.token
446 + " is exiting");
447 case WindowManagerImpl.ADD_DUPLICATE_ADD:
448 throw new WindowManagerImpl.BadTokenException(
449 "Unable to add window -- window " + mWindow
450 + " has already been added");
451 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
452 // Silently ignore -- we would have just removed it
453 // right away, anyway.
454 return;
455 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
456 throw new WindowManagerImpl.BadTokenException(
457 "Unable to add window " + mWindow +
458 " -- another window of this type already exists");
459 case WindowManagerImpl.ADD_PERMISSION_DENIED:
460 throw new WindowManagerImpl.BadTokenException(
461 "Unable to add window " + mWindow +
462 " -- permission denied for this window type");
463 }
464 throw new RuntimeException(
465 "Unable to add window -- unknown error code " + res);
466 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700467
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700468 if (view instanceof RootViewSurfaceTaker) {
469 mInputQueueCallback =
470 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
471 }
472 if (mInputQueueCallback != null) {
473 mInputQueue = new InputQueue(mInputChannel);
474 mInputQueueCallback.onInputQueueCreated(mInputQueue);
475 } else {
476 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
477 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700478 }
479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 view.assignParent(this);
481 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
482 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
483 }
484 }
485 }
486
Romain Guy529b60a2010-08-03 18:05:47 -0700487 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800488 mAttachInfo.mHardwareAccelerated = false;
489 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800490
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800491 // Try to enable hardware acceleration if requested
492 if (attrs != null &&
493 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
494 // Only enable hardware acceleration if we are not in the system process
495 // The window manager creates ViewRoots to display animated preview windows
496 // of launching apps and we don't want those to be hardware accelerated
497 if (!HardwareRenderer.sRendererDisabled) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800498 // Don't enable hardware acceleration when we're not on the main thread
499 if (Looper.getMainLooper() != Looper.myLooper()) {
500 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
501 + "acceleration outside of the main thread, aborting");
502 return;
503 }
504
Romain Guye4d01122010-06-16 18:44:05 -0700505 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700506 if (mAttachInfo.mHardwareRenderer != null) {
507 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700508 }
Romain Guyb051e892010-09-28 19:09:36 -0700509 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800510 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
511 = mAttachInfo.mHardwareRenderer != null;
512 } else if (HardwareRenderer.isAvailable()) {
513 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700514 }
515 }
516 }
517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 public View getView() {
519 return mView;
520 }
521
522 final WindowLeaked getLocation() {
523 return mLocation;
524 }
525
526 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
527 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700528 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700529 // preserve compatible window flag if exists.
530 int compatibleWindowFlag =
531 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700533 mWindowAttributes.flags |= compatibleWindowFlag;
534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 if (newView) {
536 mSoftInputMode = attrs.softInputMode;
537 requestLayout();
538 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700539 // Don't lose the mode we last auto-computed.
540 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
541 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
542 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
543 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
544 | (oldSoftInputMode
545 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 mWindowAttributesChanged = true;
548 scheduleTraversals();
549 }
550 }
551
552 void handleAppVisibility(boolean visible) {
553 if (mAppVisible != visible) {
554 mAppVisible = visible;
555 scheduleTraversals();
556 }
557 }
558
559 void handleGetNewSurface() {
560 mNewSurfaceNeeded = true;
561 mFullRedrawNeeded = true;
562 scheduleTraversals();
563 }
564
565 /**
566 * {@inheritDoc}
567 */
568 public void requestLayout() {
569 checkThread();
570 mLayoutRequested = true;
571 scheduleTraversals();
572 }
573
574 /**
575 * {@inheritDoc}
576 */
577 public boolean isLayoutRequested() {
578 return mLayoutRequested;
579 }
580
581 public void invalidateChild(View child, Rect dirty) {
582 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700583 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700584 if (dirty == null) {
585 // Fast invalidation for GL-enabled applications; GL must redraw everything
586 invalidate();
587 return;
588 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700589 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700591 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700592 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700593 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700594 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700595 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700596 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700597 }
Romain Guy1e095972009-07-07 11:22:45 -0700598 if (mAttachInfo.mScalingRequired) {
599 dirty.inset(-1, -1);
600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
Chet Haasedaf98e92011-01-10 14:10:36 -0800602 if (!mDirty.isEmpty() && !mDirty.contains(dirty)) {
Romain Guy7d695942010-12-01 17:22:29 -0800603 mAttachInfo.mIgnoreDirtyState = true;
604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 mDirty.union(dirty);
606 if (!mWillDrawSoon) {
607 scheduleTraversals();
608 }
609 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700610
611 void invalidate() {
612 mDirty.set(0, 0, mWidth, mHeight);
613 scheduleTraversals();
614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615
616 public ViewParent getParent() {
617 return null;
618 }
619
620 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
621 invalidateChild(null, dirty);
622 return null;
623 }
624
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700625 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 if (child != mView) {
627 throw new RuntimeException("child is not mine, honest!");
628 }
629 // Note: don't apply scroll offset, because we want to know its
630 // visibility in the virtual canvas being given to the view hierarchy.
631 return r.intersect(0, 0, mWidth, mHeight);
632 }
633
634 public void bringChildToFront(View child) {
635 }
636
637 public void scheduleTraversals() {
638 if (!mTraversalScheduled) {
639 mTraversalScheduled = true;
640 sendEmptyMessage(DO_TRAVERSAL);
641 }
642 }
643
644 public void unscheduleTraversals() {
645 if (mTraversalScheduled) {
646 mTraversalScheduled = false;
647 removeMessages(DO_TRAVERSAL);
648 }
649 }
650
651 int getHostVisibility() {
652 return mAppVisible ? mView.getVisibility() : View.GONE;
653 }
Romain Guy8506ab42009-06-11 17:35:47 -0700654
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800655 void disposeResizeBitmap() {
656 if (mResizeBitmap != null) {
657 mResizeBitmap.recycle();
658 mResizeBitmap = null;
659 }
660 }
661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 private void performTraversals() {
663 // cache mView since it is used so much below...
664 final View host = mView;
665
666 if (DBG) {
667 System.out.println("======================================");
668 System.out.println("performTraversals");
669 host.debug();
670 }
671
672 if (host == null || !mAdded)
673 return;
674
675 mTraversalScheduled = false;
676 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800677 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 boolean fullRedrawNeeded = mFullRedrawNeeded;
679 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700680 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 WindowManager.LayoutParams lp = mWindowAttributes;
682
683 int desiredWindowWidth;
684 int desiredWindowHeight;
685 int childWidthMeasureSpec;
686 int childHeightMeasureSpec;
687
688 final View.AttachInfo attachInfo = mAttachInfo;
689
690 final int viewVisibility = getHostVisibility();
691 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
692 || mNewSurfaceNeeded;
693
694 WindowManager.LayoutParams params = null;
695 if (mWindowAttributesChanged) {
696 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700697 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 params = lp;
699 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700700 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 if (mFirst) {
702 fullRedrawNeeded = true;
703 mLayoutRequested = true;
704
Romain Guy8506ab42009-06-11 17:35:47 -0700705 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700706 mView.getContext().getResources().getDisplayMetrics();
707 desiredWindowWidth = packageMetrics.widthPixels;
708 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
710 // For the very first time, tell the view hierarchy that it
711 // is attached to the window. Note that at this point the surface
712 // object is not initialized to its backing store, but soon it
713 // will be (assuming the window is visible).
714 attachInfo.mSurface = mSurface;
Romain Guyc5d55862011-01-21 19:01:46 -0800715 // We used to use the following condition to choose 32 bits drawing caches:
716 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
717 // However, windows are now always 32 bits by default, so choose 32 bits
718 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 attachInfo.mHasWindowFocus = false;
720 attachInfo.mWindowVisibility = viewVisibility;
721 attachInfo.mRecomputeGlobalAttributes = false;
722 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800723 attachInfo.mSystemUiVisibility = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700725 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700730 desiredWindowWidth = frame.width();
731 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700733 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700734 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 fullRedrawNeeded = true;
736 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800737 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 }
739 }
740
741 if (viewVisibilityChanged) {
742 attachInfo.mWindowVisibility = viewVisibility;
743 host.dispatchWindowVisibilityChanged(viewVisibility);
744 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700745 if (mAttachInfo.mHardwareRenderer != null) {
746 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 }
749 if (viewVisibility == View.GONE) {
750 // After making a window gone, we will count it as being
751 // shown for the first time the next time it gets focus.
752 mHasHadWindowFocus = false;
753 }
754 }
755
756 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700759 // Execute enqueued actions on every layout in case a view that was detached
760 // enqueued an action after being detached
761 getRunQueue().executeActions(attachInfo.mHandler);
762
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800763 final Resources res = mView.getContext().getResources();
764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 if (mFirst) {
766 host.fitSystemWindows(mAttachInfo.mContentInsets);
767 // make sure touch mode code executes by setting cached value
768 // to opposite of the added touch mode.
769 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700770 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 } else {
772 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800773 if (mWidth > 0 && mHeight > 0 &&
774 mSurface != null && mSurface.isValid() &&
775 mAttachInfo.mHardwareRenderer != null &&
776 mAttachInfo.mHardwareRenderer.isEnabled() &&
777 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
778
779 disposeResizeBitmap();
780
781 boolean completed = false;
782 try {
783 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
784 Bitmap.Config.ARGB_8888);
785 mResizeBitmap.setHasAlpha(false);
786 Canvas canvas = new Canvas(mResizeBitmap);
787 int yoff;
788 final boolean scrolling = mScroller != null
789 && mScroller.computeScrollOffset();
790 if (scrolling) {
791 yoff = mScroller.getCurrY();
792 mScroller.abortAnimation();
793 } else {
794 yoff = mScrollY;
795 }
796 canvas.translate(0, -yoff);
797 if (mTranslator != null) {
798 mTranslator.translateCanvas(canvas);
799 }
800 canvas.setScreenDensity(mAttachInfo.mScalingRequired
801 ? DisplayMetrics.DENSITY_DEVICE : 0);
802 mView.draw(canvas);
803 mResizeBitmapStartTime = SystemClock.uptimeMillis();
804 mResizeBitmapDuration = mView.getResources().getInteger(
805 com.android.internal.R.integer.config_mediumAnimTime);
806 completed = true;
807 } catch (OutOfMemoryError e) {
808 Log.w(TAG, "Not enough memory for content change anim buffer", e);
809 } finally {
810 if (!completed) {
811 mResizeBitmap = null;
812 }
813 }
814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 mAttachInfo.mContentInsets.set(mPendingContentInsets);
816 host.fitSystemWindows(mAttachInfo.mContentInsets);
817 insetsChanged = true;
818 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
819 + mAttachInfo.mContentInsets);
820 }
821 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
822 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
823 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
824 + mAttachInfo.mVisibleInsets);
825 }
826 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
827 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800828 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800830 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700831 desiredWindowWidth = packageMetrics.widthPixels;
832 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834 }
835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700837 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 "Measuring " + host + " in display " + desiredWindowWidth
839 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800840
841 boolean goodMeasure = false;
842 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
843 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
844 // On large screens, we don't want to allow dialogs to just
845 // stretch to fill the entire width of the screen to display
846 // one line of text. First try doing the layout at a smaller
847 // size to see if it will fit.
848 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
849 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
850 int baseSize = 0;
851 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
852 baseSize = (int)mTmpValue.getDimension(packageMetrics);
853 }
854 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800855 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800856 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
857 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
858 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
859 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800860 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
861 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800862 goodMeasure = true;
863 } else {
864 // Didn't fit in that size... try expanding a bit.
865 baseSize = (baseSize+desiredWindowWidth)/2;
866 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
867 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800868 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800869 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
870 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800871 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
872 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800873 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
874 goodMeasure = true;
875 }
876 }
877 }
878 }
879
880 if (!goodMeasure) {
881 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
882 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
883 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800884 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
885 windowSizeMayChange = true;
886 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888
889 if (DBG) {
890 System.out.println("======================================");
891 System.out.println("performTraversals -- after measure");
892 host.debug();
893 }
894 }
895
896 if (attachInfo.mRecomputeGlobalAttributes) {
Joe Onorato664644d2011-01-23 17:53:23 -0800897 //Log.i(TAG, "Computing view hierarchy attributes!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 attachInfo.mRecomputeGlobalAttributes = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800899 boolean oldScreenOn = attachInfo.mKeepScreenOn;
900 int oldVis = attachInfo.mSystemUiVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800902 attachInfo.mSystemUiVisibility = 0;
903 attachInfo.mHasSystemUiListeners = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 host.dispatchCollectViewAttributes(0);
Joe Onorato664644d2011-01-23 17:53:23 -0800905 if (attachInfo.mKeepScreenOn != oldScreenOn ||
906 attachInfo.mSystemUiVisibility != oldVis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 }
909 }
910
911 if (mFirst || attachInfo.mViewVisibilityChanged) {
912 attachInfo.mViewVisibilityChanged = false;
913 int resizeMode = mSoftInputMode &
914 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
915 // If we are in auto resize mode, then we need to determine
916 // what mode to use now.
917 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
918 final int N = attachInfo.mScrollContainers.size();
919 for (int i=0; i<N; i++) {
920 if (attachInfo.mScrollContainers.get(i).isShown()) {
921 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
922 }
923 }
924 if (resizeMode == 0) {
925 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
926 }
927 if ((lp.softInputMode &
928 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
929 lp.softInputMode = (lp.softInputMode &
930 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
931 resizeMode;
932 params = lp;
933 }
934 }
935 }
Romain Guy8506ab42009-06-11 17:35:47 -0700936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
938 if (!PixelFormat.formatHasAlpha(params.format)) {
939 params.format = PixelFormat.TRANSLUCENT;
940 }
941 }
942
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800943 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800944 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700945 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
946 frame.width() < desiredWindowWidth && frame.width() != mWidth)
947 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
948 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949
950 final boolean computesInternalInsets =
951 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 boolean insetsPending = false;
954 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700955
956 if (mFirst || windowShouldResize || insetsChanged ||
957 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958
959 if (viewVisibility == View.VISIBLE) {
960 // If this window is giving internal insets to the window
961 // manager, and it is being added or changing its visibility,
962 // then we want to first give the window manager "fake"
963 // insets to cause it to effectively ignore the content of
964 // the window during layout. This avoids it briefly causing
965 // other windows to resize/move based on the raw frame of the
966 // window, waiting until we can finish laying out this window
967 // and get back to the window manager with the ultimately
968 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700969 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700972 if (mSurfaceHolder != null) {
973 mSurfaceHolder.mSurfaceLock.lock();
974 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700975 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700976
Romain Guyc361da82010-10-25 15:29:10 -0700977 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700979 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700980 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 int fl = 0;
984 if (params != null) {
985 fl = params.flags;
986 if (attachInfo.mKeepScreenOn) {
987 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
988 }
Joe Onorato664644d2011-01-23 17:53:23 -0800989 params.systemUiVisibility = attachInfo.mSystemUiVisibility;
990 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700992 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800993 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
994 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700995 }
Romain Guy2a83f002011-01-18 18:28:21 -0800996
997 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700998 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 if (params != null) {
1001 params.flags = fl;
1002 }
1003
1004 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1005 + " content=" + mPendingContentInsets.toShortString()
1006 + " visible=" + mPendingVisibleInsets.toShortString()
1007 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001008
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001009 if (mPendingConfiguration.seq != 0) {
1010 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1011 + mPendingConfiguration);
1012 updateConfiguration(mPendingConfiguration, !mFirst);
1013 mPendingConfiguration.seq = 0;
1014 }
1015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 contentInsetsChanged = !mPendingContentInsets.equals(
1017 mAttachInfo.mContentInsets);
1018 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1019 mAttachInfo.mVisibleInsets);
1020 if (contentInsetsChanged) {
1021 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1022 host.fitSystemWindows(mAttachInfo.mContentInsets);
1023 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1024 + mAttachInfo.mContentInsets);
1025 }
1026 if (visibleInsetsChanged) {
1027 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1028 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1029 + mAttachInfo.mVisibleInsets);
1030 }
1031
1032 if (!hadSurface) {
1033 if (mSurface.isValid()) {
1034 // If we are creating a new surface, then we need to
1035 // completely redraw it. Also, when we get to the
1036 // point of drawing it we will hold off and schedule
1037 // a new traversal instead. This is so we can tell the
1038 // window manager about all of the windows being displayed
1039 // before actually drawing them, so it can display then
1040 // all at once.
1041 newSurface = true;
1042 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001043 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001044
Romain Guyb051e892010-09-28 19:09:36 -07001045 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001046 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048 }
1049 } else if (!mSurface.isValid()) {
1050 // If the surface has been removed, then reset the scroll
1051 // positions.
1052 mLastScrolledFocus = null;
1053 mScrollY = mCurScrollY = 0;
1054 if (mScroller != null) {
1055 mScroller.abortAnimation();
1056 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001057 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001058 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1059 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
Romain Guy7d7b5492011-01-24 16:33:45 -08001060 fullRedrawNeeded = true;
Romain Guy2a83f002011-01-18 18:28:21 -08001061 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 }
1063 } catch (RemoteException e) {
1064 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001067 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068
1069 attachInfo.mWindowLeft = frame.left;
1070 attachInfo.mWindowTop = frame.top;
1071
1072 // !!FIXME!! This next section handles the case where we did not get the
1073 // window size we asked for. We should avoid this by getting a maximum size from
1074 // the window session beforehand.
1075 mWidth = frame.width();
1076 mHeight = frame.height();
1077
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001078 if (mSurfaceHolder != null) {
1079 // The app owns the surface; tell it about what is going on.
1080 if (mSurface.isValid()) {
1081 // XXX .copyFrom() doesn't work!
1082 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1083 mSurfaceHolder.mSurface = mSurface;
1084 }
1085 mSurfaceHolder.mSurfaceLock.unlock();
1086 if (mSurface.isValid()) {
1087 if (!hadSurface) {
1088 mSurfaceHolder.ungetCallbacks();
1089
1090 mIsCreating = true;
1091 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1092 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1093 if (callbacks != null) {
1094 for (SurfaceHolder.Callback c : callbacks) {
1095 c.surfaceCreated(mSurfaceHolder);
1096 }
1097 }
1098 surfaceChanged = true;
1099 }
1100 if (surfaceChanged) {
1101 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1102 lp.format, mWidth, mHeight);
1103 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1104 if (callbacks != null) {
1105 for (SurfaceHolder.Callback c : callbacks) {
1106 c.surfaceChanged(mSurfaceHolder, lp.format,
1107 mWidth, mHeight);
1108 }
1109 }
1110 }
1111 mIsCreating = false;
1112 } else if (hadSurface) {
1113 mSurfaceHolder.ungetCallbacks();
1114 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1115 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1116 if (callbacks != null) {
1117 for (SurfaceHolder.Callback c : callbacks) {
1118 c.surfaceDestroyed(mSurfaceHolder);
1119 }
1120 }
1121 mSurfaceHolder.mSurfaceLock.lock();
1122 // Make surface invalid.
1123 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1124 mSurfaceHolder.mSurface = new Surface();
1125 mSurfaceHolder.mSurfaceLock.unlock();
1126 }
1127 }
Romain Guy53389bd2010-09-07 17:16:32 -07001128
Romain Guy6b5108b2011-01-04 16:11:10 -08001129 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001130 mAttachInfo.mHardwareRenderer != null &&
1131 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001132 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134
1135 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001136 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001137 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1138 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1140 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1141
1142 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001143 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + " mHeight=" + mHeight
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001145 + " measuredHeight=" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 // Ask host how big it wants to be
1149 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1150
1151 // Implementation of weights from WindowManager.LayoutParams
1152 // We just grow the dimensions as needed and re-measure if
1153 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001154 int width = host.getMeasuredWidth();
1155 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 boolean measureAgain = false;
1157
1158 if (lp.horizontalWeight > 0.0f) {
1159 width += (int) ((mWidth - width) * lp.horizontalWeight);
1160 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1161 MeasureSpec.EXACTLY);
1162 measureAgain = true;
1163 }
1164 if (lp.verticalWeight > 0.0f) {
1165 height += (int) ((mHeight - height) * lp.verticalWeight);
1166 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1167 MeasureSpec.EXACTLY);
1168 measureAgain = true;
1169 }
1170
1171 if (measureAgain) {
1172 if (DEBUG_LAYOUT) Log.v(TAG,
1173 "And hey let's measure once more: width=" + width
1174 + " height=" + height);
1175 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1176 }
1177
1178 mLayoutRequested = true;
1179 }
1180 }
1181
1182 final boolean didLayout = mLayoutRequested;
1183 boolean triggerGlobalLayoutListener = didLayout
1184 || attachInfo.mRecomputeGlobalAttributes;
1185 if (didLayout) {
1186 mLayoutRequested = false;
1187 mScrollMayChange = true;
1188 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001189 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001190 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001191 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001192 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 startTime = SystemClock.elapsedRealtime();
1194 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001195 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196
Romain Guy13922e02009-05-12 17:56:14 -07001197 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1198 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1199 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1200 + "please refer to the logs with the tag "
1201 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1202 }
1203 }
1204
Romain Guy5429e1d2010-09-07 12:38:00 -07001205 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1207 }
1208
1209 // By this point all views have been sized and positionned
1210 // We can compute the transparent area
1211
1212 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1213 // start out transparent
1214 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1215 host.getLocationInWindow(mTmpLocation);
1216 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1217 mTmpLocation[0] + host.mRight - host.mLeft,
1218 mTmpLocation[1] + host.mBottom - host.mTop);
1219
1220 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001221 if (mTranslator != null) {
1222 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1223 }
1224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1226 mPreviousTransparentRegion.set(mTransparentRegion);
1227 // reconfigure window manager
1228 try {
1229 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1230 } catch (RemoteException e) {
1231 }
1232 }
1233 }
1234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if (DBG) {
1236 System.out.println("======================================");
1237 System.out.println("performTraversals -- after setFrame");
1238 host.debug();
1239 }
1240 }
1241
1242 if (triggerGlobalLayoutListener) {
1243 attachInfo.mRecomputeGlobalAttributes = false;
1244 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1245 }
1246
1247 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001248 // Clear the original insets.
1249 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1250 insets.reset();
1251
1252 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001254
1255 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1257 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001258
1259 // Translate insets to screen coordinates if needed.
1260 final Rect contentInsets;
1261 final Rect visibleInsets;
1262 final Region touchableRegion;
1263 if (mTranslator != null) {
1264 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1265 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1266 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1267 } else {
1268 contentInsets = insets.contentInsets;
1269 visibleInsets = insets.visibleInsets;
1270 touchableRegion = insets.touchableRegion;
1271 }
1272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 try {
1274 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001275 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 } catch (RemoteException e) {
1277 }
1278 }
1279 }
Romain Guy8506ab42009-06-11 17:35:47 -07001280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 if (mFirst) {
1282 // handle first focus request
1283 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1284 + mView.hasFocus());
1285 if (mView != null) {
1286 if (!mView.hasFocus()) {
1287 mView.requestFocus(View.FOCUS_FORWARD);
1288 mFocusedView = mRealFocusedView = mView.findFocus();
1289 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1290 + mFocusedView);
1291 } else {
1292 mRealFocusedView = mView.findFocus();
1293 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1294 + mRealFocusedView);
1295 }
1296 }
1297 }
1298
1299 mFirst = false;
1300 mWillDrawSoon = false;
1301 mNewSurfaceNeeded = false;
1302 mViewVisibility = viewVisibility;
1303
1304 if (mAttachInfo.mHasWindowFocus) {
1305 final boolean imTarget = WindowManager.LayoutParams
1306 .mayUseInputMethod(mWindowAttributes.flags);
1307 if (imTarget != mLastWasImTarget) {
1308 mLastWasImTarget = imTarget;
1309 InputMethodManager imm = InputMethodManager.peekInstance();
1310 if (imm != null && imTarget) {
1311 imm.startGettingWindowFocus(mView);
1312 imm.onWindowFocus(mView, mView.findFocus(),
1313 mWindowAttributes.softInputMode,
1314 !mHasHadWindowFocus, mWindowAttributes.flags);
1315 }
1316 }
1317 }
Romain Guy8506ab42009-06-11 17:35:47 -07001318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1320
1321 if (!cancelDraw && !newSurface) {
1322 mFullRedrawNeeded = false;
1323 draw(fullRedrawNeeded);
1324
1325 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1326 || mReportNextDraw) {
1327 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001328 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001331 if (mSurfaceHolder != null && mSurface.isValid()) {
1332 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1333 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1334 if (callbacks != null) {
1335 for (SurfaceHolder.Callback c : callbacks) {
1336 if (c instanceof SurfaceHolder.Callback2) {
1337 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1338 mSurfaceHolder);
1339 }
1340 }
1341 }
1342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 try {
1344 sWindowSession.finishDrawing(mWindow);
1345 } catch (RemoteException e) {
1346 }
1347 }
1348 } else {
1349 // We were supposed to report when we are done drawing. Since we canceled the
1350 // draw, remember it here.
1351 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1352 mReportNextDraw = true;
1353 }
1354 if (fullRedrawNeeded) {
1355 mFullRedrawNeeded = true;
1356 }
1357 // Try again
1358 scheduleTraversals();
1359 }
1360 }
1361
1362 public void requestTransparentRegion(View child) {
1363 // the test below should not fail unless someone is messing with us
1364 checkThread();
1365 if (mView == child) {
1366 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1367 // Need to make sure we re-evaluate the window attributes next
1368 // time around, to ensure the window has the correct format.
1369 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001370 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 }
1372 }
1373
1374 /**
1375 * Figures out the measure spec for the root view in a window based on it's
1376 * layout params.
1377 *
1378 * @param windowSize
1379 * The available width or height of the window
1380 *
1381 * @param rootDimension
1382 * The layout params for one dimension (width or height) of the
1383 * window.
1384 *
1385 * @return The measure spec to use to measure the root view.
1386 */
1387 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1388 int measureSpec;
1389 switch (rootDimension) {
1390
Romain Guy980a9382010-01-08 15:06:28 -08001391 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 // Window can't resize. Force root view to be windowSize.
1393 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1394 break;
1395 case ViewGroup.LayoutParams.WRAP_CONTENT:
1396 // Window can resize. Set max size for root view.
1397 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1398 break;
1399 default:
1400 // Window wants to be an exact size. Force root view to be that size.
1401 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1402 break;
1403 }
1404 return measureSpec;
1405 }
1406
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001407 int mHardwareYOffset;
1408 int mResizeAlpha;
1409 final Paint mResizePaint = new Paint();
1410
1411 public void onHardwarePreDraw(Canvas canvas) {
1412 canvas.translate(0, -mHardwareYOffset);
1413 }
1414
1415 public void onHardwarePostDraw(Canvas canvas) {
1416 if (mResizeBitmap != null) {
1417 canvas.translate(0, mHardwareYOffset);
1418 mResizePaint.setAlpha(mResizeAlpha);
1419 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1420 }
1421 }
1422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 private void draw(boolean fullRedrawNeeded) {
1424 Surface surface = mSurface;
1425 if (surface == null || !surface.isValid()) {
1426 return;
1427 }
1428
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001429 if (!sFirstDrawComplete) {
1430 synchronized (sFirstDrawHandlers) {
1431 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001432 final int count = sFirstDrawHandlers.size();
1433 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001434 post(sFirstDrawHandlers.get(i));
1435 }
1436 }
1437 }
1438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 scrollToRectOrFocus(null, false);
1440
1441 if (mAttachInfo.mViewScrollChanged) {
1442 mAttachInfo.mViewScrollChanged = false;
1443 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1444 }
Romain Guy8506ab42009-06-11 17:35:47 -07001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001447 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1448 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 yoff = mScroller.getCurrY();
1450 } else {
1451 yoff = mScrollY;
1452 }
1453 if (mCurScrollY != yoff) {
1454 mCurScrollY = yoff;
1455 fullRedrawNeeded = true;
1456 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001457 float appScale = mAttachInfo.mApplicationScale;
1458 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001460 int resizeAlpha = 0;
1461 if (mResizeBitmap != null) {
1462 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1463 if (deltaTime < mResizeBitmapDuration) {
1464 float amt = deltaTime/(float)mResizeBitmapDuration;
1465 amt = mResizeInterpolator.getInterpolation(amt);
1466 animating = true;
1467 resizeAlpha = 255 - (int)(amt*255);
1468 } else {
1469 disposeResizeBitmap();
1470 }
1471 }
1472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001474 if (mSurfaceHolder != null) {
1475 // The app owns the surface, we won't draw.
1476 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001477 if (animating) {
1478 if (mScroller != null) {
1479 mScroller.abortAnimation();
1480 }
1481 disposeResizeBitmap();
1482 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001483 return;
1484 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001485
1486 if (fullRedrawNeeded) {
1487 mAttachInfo.mIgnoreDirtyState = true;
1488 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1489 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001490
Romain Guyb051e892010-09-28 19:09:36 -07001491 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001492 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001493 mIsAnimating = false;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001494 mHardwareYOffset = yoff;
1495 mResizeAlpha = resizeAlpha;
Romain Guy7d7b5492011-01-24 16:33:45 -08001496
1497 mCurrentDirty.set(dirty);
1498 mCurrentDirty.union(mPreviousDirty);
1499 mPreviousDirty.set(dirty);
1500 dirty.setEmpty();
1501
1502 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, mCurrentDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001504
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001505 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 mFullRedrawNeeded = true;
1507 scheduleTraversals();
1508 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 return;
1511 }
1512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001514 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 + mWindowAttributes.getTitle()
1516 + ": dirty={" + dirty.left + "," + dirty.top
1517 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001518 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1519 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001522 if (!dirty.isEmpty() || mIsAnimating) {
1523 Canvas canvas;
1524 try {
1525 int left = dirty.left;
1526 int top = dirty.top;
1527 int right = dirty.right;
1528 int bottom = dirty.bottom;
1529 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001530
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001531 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1532 bottom != dirty.bottom) {
1533 mAttachInfo.mIgnoreDirtyState = true;
1534 }
1535
1536 // TODO: Do this in native
1537 canvas.setDensity(mDensity);
1538 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001539 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001540 // TODO: we should ask the window manager to do something!
1541 // for now we just do nothing
1542 return;
1543 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001544 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001545 // TODO: we should ask the window manager to do something!
1546 // for now we just do nothing
1547 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001548 }
1549
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001550 try {
1551 if (!dirty.isEmpty() || mIsAnimating) {
1552 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001554 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001555 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001556 + canvas.getWidth() + ", h=" + canvas.getHeight());
1557 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559
Romain Guy5429e1d2010-09-07 12:38:00 -07001560 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001561 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001563
1564 // If this bitmap's format includes an alpha channel, we
1565 // need to clear it before drawing so that the child will
1566 // properly re-composite its drawing on a transparent
1567 // background. This automatically respects the clip/dirty region
1568 // or
1569 // If we are applying an offset, we need to clear the area
1570 // where the offset doesn't appear to avoid having garbage
1571 // left in the blank areas.
1572 if (!canvas.isOpaque() || yoff != 0) {
1573 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1574 }
1575
1576 dirty.setEmpty();
1577 mIsAnimating = false;
1578 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1579 mView.mPrivateFlags |= View.DRAWN;
1580
1581 if (DEBUG_DRAW) {
1582 Context cxt = mView.getContext();
1583 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1584 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1585 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1586 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001587 try {
1588 canvas.translate(0, -yoff);
1589 if (mTranslator != null) {
1590 mTranslator.translateCanvas(canvas);
1591 }
1592 canvas.setScreenDensity(scalingRequired
1593 ? DisplayMetrics.DENSITY_DEVICE : 0);
1594 mView.draw(canvas);
1595 } finally {
1596 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001597 }
1598
1599 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1600 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1601 }
1602
Romain Guy5429e1d2010-09-07 12:38:00 -07001603 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001604 int now = (int)SystemClock.elapsedRealtime();
1605 if (sDrawTime != 0) {
1606 nativeShowFPS(canvas, now - sDrawTime);
1607 }
1608 sDrawTime = now;
1609 }
1610
Romain Guy5429e1d2010-09-07 12:38:00 -07001611 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001612 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
1615
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001616 } finally {
1617 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 }
1620
1621 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001622 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
Romain Guy8506ab42009-06-11 17:35:47 -07001624
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001625 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 mFullRedrawNeeded = true;
1627 scheduleTraversals();
1628 }
1629 }
1630
1631 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1632 final View.AttachInfo attachInfo = mAttachInfo;
1633 final Rect ci = attachInfo.mContentInsets;
1634 final Rect vi = attachInfo.mVisibleInsets;
1635 int scrollY = 0;
1636 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 if (vi.left > ci.left || vi.top > ci.top
1639 || vi.right > ci.right || vi.bottom > ci.bottom) {
1640 // We'll assume that we aren't going to change the scroll
1641 // offset, since we want to avoid that unless it is actually
1642 // going to make the focus visible... otherwise we scroll
1643 // all over the place.
1644 scrollY = mScrollY;
1645 // We can be called for two different situations: during a draw,
1646 // to update the scroll position if the focus has changed (in which
1647 // case 'rectangle' is null), or in response to a
1648 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1649 // is non-null and we just want to scroll to whatever that
1650 // rectangle is).
1651 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001652
1653 // When in touch mode, focus points to the previously focused view,
1654 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001655 // line checks whether the view is still in our hierarchy.
1656 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001657 mRealFocusedView = null;
1658 return false;
1659 }
1660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 if (focus != mLastScrolledFocus) {
1662 // If the focus has changed, then ignore any requests to scroll
1663 // to a rectangle; first we want to make sure the entire focus
1664 // view is visible.
1665 rectangle = null;
1666 }
1667 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1668 + " rectangle=" + rectangle + " ci=" + ci
1669 + " vi=" + vi);
1670 if (focus == mLastScrolledFocus && !mScrollMayChange
1671 && rectangle == null) {
1672 // Optimization: if the focus hasn't changed since last
1673 // time, and no layout has happened, then just leave things
1674 // as they are.
1675 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1676 + mScrollY + " vi=" + vi.toShortString());
1677 } else if (focus != null) {
1678 // We need to determine if the currently focused view is
1679 // within the visible part of the window and, if not, apply
1680 // a pan so it can be seen.
1681 mLastScrolledFocus = focus;
1682 mScrollMayChange = false;
1683 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1684 // Try to find the rectangle from the focus view.
1685 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1686 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1687 + mView.getWidth() + " h=" + mView.getHeight()
1688 + " ci=" + ci.toShortString()
1689 + " vi=" + vi.toShortString());
1690 if (rectangle == null) {
1691 focus.getFocusedRect(mTempRect);
1692 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1693 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001694 if (mView instanceof ViewGroup) {
1695 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1696 focus, mTempRect);
1697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1699 "Focus in window: focusRect="
1700 + mTempRect.toShortString()
1701 + " visRect=" + mVisRect.toShortString());
1702 } else {
1703 mTempRect.set(rectangle);
1704 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1705 "Request scroll to rect: "
1706 + mTempRect.toShortString()
1707 + " visRect=" + mVisRect.toShortString());
1708 }
1709 if (mTempRect.intersect(mVisRect)) {
1710 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1711 "Focus window visible rect: "
1712 + mTempRect.toShortString());
1713 if (mTempRect.height() >
1714 (mView.getHeight()-vi.top-vi.bottom)) {
1715 // If the focus simply is not going to fit, then
1716 // best is probably just to leave things as-is.
1717 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1718 "Too tall; leaving scrollY=" + scrollY);
1719 } else if ((mTempRect.top-scrollY) < vi.top) {
1720 scrollY -= vi.top - (mTempRect.top-scrollY);
1721 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1722 "Top covered; scrollY=" + scrollY);
1723 } else if ((mTempRect.bottom-scrollY)
1724 > (mView.getHeight()-vi.bottom)) {
1725 scrollY += (mTempRect.bottom-scrollY)
1726 - (mView.getHeight()-vi.bottom);
1727 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1728 "Bottom covered; scrollY=" + scrollY);
1729 }
1730 handled = true;
1731 }
1732 }
1733 }
1734 }
Romain Guy8506ab42009-06-11 17:35:47 -07001735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 if (scrollY != mScrollY) {
1737 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1738 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001739 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 if (mScroller == null) {
1741 mScroller = new Scroller(mView.getContext());
1742 }
1743 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1744 } else if (mScroller != null) {
1745 mScroller.abortAnimation();
1746 }
1747 mScrollY = scrollY;
1748 }
Romain Guy8506ab42009-06-11 17:35:47 -07001749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 return handled;
1751 }
Romain Guy8506ab42009-06-11 17:35:47 -07001752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 public void requestChildFocus(View child, View focused) {
1754 checkThread();
1755 if (mFocusedView != focused) {
1756 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1757 scheduleTraversals();
1758 }
1759 mFocusedView = mRealFocusedView = focused;
1760 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1761 + mFocusedView);
1762 }
1763
1764 public void clearChildFocus(View child) {
1765 checkThread();
1766
1767 View oldFocus = mFocusedView;
1768
1769 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1770 mFocusedView = mRealFocusedView = null;
1771 if (mView != null && !mView.hasFocus()) {
1772 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1773 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1774 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1775 }
1776 } else if (oldFocus != null) {
1777 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1778 }
1779 }
1780
1781
1782 public void focusableViewAvailable(View v) {
1783 checkThread();
1784
1785 if (mView != null && !mView.hasFocus()) {
1786 v.requestFocus();
1787 } else {
1788 // the one case where will transfer focus away from the current one
1789 // is if the current view is a view group that prefers to give focus
1790 // to its children first AND the view is a descendant of it.
1791 mFocusedView = mView.findFocus();
1792 boolean descendantsHaveDibsOnFocus =
1793 (mFocusedView instanceof ViewGroup) &&
1794 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1795 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1796 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1797 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1798 v.requestFocus();
1799 }
1800 }
1801 }
1802
1803 public void recomputeViewAttributes(View child) {
1804 checkThread();
1805 if (mView == child) {
1806 mAttachInfo.mRecomputeGlobalAttributes = true;
1807 if (!mWillDrawSoon) {
1808 scheduleTraversals();
1809 }
1810 }
1811 }
1812
1813 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001814 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 mView.dispatchDetachedFromWindow();
1816 }
1817
1818 mView = null;
1819 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001820 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821
Romain Guy29d89972010-09-22 16:10:57 -07001822 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001823
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001824 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001826 if (mInputChannel != null) {
1827 if (mInputQueueCallback != null) {
1828 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1829 mInputQueueCallback = null;
1830 } else {
1831 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001832 }
1833 }
1834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 try {
1836 sWindowSession.remove(mWindow);
1837 } catch (RemoteException e) {
1838 }
Jeff Brown349703e2010-06-22 01:27:15 -07001839
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001840 // Dispose the input channel after removing the window so the Window Manager
1841 // doesn't interpret the input channel being closed as an abnormal termination.
1842 if (mInputChannel != null) {
1843 mInputChannel.dispose();
1844 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
Romain Guy8506ab42009-06-11 17:35:47 -07001847
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001848 void updateConfiguration(Configuration config, boolean force) {
1849 if (DEBUG_CONFIGURATION) Log.v(TAG,
1850 "Applying new config to window "
1851 + mWindowAttributes.getTitle()
1852 + ": " + config);
1853 synchronized (sConfigCallbacks) {
1854 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1855 sConfigCallbacks.get(i).onConfigurationChanged(config);
1856 }
1857 }
1858 if (mView != null) {
1859 // At this point the resources have been updated to
1860 // have the most recent config, whatever that is. Use
1861 // the on in them which may be newer.
1862 if (mView != null) {
1863 config = mView.getResources().getConfiguration();
1864 }
1865 if (force || mLastConfiguration.diff(config) != 0) {
1866 mLastConfiguration.setTo(config);
1867 mView.dispatchConfigurationChanged(config);
1868 }
1869 }
1870 }
1871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 /**
1873 * Return true if child is an ancestor of parent, (or equal to the parent).
1874 */
1875 private static boolean isViewDescendantOf(View child, View parent) {
1876 if (child == parent) {
1877 return true;
1878 }
1879
1880 final ViewParent theParent = child.getParent();
1881 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1882 }
1883
Romain Guycdb86672010-03-18 18:54:50 -07001884 private static void forceLayout(View view) {
1885 view.forceLayout();
1886 if (view instanceof ViewGroup) {
1887 ViewGroup group = (ViewGroup) view;
1888 final int count = group.getChildCount();
1889 for (int i = 0; i < count; i++) {
1890 forceLayout(group.getChildAt(i));
1891 }
1892 }
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894
1895 public final static int DO_TRAVERSAL = 1000;
1896 public final static int DIE = 1001;
1897 public final static int RESIZED = 1002;
1898 public final static int RESIZED_REPORT = 1003;
1899 public final static int WINDOW_FOCUS_CHANGED = 1004;
1900 public final static int DISPATCH_KEY = 1005;
1901 public final static int DISPATCH_POINTER = 1006;
1902 public final static int DISPATCH_TRACKBALL = 1007;
1903 public final static int DISPATCH_APP_VISIBILITY = 1008;
1904 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1905 public final static int FINISHED_EVENT = 1010;
1906 public final static int DISPATCH_KEY_FROM_IME = 1011;
1907 public final static int FINISH_INPUT_CONNECTION = 1012;
1908 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001909 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001910 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001911 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08001912 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913
1914 @Override
1915 public void handleMessage(Message msg) {
1916 switch (msg.what) {
1917 case View.AttachInfo.INVALIDATE_MSG:
1918 ((View) msg.obj).invalidate();
1919 break;
1920 case View.AttachInfo.INVALIDATE_RECT_MSG:
1921 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1922 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1923 info.release();
1924 break;
1925 case DO_TRAVERSAL:
1926 if (mProfile) {
1927 Debug.startMethodTracing("ViewRoot");
1928 }
1929
1930 performTraversals();
1931
1932 if (mProfile) {
1933 Debug.stopMethodTracing();
1934 mProfile = false;
1935 }
1936 break;
1937 case FINISHED_EVENT:
1938 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1939 break;
1940 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001941 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001943 case DISPATCH_POINTER:
1944 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1945 break;
1946 case DISPATCH_TRACKBALL:
1947 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1948 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 case DISPATCH_APP_VISIBILITY:
1950 handleAppVisibility(msg.arg1 != 0);
1951 break;
1952 case DISPATCH_GET_NEW_SURFACE:
1953 handleGetNewSurface();
1954 break;
1955 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001956 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001959 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001960 && mPendingVisibleInsets.equals(ri.visibleInsets)
1961 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 break;
1963 }
1964 // fall through...
1965 case RESIZED_REPORT:
1966 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001967 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1968 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001969 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 mWinFrame.left = 0;
1972 mWinFrame.right = msg.arg1;
1973 mWinFrame.top = 0;
1974 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001975 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1976 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 if (msg.what == RESIZED_REPORT) {
1978 mReportNextDraw = true;
1979 }
Romain Guycdb86672010-03-18 18:54:50 -07001980
1981 if (mView != null) {
1982 forceLayout(mView);
1983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 requestLayout();
1985 }
1986 break;
1987 case WINDOW_FOCUS_CHANGED: {
1988 if (mAdded) {
1989 boolean hasWindowFocus = msg.arg1 != 0;
1990 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1991 if (hasWindowFocus) {
1992 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001993 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994
Romain Guyc361da82010-10-25 15:29:10 -07001995 if (mAttachInfo.mHardwareRenderer != null &&
1996 mSurface != null && mSurface.isValid()) {
Romain Guy7d7b5492011-01-24 16:33:45 -08001997 mFullRedrawNeeded = true;
Romain Guyb051e892010-09-28 19:09:36 -07001998 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1999 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 }
2001 }
Romain Guy8506ab42009-06-11 17:35:47 -07002002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 mLastWasImTarget = WindowManager.LayoutParams
2004 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 InputMethodManager imm = InputMethodManager.peekInstance();
2007 if (mView != null) {
2008 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2009 imm.startGettingWindowFocus(mView);
2010 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002011 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 mView.dispatchWindowFocusChanged(hasWindowFocus);
2013 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 // Note: must be done after the focus change callbacks,
2016 // so all of the view state is set up correctly.
2017 if (hasWindowFocus) {
2018 if (imm != null && mLastWasImTarget) {
2019 imm.onWindowFocus(mView, mView.findFocus(),
2020 mWindowAttributes.softInputMode,
2021 !mHasHadWindowFocus, mWindowAttributes.flags);
2022 }
2023 // Clear the forward bit. We can just do this directly, since
2024 // the window manager doesn't care about it.
2025 mWindowAttributes.softInputMode &=
2026 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2027 ((WindowManager.LayoutParams)mView.getLayoutParams())
2028 .softInputMode &=
2029 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2030 mHasHadWindowFocus = true;
2031 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002032
2033 if (hasWindowFocus && mView != null) {
2034 sendAccessibilityEvents();
2035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
2037 } break;
2038 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002039 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002041 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002043 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002045 KeyEvent event = (KeyEvent)msg.obj;
2046 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2047 // The IME is trying to say this event is from the
2048 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002049 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002050 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002051 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002052 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 case FINISH_INPUT_CONNECTION: {
2054 InputMethodManager imm = InputMethodManager.peekInstance();
2055 if (imm != null) {
2056 imm.reportFinishInputConnection((InputConnection)msg.obj);
2057 }
2058 } break;
2059 case CHECK_FOCUS: {
2060 InputMethodManager imm = InputMethodManager.peekInstance();
2061 if (imm != null) {
2062 imm.checkFocus();
2063 }
2064 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002065 case CLOSE_SYSTEM_DIALOGS: {
2066 if (mView != null) {
2067 mView.onCloseSystemDialogs((String)msg.obj);
2068 }
2069 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002070 case DISPATCH_DRAG_EVENT:
2071 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002072 DragEvent event = (DragEvent)msg.obj;
2073 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2074 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002075 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002076 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2077 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2078 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002081
Jeff Brown3915bb82010-11-05 15:02:16 -07002082 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002083 if (mFinishedCallback != null) {
2084 Slog.w(TAG, "Received a new input event from the input queue but there is "
2085 + "already an unfinished input event in progress.");
2086 }
2087
2088 mFinishedCallback = finishedCallback;
2089 }
2090
Jeff Brown3915bb82010-11-05 15:02:16 -07002091 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002092 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002093
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002094 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002095 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002096 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002097 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002098 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2099 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002100 }
2101 }
2102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 /**
2104 * Something in the current window tells us we need to change the touch mode. For
2105 * example, we are not in touch mode, and the user touches the screen.
2106 *
2107 * If the touch mode has changed, tell the window manager, and handle it locally.
2108 *
2109 * @param inTouchMode Whether we want to be in touch mode.
2110 * @return True if the touch mode changed and focus changed was changed as a result
2111 */
2112 boolean ensureTouchMode(boolean inTouchMode) {
2113 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2114 + "touch mode is " + mAttachInfo.mInTouchMode);
2115 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2116
2117 // tell the window manager
2118 try {
2119 sWindowSession.setInTouchMode(inTouchMode);
2120 } catch (RemoteException e) {
2121 throw new RuntimeException(e);
2122 }
2123
2124 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002125 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
2127
2128 /**
2129 * Ensure that the touch mode for this window is set, and if it is changing,
2130 * take the appropriate action.
2131 * @param inTouchMode Whether we want to be in touch mode.
2132 * @return True if the touch mode changed and focus changed was changed as a result
2133 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002134 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2136 + "touch mode is " + mAttachInfo.mInTouchMode);
2137
2138 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2139
2140 mAttachInfo.mInTouchMode = inTouchMode;
2141 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2142
Romain Guy2d4cff62010-04-09 15:39:00 -07002143 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 }
2145
2146 private boolean enterTouchMode() {
2147 if (mView != null) {
2148 if (mView.hasFocus()) {
2149 // note: not relying on mFocusedView here because this could
2150 // be when the window is first being added, and mFocused isn't
2151 // set yet.
2152 final View focused = mView.findFocus();
2153 if (focused != null && !focused.isFocusableInTouchMode()) {
2154
2155 final ViewGroup ancestorToTakeFocus =
2156 findAncestorToTakeFocusInTouchMode(focused);
2157 if (ancestorToTakeFocus != null) {
2158 // there is an ancestor that wants focus after its descendants that
2159 // is focusable in touch mode.. give it focus
2160 return ancestorToTakeFocus.requestFocus();
2161 } else {
2162 // nothing appropriate to have focus in touch mode, clear it out
2163 mView.unFocus();
2164 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2165 mFocusedView = null;
2166 return true;
2167 }
2168 }
2169 }
2170 }
2171 return false;
2172 }
2173
2174
2175 /**
2176 * Find an ancestor of focused that wants focus after its descendants and is
2177 * focusable in touch mode.
2178 * @param focused The currently focused view.
2179 * @return An appropriate view, or null if no such view exists.
2180 */
2181 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2182 ViewParent parent = focused.getParent();
2183 while (parent instanceof ViewGroup) {
2184 final ViewGroup vgParent = (ViewGroup) parent;
2185 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2186 && vgParent.isFocusableInTouchMode()) {
2187 return vgParent;
2188 }
2189 if (vgParent.isRootNamespace()) {
2190 return null;
2191 } else {
2192 parent = vgParent.getParent();
2193 }
2194 }
2195 return null;
2196 }
2197
2198 private boolean leaveTouchMode() {
2199 if (mView != null) {
2200 if (mView.hasFocus()) {
2201 // i learned the hard way to not trust mFocusedView :)
2202 mFocusedView = mView.findFocus();
2203 if (!(mFocusedView instanceof ViewGroup)) {
2204 // some view has focus, let it keep it
2205 return false;
2206 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2207 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2208 // some view group has focus, and doesn't prefer its children
2209 // over itself for focus, so let them keep it.
2210 return false;
2211 }
2212 }
2213
2214 // find the best view to give focus to in this brave new non-touch-mode
2215 // world
2216 final View focused = focusSearch(null, View.FOCUS_DOWN);
2217 if (focused != null) {
2218 return focused.requestFocus(View.FOCUS_DOWN);
2219 }
2220 }
2221 return false;
2222 }
2223
Jeff Brown3915bb82010-11-05 15:02:16 -07002224 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2225 // If there is no view, then the event will not be handled.
2226 if (mView == null || !mAdded) {
2227 finishPointerEvent(event, sendDone, false);
2228 return;
2229 }
2230
2231 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002232 if (mTranslator != null) {
2233 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 }
2235
Jeff Brown3915bb82010-11-05 15:02:16 -07002236 // Enter touch mode on the down.
2237 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2238 if (isDown) {
2239 ensureTouchMode(true);
2240 }
2241 if(Config.LOGV) {
2242 captureMotionLog("captureDispatchPointer", event);
2243 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002244
Jeff Brown3915bb82010-11-05 15:02:16 -07002245 // Offset the scroll position.
2246 if (mCurScrollY != 0) {
2247 event.offsetLocation(0, mCurScrollY);
2248 }
2249 if (MEASURE_LATENCY) {
2250 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2251 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002252
Jeff Brown3915bb82010-11-05 15:02:16 -07002253 // Remember the touch position for possible drag-initiation.
2254 mLastTouchPoint.x = event.getRawX();
2255 mLastTouchPoint.y = event.getRawY();
2256
2257 // Dispatch touch to view hierarchy.
2258 boolean handled = mView.dispatchTouchEvent(event);
2259 if (MEASURE_LATENCY) {
2260 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2261 }
2262 if (handled) {
2263 finishPointerEvent(event, sendDone, true);
2264 return;
2265 }
2266
2267 // Apply edge slop and try again, if appropriate.
2268 final int edgeFlags = event.getEdgeFlags();
2269 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2270 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2271 int direction = View.FOCUS_UP;
2272 int x = (int)event.getX();
2273 int y = (int)event.getY();
2274 final int[] deltas = new int[2];
2275
2276 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2277 direction = View.FOCUS_DOWN;
2278 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2279 deltas[0] = edgeSlop;
2280 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002281 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002282 deltas[0] = -edgeSlop;
2283 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002284 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002285 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2286 direction = View.FOCUS_UP;
2287 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2288 deltas[0] = edgeSlop;
2289 x += edgeSlop;
2290 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2291 deltas[0] = -edgeSlop;
2292 x -= edgeSlop;
2293 }
2294 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2295 direction = View.FOCUS_RIGHT;
2296 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2297 direction = View.FOCUS_LEFT;
2298 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002299
Jeff Brown3915bb82010-11-05 15:02:16 -07002300 View nearest = FocusFinder.getInstance().findNearestTouchable(
2301 ((ViewGroup) mView), x, y, direction, deltas);
2302 if (nearest != null) {
2303 event.offsetLocation(deltas[0], deltas[1]);
2304 event.setEdgeFlags(0);
2305 if (mView.dispatchTouchEvent(event)) {
2306 finishPointerEvent(event, sendDone, true);
2307 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002308 }
2309 }
2310 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002311
2312 // Pointer event was unhandled.
2313 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002314 }
2315
Jeff Brown3915bb82010-11-05 15:02:16 -07002316 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2317 event.recycle();
2318 if (sendDone) {
2319 finishInputEvent(handled);
2320 }
2321 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2322 }
2323
2324 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2326
Jeff Brown3915bb82010-11-05 15:02:16 -07002327 // If there is no view, then the event will not be handled.
2328 if (mView == null || !mAdded) {
2329 finishTrackballEvent(event, sendDone, false);
2330 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
2332
Jeff Brown3915bb82010-11-05 15:02:16 -07002333 // Deliver the trackball event to the view.
2334 if (mView.dispatchTrackballEvent(event)) {
2335 // If we reach this, we delivered a trackball event to mView and
2336 // mView consumed it. Because we will not translate the trackball
2337 // event into a key event, touch mode will not exit, so we exit
2338 // touch mode here.
2339 ensureTouchMode(false);
2340
2341 finishTrackballEvent(event, sendDone, true);
2342 mLastTrackballTime = Integer.MIN_VALUE;
2343 return;
2344 }
2345
2346 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 final TrackballAxis x = mTrackballAxisX;
2348 final TrackballAxis y = mTrackballAxisY;
2349
2350 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002351 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 // It has been too long since the last movement,
2353 // so restart at the beginning.
2354 x.reset(0);
2355 y.reset(0);
2356 mLastTrackballTime = curTime;
2357 }
2358
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002359 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002360 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002361 switch (action) {
2362 case MotionEvent.ACTION_DOWN:
2363 x.reset(2);
2364 y.reset(2);
2365 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002366 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2367 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2368 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002369 break;
2370 case MotionEvent.ACTION_UP:
2371 x.reset(2);
2372 y.reset(2);
2373 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002374 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2375 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2376 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002377 break;
2378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002380 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2381 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2382 + " move=" + event.getX()
2383 + " / Y=" + y.position + " step="
2384 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2385 + " move=" + event.getY());
2386 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2387 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002389 // Generate DPAD events based on the trackball movement.
2390 // We pick the axis that has moved the most as the direction of
2391 // the DPAD. When we generate DPAD events for one axis, then the
2392 // other axis is reset -- we don't want to perform DPAD jumps due
2393 // to slight movements in the trackball when making major movements
2394 // along the other axis.
2395 int keycode = 0;
2396 int movement = 0;
2397 float accel = 1;
2398 if (xOff > yOff) {
2399 movement = x.generate((2/event.getXPrecision()));
2400 if (movement != 0) {
2401 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2402 : KeyEvent.KEYCODE_DPAD_LEFT;
2403 accel = x.acceleration;
2404 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002406 } else if (yOff > 0) {
2407 movement = y.generate((2/event.getYPrecision()));
2408 if (movement != 0) {
2409 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2410 : KeyEvent.KEYCODE_DPAD_UP;
2411 accel = y.acceleration;
2412 x.reset(2);
2413 }
2414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002416 if (keycode != 0) {
2417 if (movement < 0) movement = -movement;
2418 int accelMovement = (int)(movement * accel);
2419 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2420 + " accelMovement=" + accelMovement
2421 + " accel=" + accel);
2422 if (accelMovement > movement) {
2423 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2424 + keycode);
2425 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002426 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002427 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002428 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2429 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2430 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002432 while (movement > 0) {
2433 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2434 + keycode);
2435 movement--;
2436 curTime = SystemClock.uptimeMillis();
2437 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002438 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2439 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2440 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002441 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002442 KeyEvent.ACTION_UP, keycode, 0, metaState,
2443 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2444 InputDevice.SOURCE_KEYBOARD), false);
2445 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002446 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002448
2449 // Unfortunately we can't tell whether the application consumed the keys, so
2450 // we always consider the trackball event handled.
2451 finishTrackballEvent(event, sendDone, true);
2452 }
2453
2454 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2455 event.recycle();
2456 if (sendDone) {
2457 finishInputEvent(handled);
2458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 }
2460
2461 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002462 * Returns true if the key is used for keyboard navigation.
2463 * @param keyEvent The key event.
2464 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002466 private static boolean isNavigationKey(KeyEvent keyEvent) {
2467 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 case KeyEvent.KEYCODE_DPAD_LEFT:
2469 case KeyEvent.KEYCODE_DPAD_RIGHT:
2470 case KeyEvent.KEYCODE_DPAD_UP:
2471 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002472 case KeyEvent.KEYCODE_DPAD_CENTER:
2473 case KeyEvent.KEYCODE_PAGE_UP:
2474 case KeyEvent.KEYCODE_PAGE_DOWN:
2475 case KeyEvent.KEYCODE_MOVE_HOME:
2476 case KeyEvent.KEYCODE_MOVE_END:
2477 case KeyEvent.KEYCODE_TAB:
2478 case KeyEvent.KEYCODE_SPACE:
2479 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 return true;
2481 }
2482 return false;
2483 }
2484
2485 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002486 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002488 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002490 private static boolean isTypingKey(KeyEvent keyEvent) {
2491 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002495 * See if the key event means we should leave touch mode (and leave touch mode if so).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 * @param event The key event.
2497 * @return Whether this key event should be consumed (meaning the act of
2498 * leaving touch mode alone is considered the event).
2499 */
2500 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002501 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 if (!mAttachInfo.mInTouchMode) {
2503 return false;
2504 }
2505
Jeff Brown4e6319b2010-12-13 10:36:51 -08002506 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2507 final int action = event.getAction();
2508 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 return false;
2510 }
2511
Jeff Brown4e6319b2010-12-13 10:36:51 -08002512 // Don't leave touch mode if the IME told us not to.
2513 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2514 return false;
2515 }
2516
2517 // If the key can be used for keyboard navigation then leave touch mode
2518 // and select a focused view if needed (in ensureTouchMode).
2519 // When a new focused view is selected, we consume the navigation key because
2520 // navigation doesn't make much sense unless a view already has focus so
2521 // the key's purpose is to set focus.
2522 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 return ensureTouchMode(false);
2524 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002525
2526 // If the key can be used for typing then leave touch mode
2527 // and select a focused view if needed (in ensureTouchMode).
2528 // Always allow the view to process the typing key.
2529 if (isTypingKey(event)) {
2530 ensureTouchMode(false);
2531 return false;
2532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 return false;
2535 }
2536
2537 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002538 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 */
2540 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002541 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 if (ev == null ||
2543 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2544 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
Romain Guy8506ab42009-06-11 17:35:47 -07002546
2547 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 sb.append(ev.getDownTime()).append(',');
2549 sb.append(ev.getEventTime()).append(',');
2550 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002551 sb.append(ev.getX()).append(',');
2552 sb.append(ev.getY()).append(',');
2553 sb.append(ev.getPressure()).append(',');
2554 sb.append(ev.getSize()).append(',');
2555 sb.append(ev.getMetaState()).append(',');
2556 sb.append(ev.getXPrecision()).append(',');
2557 sb.append(ev.getYPrecision()).append(',');
2558 sb.append(ev.getDeviceId()).append(',');
2559 sb.append(ev.getEdgeFlags());
2560 Log.d(TAG, sb.toString());
2561 }
2562 /**
2563 * log motion events
2564 */
2565 private static void captureKeyLog(String subTag, KeyEvent ev) {
2566 //check dynamic switch
2567 if (ev == null ||
2568 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2569 return;
2570 }
2571 StringBuilder sb = new StringBuilder(subTag + ": ");
2572 sb.append(ev.getDownTime()).append(',');
2573 sb.append(ev.getEventTime()).append(',');
2574 sb.append(ev.getAction()).append(',');
2575 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 sb.append(ev.getRepeatCount()).append(',');
2577 sb.append(ev.getMetaState()).append(',');
2578 sb.append(ev.getDeviceId()).append(',');
2579 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002580 Log.d(TAG, sb.toString());
2581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582
2583 int enqueuePendingEvent(Object event, boolean sendDone) {
2584 int seq = mPendingEventSeq+1;
2585 if (seq < 0) seq = 0;
2586 mPendingEventSeq = seq;
2587 mPendingEvents.put(seq, event);
2588 return sendDone ? seq : -seq;
2589 }
2590
2591 Object retrievePendingEvent(int seq) {
2592 if (seq < 0) seq = -seq;
2593 Object event = mPendingEvents.get(seq);
2594 if (event != null) {
2595 mPendingEvents.remove(seq);
2596 }
2597 return event;
2598 }
Romain Guy8506ab42009-06-11 17:35:47 -07002599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002601 // If there is no view, then the event will not be handled.
2602 if (mView == null || !mAdded) {
2603 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 return;
2605 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002606
2607 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2608
2609 // Perform predispatching before the IME.
2610 if (mView.dispatchKeyEventPreIme(event)) {
2611 finishKeyEvent(event, sendDone, true);
2612 return;
2613 }
2614
2615 // Dispatch to the IME before propagating down the view hierarchy.
2616 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 if (mLastWasImTarget) {
2618 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002619 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 int seq = enqueuePendingEvent(event, sendDone);
2621 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2622 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002623 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 return;
2625 }
2626 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002627
2628 // Not dispatching to IME, continue with post IME actions.
2629 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 }
2631
Jeff Brown3915bb82010-11-05 15:02:16 -07002632 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2634 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2635 + " handled=" + handled + " event=" + event);
2636 if (event != null) {
2637 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002638 if (handled) {
2639 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002641 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643 }
2644 }
Romain Guy8506ab42009-06-11 17:35:47 -07002645
Jeff Brown3915bb82010-11-05 15:02:16 -07002646 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2647 // If the view went away, then the event will not be handled.
2648 if (mView == null || !mAdded) {
2649 finishKeyEvent(event, sendDone, false);
2650 return;
2651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652
Jeff Brown3915bb82010-11-05 15:02:16 -07002653 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2654 if (checkForLeavingTouchModeAndConsume(event)) {
2655 finishKeyEvent(event, sendDone, true);
2656 return;
2657 }
Romain Guy8506ab42009-06-11 17:35:47 -07002658
Jeff Brown3915bb82010-11-05 15:02:16 -07002659 if (Config.LOGV) {
2660 captureKeyLog("captureDispatchKeyEvent", event);
2661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662
Jeff Brown90655042010-12-02 13:50:46 -08002663 // Make sure the fallback event policy sees all keys that will be delivered to the
2664 // view hierarchy.
2665 mFallbackEventHandler.preDispatchKeyEvent(event);
2666
Jeff Brown3915bb82010-11-05 15:02:16 -07002667 // Deliver the key to the view hierarchy.
2668 if (mView.dispatchKeyEvent(event)) {
2669 finishKeyEvent(event, sendDone, true);
2670 return;
2671 }
Joe Onorato86f67862010-11-05 18:57:34 -07002672
Jeff Brownc1df9072010-12-21 16:38:50 -08002673 // If the Control modifier is held, try to interpret the key as a shortcut.
2674 if (event.getAction() == KeyEvent.ACTION_UP
2675 && event.isCtrlPressed()
2676 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2677 if (mView.dispatchKeyShortcutEvent(event)) {
2678 finishKeyEvent(event, sendDone, true);
2679 return;
2680 }
2681 }
2682
Jeff Brown3915bb82010-11-05 15:02:16 -07002683 // Apply the fallback event policy.
2684 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2685 finishKeyEvent(event, sendDone, true);
2686 return;
2687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688
Jeff Brown3915bb82010-11-05 15:02:16 -07002689 // Handle automatic focus changes.
2690 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2691 int direction = 0;
2692 switch (event.getKeyCode()) {
2693 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002694 if (event.hasNoModifiers()) {
2695 direction = View.FOCUS_LEFT;
2696 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002697 break;
2698 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002699 if (event.hasNoModifiers()) {
2700 direction = View.FOCUS_RIGHT;
2701 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002702 break;
2703 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002704 if (event.hasNoModifiers()) {
2705 direction = View.FOCUS_UP;
2706 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002707 break;
2708 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002709 if (event.hasNoModifiers()) {
2710 direction = View.FOCUS_DOWN;
2711 }
2712 break;
2713 case KeyEvent.KEYCODE_TAB:
2714 if (event.hasNoModifiers()) {
2715 direction = View.FOCUS_FORWARD;
2716 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2717 direction = View.FOCUS_BACKWARD;
2718 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002719 break;
2720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721
Jeff Brown3915bb82010-11-05 15:02:16 -07002722 if (direction != 0) {
2723 View focused = mView != null ? mView.findFocus() : null;
2724 if (focused != null) {
2725 View v = focused.focusSearch(direction);
2726 if (v != null && v != focused) {
2727 // do the math the get the interesting rect
2728 // of previous focused into the coord system of
2729 // newly focused view
2730 focused.getFocusedRect(mTempRect);
2731 if (mView instanceof ViewGroup) {
2732 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2733 focused, mTempRect);
2734 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2735 v, mTempRect);
2736 }
2737 if (v.requestFocus(direction, mTempRect)) {
2738 playSoundEffect(
2739 SoundEffectConstants.getContantForFocusDirection(direction));
2740 finishKeyEvent(event, sendDone, true);
2741 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 }
2743 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002744
2745 // Give the focused view a last chance to handle the dpad key.
2746 if (mView.dispatchUnhandledMove(focused, direction)) {
2747 finishKeyEvent(event, sendDone, true);
2748 return;
2749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 }
2751 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753
Jeff Brown3915bb82010-11-05 15:02:16 -07002754 // Key was unhandled.
2755 finishKeyEvent(event, sendDone, false);
2756 }
2757
2758 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2759 if (sendDone) {
2760 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 }
2762 }
2763
Christopher Tatea53146c2010-09-07 11:57:52 -07002764 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002765 void setLocalDragState(Object obj) {
2766 mLocalDragState = obj;
2767 }
2768
Christopher Tatea53146c2010-09-07 11:57:52 -07002769 private void handleDragEvent(DragEvent event) {
2770 // From the root, only drag start/end/location are dispatched. entered/exited
2771 // are determined and dispatched by the viewgroup hierarchy, who then report
2772 // that back here for ultimate reporting back to the framework.
2773 if (mView != null && mAdded) {
2774 final int what = event.mAction;
2775
2776 if (what == DragEvent.ACTION_DRAG_EXITED) {
2777 // A direct EXITED event means that the window manager knows we've just crossed
2778 // a window boundary, so the current drag target within this one must have
2779 // just been exited. Send it the usual notifications and then we're done
2780 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002781 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002782 } else {
2783 // Cache the drag description when the operation starts, then fill it in
2784 // on subsequent calls as a convenience
2785 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002786 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002787 mDragDescription = event.mClipDescription;
2788 } else {
2789 event.mClipDescription = mDragDescription;
2790 }
2791
2792 // For events with a [screen] location, translate into window coordinates
2793 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2794 mDragPoint.set(event.mX, event.mY);
2795 if (mTranslator != null) {
2796 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2797 }
2798
2799 if (mCurScrollY != 0) {
2800 mDragPoint.offset(0, mCurScrollY);
2801 }
2802
2803 event.mX = mDragPoint.x;
2804 event.mY = mDragPoint.y;
2805 }
2806
2807 // Remember who the current drag target is pre-dispatch
2808 final View prevDragView = mCurrentDragView;
2809
2810 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002811 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002812
2813 // If we changed apparent drag target, tell the OS about it
2814 if (prevDragView != mCurrentDragView) {
2815 try {
2816 if (prevDragView != null) {
2817 sWindowSession.dragRecipientExited(mWindow);
2818 }
2819 if (mCurrentDragView != null) {
2820 sWindowSession.dragRecipientEntered(mWindow);
2821 }
2822 } catch (RemoteException e) {
2823 Slog.e(TAG, "Unable to note drag target change");
2824 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002825 }
Chris Tated4533f12010-10-19 15:15:08 -07002826
Christopher Tate407b4e92010-11-30 17:14:08 -08002827 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002828 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002829 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002830 try {
2831 Log.i(TAG, "Reporting drop result: " + result);
2832 sWindowSession.reportDropResult(mWindow, result);
2833 } catch (RemoteException e) {
2834 Log.e(TAG, "Unable to report drop result");
2835 }
2836 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002837
2838 // When the drag operation ends, release any local state object
2839 // that may have been in use
2840 if (what == DragEvent.ACTION_DRAG_ENDED) {
2841 setLocalDragState(null);
2842 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002843 }
2844 }
2845 event.recycle();
2846 }
2847
Joe Onorato664644d2011-01-23 17:53:23 -08002848 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
2849 if (mView == null) return;
2850 mView.dispatchSystemUiVisibilityChanged(visibility);
2851 }
2852
Christopher Tate2c095f32010-10-04 14:13:40 -07002853 public void getLastTouchPoint(Point outLocation) {
2854 outLocation.x = (int) mLastTouchPoint.x;
2855 outLocation.y = (int) mLastTouchPoint.y;
2856 }
2857
Chris Tate9d1ab882010-11-02 15:55:39 -07002858 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002859 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002860 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002861 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002862 }
2863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 private AudioManager getAudioManager() {
2865 if (mView == null) {
2866 throw new IllegalStateException("getAudioManager called when there is no mView");
2867 }
2868 if (mAudioManager == null) {
2869 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2870 }
2871 return mAudioManager;
2872 }
2873
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002874 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2875 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002876
2877 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002878 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002879 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002880 restore = true;
2881 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002882 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002883 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002884 if (params != null) {
2885 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002886 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002887 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002888 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002889 int relayoutResult = sWindowSession.relayout(
2890 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002891 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2892 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002893 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002894 mPendingContentInsets, mPendingVisibleInsets,
2895 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002896 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002897 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002898 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002899 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002900
2901 if (mTranslator != null) {
2902 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2903 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2904 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002905 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002906 return relayoutResult;
2907 }
Romain Guy8506ab42009-06-11 17:35:47 -07002908
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002909 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 * {@inheritDoc}
2911 */
2912 public void playSoundEffect(int effectId) {
2913 checkThread();
2914
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002915 try {
2916 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002918 switch (effectId) {
2919 case SoundEffectConstants.CLICK:
2920 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2921 return;
2922 case SoundEffectConstants.NAVIGATION_DOWN:
2923 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2924 return;
2925 case SoundEffectConstants.NAVIGATION_LEFT:
2926 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2927 return;
2928 case SoundEffectConstants.NAVIGATION_RIGHT:
2929 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2930 return;
2931 case SoundEffectConstants.NAVIGATION_UP:
2932 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2933 return;
2934 default:
2935 throw new IllegalArgumentException("unknown effect id " + effectId +
2936 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2937 }
2938 } catch (IllegalStateException e) {
2939 // Exception thrown by getAudioManager() when mView is null
2940 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2941 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
2943 }
2944
2945 /**
2946 * {@inheritDoc}
2947 */
2948 public boolean performHapticFeedback(int effectId, boolean always) {
2949 try {
2950 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2951 } catch (RemoteException e) {
2952 return false;
2953 }
2954 }
2955
2956 /**
2957 * {@inheritDoc}
2958 */
2959 public View focusSearch(View focused, int direction) {
2960 checkThread();
2961 if (!(mView instanceof ViewGroup)) {
2962 return null;
2963 }
2964 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2965 }
2966
2967 public void debug() {
2968 mView.debug();
2969 }
2970
2971 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002972 if (immediate) {
2973 doDie();
2974 } else {
2975 sendEmptyMessage(DIE);
2976 }
2977 }
2978
2979 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002981 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 synchronized (this) {
2983 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002984 destroyHardwareRenderer();
2985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 int viewVisibility = mView.getVisibility();
2987 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2988 if (mWindowAttributesChanged || viewVisibilityChanged) {
2989 // If layout params have been changed, first give them
2990 // to the window manager to make sure it has the correct
2991 // animation info.
2992 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002993 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2994 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 sWindowSession.finishDrawing(mWindow);
2996 }
2997 } catch (RemoteException e) {
2998 }
2999 }
3000
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003001 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 }
3003 if (mAdded) {
3004 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003005 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 }
3007 }
3008 }
3009
Romain Guy29d89972010-09-22 16:10:57 -07003010 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003011 if (mAttachInfo.mHardwareRenderer != null) {
3012 mAttachInfo.mHardwareRenderer.destroy(true);
3013 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003014 mAttachInfo.mHardwareAccelerated = false;
3015 }
3016 }
3017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 public void dispatchFinishedEvent(int seq, boolean handled) {
3019 Message msg = obtainMessage(FINISHED_EVENT);
3020 msg.arg1 = seq;
3021 msg.arg2 = handled ? 1 : 0;
3022 sendMessage(msg);
3023 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003026 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3028 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3029 + " visibleInsets=" + visibleInsets.toShortString()
3030 + " reportDraw=" + reportDraw);
3031 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003032 if (mTranslator != null) {
3033 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3034 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3035 w *= mTranslator.applicationInvertedScale;
3036 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003037 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003038 msg.arg1 = w;
3039 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003040 ResizedInfo ri = new ResizedInfo();
3041 ri.coveredInsets = new Rect(coveredInsets);
3042 ri.visibleInsets = new Rect(visibleInsets);
3043 ri.newConfig = newConfig;
3044 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 sendMessage(msg);
3046 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003047
Jeff Brown3915bb82010-11-05 15:02:16 -07003048 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003049
3050 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003051 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003052 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003053 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003054 }
3055
Jeff Brown3915bb82010-11-05 15:02:16 -07003056 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003057 startInputEvent(finishedCallback);
3058 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003059 }
3060 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061
3062 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003063 dispatchKey(event, false);
3064 }
3065
3066 private void dispatchKey(KeyEvent event, boolean sendDone) {
3067 //noinspection ConstantConditions
3068 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3069 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003070 if (DBG) Log.d("keydisp", "===================================================");
3071 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 debug();
3074
Romain Guy812ccbe2010-06-01 14:07:24 -07003075 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
3077 }
3078
3079 Message msg = obtainMessage(DISPATCH_KEY);
3080 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003081 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082
3083 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003084 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085
3086 sendMessageAtTime(msg, event.getEventTime());
3087 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003088
3089 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003090 dispatchMotion(event, false);
3091 }
3092
3093 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003094 int source = event.getSource();
3095 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003096 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003097 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003098 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003099 } else {
3100 // TODO
3101 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003102 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003103 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003104 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003105 }
3106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003108 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003109 dispatchPointer(event, false);
3110 }
3111
3112 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 Message msg = obtainMessage(DISPATCH_POINTER);
3114 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003115 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003116 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 }
3118
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003119 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003120 dispatchTrackball(event, false);
3121 }
3122
3123 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3125 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003126 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003127 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 public void dispatchAppVisibility(boolean visible) {
3131 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3132 msg.arg1 = visible ? 1 : 0;
3133 sendMessage(msg);
3134 }
3135
3136 public void dispatchGetNewSurface() {
3137 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3138 sendMessage(msg);
3139 }
3140
3141 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3142 Message msg = Message.obtain();
3143 msg.what = WINDOW_FOCUS_CHANGED;
3144 msg.arg1 = hasFocus ? 1 : 0;
3145 msg.arg2 = inTouchMode ? 1 : 0;
3146 sendMessage(msg);
3147 }
3148
Dianne Hackbornffa42482009-09-23 22:20:11 -07003149 public void dispatchCloseSystemDialogs(String reason) {
3150 Message msg = Message.obtain();
3151 msg.what = CLOSE_SYSTEM_DIALOGS;
3152 msg.obj = reason;
3153 sendMessage(msg);
3154 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003155
3156 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003157 final int what;
3158 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3159 what = DISPATCH_DRAG_LOCATION_EVENT;
3160 removeMessages(what);
3161 } else {
3162 what = DISPATCH_DRAG_EVENT;
3163 }
3164 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003165 sendMessage(msg);
3166 }
3167
Joe Onorato664644d2011-01-23 17:53:23 -08003168 public void dispatchSystemUiVisibilityChanged(int visibility) {
3169 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3170 }
3171
svetoslavganov75986cf2009-05-14 22:28:01 -07003172 /**
3173 * The window is getting focus so if there is anything focused/selected
3174 * send an {@link AccessibilityEvent} to announce that.
3175 */
3176 private void sendAccessibilityEvents() {
3177 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3178 return;
3179 }
3180 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3181 View focusedView = mView.findFocus();
3182 if (focusedView != null && focusedView != mView) {
3183 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3184 }
3185 }
3186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 public boolean showContextMenuForChild(View originalView) {
3188 return false;
3189 }
3190
Adam Powell6e346362010-07-23 10:18:23 -07003191 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3192 return null;
3193 }
3194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 public void createContextMenu(ContextMenu menu) {
3196 }
3197
3198 public void childDrawableStateChanged(View child) {
3199 }
3200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 void checkThread() {
3202 if (mThread != Thread.currentThread()) {
3203 throw new CalledFromWrongThreadException(
3204 "Only the original thread that created a view hierarchy can touch its views.");
3205 }
3206 }
3207
3208 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3209 // ViewRoot never intercepts touch event, so this can be a no-op
3210 }
3211
3212 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3213 boolean immediate) {
3214 return scrollToRectOrFocus(rectangle, immediate);
3215 }
Romain Guy8506ab42009-06-11 17:35:47 -07003216
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003217 class TakenSurfaceHolder extends BaseSurfaceHolder {
3218 @Override
3219 public boolean onAllowLockCanvas() {
3220 return mDrawingAllowed;
3221 }
3222
3223 @Override
3224 public void onRelayoutContainer() {
3225 // Not currently interesting -- from changing between fixed and layout size.
3226 }
3227
3228 public void setFormat(int format) {
3229 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3230 }
3231
3232 public void setType(int type) {
3233 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3234 }
3235
3236 @Override
3237 public void onUpdateSurface() {
3238 // We take care of format and type changes on our own.
3239 throw new IllegalStateException("Shouldn't be here");
3240 }
3241
3242 public boolean isCreating() {
3243 return mIsCreating;
3244 }
3245
3246 @Override
3247 public void setFixedSize(int width, int height) {
3248 throw new UnsupportedOperationException(
3249 "Currently only support sizing from layout");
3250 }
3251
3252 public void setKeepScreenOn(boolean screenOn) {
3253 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3254 }
3255 }
3256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 static class InputMethodCallback extends IInputMethodCallback.Stub {
3258 private WeakReference<ViewRoot> mViewRoot;
3259
3260 public InputMethodCallback(ViewRoot viewRoot) {
3261 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3262 }
Romain Guy8506ab42009-06-11 17:35:47 -07003263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 public void finishedEvent(int seq, boolean handled) {
3265 final ViewRoot viewRoot = mViewRoot.get();
3266 if (viewRoot != null) {
3267 viewRoot.dispatchFinishedEvent(seq, handled);
3268 }
3269 }
3270
3271 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3272 // Stub -- not for use in the client.
3273 }
3274 }
Romain Guy8506ab42009-06-11 17:35:47 -07003275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003277 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278
Romain Guyfb8b7632010-08-23 21:05:08 -07003279 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3281 }
3282
Romain Guyfb8b7632010-08-23 21:05:08 -07003283 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3284 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 final ViewRoot viewRoot = mViewRoot.get();
3286 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003287 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 }
3289 }
3290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 public void dispatchAppVisibility(boolean visible) {
3292 final ViewRoot viewRoot = mViewRoot.get();
3293 if (viewRoot != null) {
3294 viewRoot.dispatchAppVisibility(visible);
3295 }
3296 }
3297
3298 public void dispatchGetNewSurface() {
3299 final ViewRoot viewRoot = mViewRoot.get();
3300 if (viewRoot != null) {
3301 viewRoot.dispatchGetNewSurface();
3302 }
3303 }
3304
3305 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3306 final ViewRoot viewRoot = mViewRoot.get();
3307 if (viewRoot != null) {
3308 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3309 }
3310 }
3311
3312 private static int checkCallingPermission(String permission) {
3313 if (!Process.supportsProcesses()) {
3314 return PackageManager.PERMISSION_GRANTED;
3315 }
3316
3317 try {
3318 return ActivityManagerNative.getDefault().checkPermission(
3319 permission, Binder.getCallingPid(), Binder.getCallingUid());
3320 } catch (RemoteException e) {
3321 return PackageManager.PERMISSION_DENIED;
3322 }
3323 }
3324
3325 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3326 final ViewRoot viewRoot = mViewRoot.get();
3327 if (viewRoot != null) {
3328 final View view = viewRoot.mView;
3329 if (view != null) {
3330 if (checkCallingPermission(Manifest.permission.DUMP) !=
3331 PackageManager.PERMISSION_GRANTED) {
3332 throw new SecurityException("Insufficient permissions to invoke"
3333 + " executeCommand() from pid=" + Binder.getCallingPid()
3334 + ", uid=" + Binder.getCallingUid());
3335 }
3336
3337 OutputStream clientStream = null;
3338 try {
3339 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3340 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3341 } catch (IOException e) {
3342 e.printStackTrace();
3343 } finally {
3344 if (clientStream != null) {
3345 try {
3346 clientStream.close();
3347 } catch (IOException e) {
3348 e.printStackTrace();
3349 }
3350 }
3351 }
3352 }
3353 }
3354 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003355
Dianne Hackbornffa42482009-09-23 22:20:11 -07003356 public void closeSystemDialogs(String reason) {
3357 final ViewRoot viewRoot = mViewRoot.get();
3358 if (viewRoot != null) {
3359 viewRoot.dispatchCloseSystemDialogs(reason);
3360 }
3361 }
3362
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003363 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3364 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003365 if (sync) {
3366 try {
3367 sWindowSession.wallpaperOffsetsComplete(asBinder());
3368 } catch (RemoteException e) {
3369 }
3370 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003371 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003372
3373 public void dispatchWallpaperCommand(String action, int x, int y,
3374 int z, Bundle extras, boolean sync) {
3375 if (sync) {
3376 try {
3377 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3378 } catch (RemoteException e) {
3379 }
3380 }
3381 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003382
3383 /* Drag/drop */
3384 public void dispatchDragEvent(DragEvent event) {
3385 final ViewRoot viewRoot = mViewRoot.get();
3386 if (viewRoot != null) {
3387 viewRoot.dispatchDragEvent(event);
3388 }
3389 }
Joe Onorato664644d2011-01-23 17:53:23 -08003390
3391 @Override
3392 public void dispatchSystemUiVisibilityChanged(int visibility) {
3393 final ViewRoot viewRoot = mViewRoot.get();
3394 if (viewRoot != null) {
3395 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3396 }
3397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
3399
3400 /**
3401 * Maintains state information for a single trackball axis, generating
3402 * discrete (DPAD) movements based on raw trackball motion.
3403 */
3404 static final class TrackballAxis {
3405 /**
3406 * The maximum amount of acceleration we will apply.
3407 */
3408 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 /**
3411 * The maximum amount of time (in milliseconds) between events in order
3412 * for us to consider the user to be doing fast trackball movements,
3413 * and thus apply an acceleration.
3414 */
3415 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 /**
3418 * Scaling factor to the time (in milliseconds) between events to how
3419 * much to multiple/divide the current acceleration. When movement
3420 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3421 * FAST_MOVE_TIME it divides it.
3422 */
3423 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 float position;
3426 float absPosition;
3427 float acceleration = 1;
3428 long lastMoveTime = 0;
3429 int step;
3430 int dir;
3431 int nonAccelMovement;
3432
3433 void reset(int _step) {
3434 position = 0;
3435 acceleration = 1;
3436 lastMoveTime = 0;
3437 step = _step;
3438 dir = 0;
3439 }
3440
3441 /**
3442 * Add trackball movement into the state. If the direction of movement
3443 * has been reversed, the state is reset before adding the
3444 * movement (so that you don't have to compensate for any previously
3445 * collected movement before see the result of the movement in the
3446 * new direction).
3447 *
3448 * @return Returns the absolute value of the amount of movement
3449 * collected so far.
3450 */
3451 float collect(float off, long time, String axis) {
3452 long normTime;
3453 if (off > 0) {
3454 normTime = (long)(off * FAST_MOVE_TIME);
3455 if (dir < 0) {
3456 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3457 position = 0;
3458 step = 0;
3459 acceleration = 1;
3460 lastMoveTime = 0;
3461 }
3462 dir = 1;
3463 } else if (off < 0) {
3464 normTime = (long)((-off) * FAST_MOVE_TIME);
3465 if (dir > 0) {
3466 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3467 position = 0;
3468 step = 0;
3469 acceleration = 1;
3470 lastMoveTime = 0;
3471 }
3472 dir = -1;
3473 } else {
3474 normTime = 0;
3475 }
Romain Guy8506ab42009-06-11 17:35:47 -07003476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 // The number of milliseconds between each movement that is
3478 // considered "normal" and will not result in any acceleration
3479 // or deceleration, scaled by the offset we have here.
3480 if (normTime > 0) {
3481 long delta = time - lastMoveTime;
3482 lastMoveTime = time;
3483 float acc = acceleration;
3484 if (delta < normTime) {
3485 // The user is scrolling rapidly, so increase acceleration.
3486 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3487 if (scale > 1) acc *= scale;
3488 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3489 + off + " normTime=" + normTime + " delta=" + delta
3490 + " scale=" + scale + " acc=" + acc);
3491 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3492 } else {
3493 // The user is scrolling slowly, so decrease acceleration.
3494 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3495 if (scale > 1) acc /= scale;
3496 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3497 + off + " normTime=" + normTime + " delta=" + delta
3498 + " scale=" + scale + " acc=" + acc);
3499 acceleration = acc > 1 ? acc : 1;
3500 }
3501 }
3502 position += off;
3503 return (absPosition = Math.abs(position));
3504 }
3505
3506 /**
3507 * Generate the number of discrete movement events appropriate for
3508 * the currently collected trackball movement.
3509 *
3510 * @param precision The minimum movement required to generate the
3511 * first discrete movement.
3512 *
3513 * @return Returns the number of discrete movements, either positive
3514 * or negative, or 0 if there is not enough trackball movement yet
3515 * for a discrete movement.
3516 */
3517 int generate(float precision) {
3518 int movement = 0;
3519 nonAccelMovement = 0;
3520 do {
3521 final int dir = position >= 0 ? 1 : -1;
3522 switch (step) {
3523 // If we are going to execute the first step, then we want
3524 // to do this as soon as possible instead of waiting for
3525 // a full movement, in order to make things look responsive.
3526 case 0:
3527 if (absPosition < precision) {
3528 return movement;
3529 }
3530 movement += dir;
3531 nonAccelMovement += dir;
3532 step = 1;
3533 break;
3534 // If we have generated the first movement, then we need
3535 // to wait for the second complete trackball motion before
3536 // generating the second discrete movement.
3537 case 1:
3538 if (absPosition < 2) {
3539 return movement;
3540 }
3541 movement += dir;
3542 nonAccelMovement += dir;
3543 position += dir > 0 ? -2 : 2;
3544 absPosition = Math.abs(position);
3545 step = 2;
3546 break;
3547 // After the first two, we generate discrete movements
3548 // consistently with the trackball, applying an acceleration
3549 // if the trackball is moving quickly. This is a simple
3550 // acceleration on top of what we already compute based
3551 // on how quickly the wheel is being turned, to apply
3552 // a longer increasing acceleration to continuous movement
3553 // in one direction.
3554 default:
3555 if (absPosition < 1) {
3556 return movement;
3557 }
3558 movement += dir;
3559 position += dir >= 0 ? -1 : 1;
3560 absPosition = Math.abs(position);
3561 float acc = acceleration;
3562 acc *= 1.1f;
3563 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3564 break;
3565 }
3566 } while (true);
3567 }
3568 }
3569
3570 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3571 public CalledFromWrongThreadException(String msg) {
3572 super(msg);
3573 }
3574 }
3575
3576 private SurfaceHolder mHolder = new SurfaceHolder() {
3577 // we only need a SurfaceHolder for opengl. it would be nice
3578 // to implement everything else though, especially the callback
3579 // support (opengl doesn't make use of it right now, but eventually
3580 // will).
3581 public Surface getSurface() {
3582 return mSurface;
3583 }
3584
3585 public boolean isCreating() {
3586 return false;
3587 }
3588
3589 public void addCallback(Callback callback) {
3590 }
3591
3592 public void removeCallback(Callback callback) {
3593 }
3594
3595 public void setFixedSize(int width, int height) {
3596 }
3597
3598 public void setSizeFromLayout() {
3599 }
3600
3601 public void setFormat(int format) {
3602 }
3603
3604 public void setType(int type) {
3605 }
3606
3607 public void setKeepScreenOn(boolean screenOn) {
3608 }
3609
3610 public Canvas lockCanvas() {
3611 return null;
3612 }
3613
3614 public Canvas lockCanvas(Rect dirty) {
3615 return null;
3616 }
3617
3618 public void unlockCanvasAndPost(Canvas canvas) {
3619 }
3620 public Rect getSurfaceFrame() {
3621 return null;
3622 }
3623 };
3624
3625 static RunQueue getRunQueue() {
3626 RunQueue rq = sRunQueues.get();
3627 if (rq != null) {
3628 return rq;
3629 }
3630 rq = new RunQueue();
3631 sRunQueues.set(rq);
3632 return rq;
3633 }
Romain Guy8506ab42009-06-11 17:35:47 -07003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 /**
3636 * @hide
3637 */
3638 static final class RunQueue {
3639 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3640
3641 void post(Runnable action) {
3642 postDelayed(action, 0);
3643 }
3644
3645 void postDelayed(Runnable action, long delayMillis) {
3646 HandlerAction handlerAction = new HandlerAction();
3647 handlerAction.action = action;
3648 handlerAction.delay = delayMillis;
3649
3650 synchronized (mActions) {
3651 mActions.add(handlerAction);
3652 }
3653 }
3654
3655 void removeCallbacks(Runnable action) {
3656 final HandlerAction handlerAction = new HandlerAction();
3657 handlerAction.action = action;
3658
3659 synchronized (mActions) {
3660 final ArrayList<HandlerAction> actions = mActions;
3661
3662 while (actions.remove(handlerAction)) {
3663 // Keep going
3664 }
3665 }
3666 }
3667
3668 void executeActions(Handler handler) {
3669 synchronized (mActions) {
3670 final ArrayList<HandlerAction> actions = mActions;
3671 final int count = actions.size();
3672
3673 for (int i = 0; i < count; i++) {
3674 final HandlerAction handlerAction = actions.get(i);
3675 handler.postDelayed(handlerAction.action, handlerAction.delay);
3676 }
3677
Romain Guy15df6702009-08-17 20:17:30 -07003678 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
3680 }
3681
3682 private static class HandlerAction {
3683 Runnable action;
3684 long delay;
3685
3686 @Override
3687 public boolean equals(Object o) {
3688 if (this == o) return true;
3689 if (o == null || getClass() != o.getClass()) return false;
3690
3691 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 return !(action != null ? !action.equals(that.action) : that.action != null);
3693
3694 }
3695
3696 @Override
3697 public int hashCode() {
3698 int result = action != null ? action.hashCode() : 0;
3699 result = 31 * result + (int) (delay ^ (delay >>> 32));
3700 return result;
3701 }
3702 }
3703 }
3704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706}