blob: 1f1562888474882535e03b278806f85504a6d678 [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;
163 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700164 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700165
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700166 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
168 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700169 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700170 InputQueue.Callback mInputQueueCallback;
171 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700172 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 final Rect mTempRect; // used in the transaction to not thrash the heap.
175 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
177 boolean mTraversalScheduled;
178 boolean mWillDrawSoon;
179 boolean mLayoutRequested;
180 boolean mFirst;
181 boolean mReportNextDraw;
182 boolean mFullRedrawNeeded;
183 boolean mNewSurfaceNeeded;
184 boolean mHasHadWindowFocus;
185 boolean mLastWasImTarget;
186
187 boolean mWindowAttributesChanged = false;
188
189 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700190 // Surface can never be reassigned or cleared (use Surface.clear()).
191 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
193 boolean mAdded;
194 boolean mAddedTouchMode;
195
196 /*package*/ int mAddNesting;
197
198 // These are accessed by multiple threads.
199 final Rect mWinFrame; // frame given by window manager.
200
201 final Rect mPendingVisibleInsets = new Rect();
202 final Rect mPendingContentInsets = new Rect();
203 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
204 = new ViewTreeObserver.InternalInsetsInfo();
205
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700206 final Configuration mLastConfiguration = new Configuration();
207 final Configuration mPendingConfiguration = new Configuration();
208
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800209 class ResizedInfo {
210 Rect coveredInsets;
211 Rect visibleInsets;
212 Configuration newConfig;
213 }
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 boolean mScrollMayChange;
216 int mSoftInputMode;
217 View mLastScrolledFocus;
218 int mScrollY;
219 int mCurScrollY;
220 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800221 Bitmap mResizeBitmap;
222 long mResizeBitmapStartTime;
223 int mResizeBitmapDuration;
224 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700225
Romain Guy8506ab42009-06-11 17:35:47 -0700226 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
Christopher Tatea53146c2010-09-07 11:57:52 -0700228 /* Drag/drop */
229 ClipDescription mDragDescription;
230 View mCurrentDragView;
Christopher Tate407b4e92010-11-30 17:14:08 -0800231 Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700232 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700233 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 /**
236 * see {@link #playSoundEffect(int)}
237 */
238 AudioManager mAudioManager;
239
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700240 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700241
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700242 public static IWindowSession getWindowSession(Looper mainLooper) {
243 synchronized (mStaticInit) {
244 if (!mInitialized) {
245 try {
246 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
247 sWindowSession = IWindowManager.Stub.asInterface(
248 ServiceManager.getService("window"))
249 .openSession(imm.getClient(), imm.getInputContext());
250 mInitialized = true;
251 } catch (RemoteException e) {
252 }
253 }
254 return sWindowSession;
255 }
256 }
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 public ViewRoot(Context context) {
259 super();
260
Romain Guy812ccbe2010-06-01 14:07:24 -0700261 if (MEASURE_LATENCY) {
262 if (lt == null) {
263 lt = new LatencyTimer(100, 1000);
264 }
Michael Chan53071d62009-05-13 17:29:48 -0700265 }
266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 // Initialize the statics when this class is first instantiated. This is
268 // done here instead of in the static block because Zygote does not
269 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700270 getWindowSession(context.getMainLooper());
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 mThread = Thread.currentThread();
273 mLocation = new WindowLeaked(null);
274 mLocation.fillInStackTrace();
275 mWidth = -1;
276 mHeight = -1;
277 mDirty = new Rect();
278 mTempRect = new Rect();
279 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700281 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 mInputMethodCallback = new InputMethodCallback(this);
283 mViewVisibility = View.GONE;
284 mTransparentRegion = new Region();
285 mPreviousTransparentRegion = new Region();
286 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 mAdded = false;
288 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
289 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700290 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700291 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800294 public static void addFirstDrawHandler(Runnable callback) {
295 synchronized (sFirstDrawHandlers) {
296 if (!sFirstDrawComplete) {
297 sFirstDrawHandlers.add(callback);
298 }
299 }
300 }
301
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800302 public static void addConfigCallback(ComponentCallbacks callback) {
303 synchronized (sConfigCallbacks) {
304 sConfigCallbacks.add(callback);
305 }
306 }
307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 // FIXME for perf testing only
309 private boolean mProfile = false;
310
311 /**
312 * Call this to profile the next traversal call.
313 * FIXME for perf testing only. Remove eventually
314 */
315 public void profile() {
316 mProfile = true;
317 }
318
319 /**
320 * Indicates whether we are in touch mode. Calling this method triggers an IPC
321 * call and should be avoided whenever possible.
322 *
323 * @return True, if the device is in touch mode, false otherwise.
324 *
325 * @hide
326 */
327 static boolean isInTouchMode() {
328 if (mInitialized) {
329 try {
330 return sWindowSession.getInTouchMode();
331 } catch (RemoteException e) {
332 }
333 }
334 return false;
335 }
336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 /**
338 * We have one child
339 */
Romain Guye4d01122010-06-16 18:44:05 -0700340 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 synchronized (this) {
342 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700343 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700344 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700345 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700346 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700347
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700348 if (view instanceof RootViewSurfaceTaker) {
349 mSurfaceHolderCallback =
350 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
351 if (mSurfaceHolderCallback != null) {
352 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700353 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700354 }
355 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800356
357 // If the application owns the surface, don't enable hardware acceleration
358 if (mSurfaceHolder == null) {
359 enableHardwareAcceleration(attrs);
360 }
361
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700362 Resources resources = mView.getContext().getResources();
363 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700364 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700365
366 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700367 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
368 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700369 }
370
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700371 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700372 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700373 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700374 attrs.backup();
375 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700376 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700377 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
378
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700379 if (!compatibilityInfo.supportsScreen()) {
380 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
381 }
382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 mSoftInputMode = attrs.softInputMode;
384 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700386 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700387 mAttachInfo.mApplicationScale =
388 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 if (panelParentView != null) {
390 mAttachInfo.mPanelParentWindowToken
391 = panelParentView.getApplicationWindowToken();
392 }
393 mAdded = true;
394 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 // Schedule the first layout -before- adding to the window
397 // manager, to make sure we do the relayout before receiving
398 // any other events from the system.
399 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700400 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700402 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700403 getHostVisibility(), mAttachInfo.mContentInsets,
404 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 } catch (RemoteException e) {
406 mAdded = false;
407 mView = null;
408 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700409 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700410 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 unscheduleTraversals();
412 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700413 } finally {
414 if (restore) {
415 attrs.restore();
416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700418
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700419 if (mTranslator != null) {
420 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 mPendingContentInsets.set(mAttachInfo.mContentInsets);
423 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800424 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 if (res < WindowManagerImpl.ADD_OKAY) {
426 mView = null;
427 mAttachInfo.mRootView = null;
428 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700429 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 unscheduleTraversals();
431 switch (res) {
432 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
433 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
434 throw new WindowManagerImpl.BadTokenException(
435 "Unable to add window -- token " + attrs.token
436 + " is not valid; is your activity running?");
437 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
438 throw new WindowManagerImpl.BadTokenException(
439 "Unable to add window -- token " + attrs.token
440 + " is not for an application");
441 case WindowManagerImpl.ADD_APP_EXITING:
442 throw new WindowManagerImpl.BadTokenException(
443 "Unable to add window -- app for token " + attrs.token
444 + " is exiting");
445 case WindowManagerImpl.ADD_DUPLICATE_ADD:
446 throw new WindowManagerImpl.BadTokenException(
447 "Unable to add window -- window " + mWindow
448 + " has already been added");
449 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
450 // Silently ignore -- we would have just removed it
451 // right away, anyway.
452 return;
453 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
454 throw new WindowManagerImpl.BadTokenException(
455 "Unable to add window " + mWindow +
456 " -- another window of this type already exists");
457 case WindowManagerImpl.ADD_PERMISSION_DENIED:
458 throw new WindowManagerImpl.BadTokenException(
459 "Unable to add window " + mWindow +
460 " -- permission denied for this window type");
461 }
462 throw new RuntimeException(
463 "Unable to add window -- unknown error code " + res);
464 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700465
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700466 if (view instanceof RootViewSurfaceTaker) {
467 mInputQueueCallback =
468 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
469 }
470 if (mInputQueueCallback != null) {
471 mInputQueue = new InputQueue(mInputChannel);
472 mInputQueueCallback.onInputQueueCreated(mInputQueue);
473 } else {
474 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
475 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700476 }
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 view.assignParent(this);
479 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
480 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
481 }
482 }
483 }
484
Romain Guy529b60a2010-08-03 18:05:47 -0700485 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800486 mAttachInfo.mHardwareAccelerated = false;
487 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800488
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800489 // Try to enable hardware acceleration if requested
490 if (attrs != null &&
491 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
Romain Guy501053a2011-01-13 18:38:45 -0800492 // Don't enable hardware acceleration when we're not on the main thread
493 if (Looper.getMainLooper() != Looper.myLooper()) {
494 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware acceleration "
495 + "outside of the main thread, aborting");
496 return;
497 }
498
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800499 // Only enable hardware acceleration if we are not in the system process
500 // The window manager creates ViewRoots to display animated preview windows
501 // of launching apps and we don't want those to be hardware accelerated
502 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700503 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700504 if (mAttachInfo.mHardwareRenderer != null) {
505 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700506 }
Romain Guyb051e892010-09-28 19:09:36 -0700507 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800508 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
509 = mAttachInfo.mHardwareRenderer != null;
510 } else if (HardwareRenderer.isAvailable()) {
511 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700512 }
513 }
514 }
515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 public View getView() {
517 return mView;
518 }
519
520 final WindowLeaked getLocation() {
521 return mLocation;
522 }
523
524 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
525 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700526 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700527 // preserve compatible window flag if exists.
528 int compatibleWindowFlag =
529 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700531 mWindowAttributes.flags |= compatibleWindowFlag;
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 if (newView) {
534 mSoftInputMode = attrs.softInputMode;
535 requestLayout();
536 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700537 // Don't lose the mode we last auto-computed.
538 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
539 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
540 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
541 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
542 | (oldSoftInputMode
543 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 mWindowAttributesChanged = true;
546 scheduleTraversals();
547 }
548 }
549
550 void handleAppVisibility(boolean visible) {
551 if (mAppVisible != visible) {
552 mAppVisible = visible;
553 scheduleTraversals();
554 }
555 }
556
557 void handleGetNewSurface() {
558 mNewSurfaceNeeded = true;
559 mFullRedrawNeeded = true;
560 scheduleTraversals();
561 }
562
563 /**
564 * {@inheritDoc}
565 */
566 public void requestLayout() {
567 checkThread();
568 mLayoutRequested = true;
569 scheduleTraversals();
570 }
571
572 /**
573 * {@inheritDoc}
574 */
575 public boolean isLayoutRequested() {
576 return mLayoutRequested;
577 }
578
579 public void invalidateChild(View child, Rect dirty) {
580 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700581 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700582 if (dirty == null) {
583 // Fast invalidation for GL-enabled applications; GL must redraw everything
584 invalidate();
585 return;
586 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700587 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700589 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700590 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700591 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700592 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700593 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700594 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700595 }
Romain Guy1e095972009-07-07 11:22:45 -0700596 if (mAttachInfo.mScalingRequired) {
597 dirty.inset(-1, -1);
598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 }
Romain Guy7d695942010-12-01 17:22:29 -0800600 if (!mDirty.isEmpty()) {
601 mAttachInfo.mIgnoreDirtyState = true;
602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 mDirty.union(dirty);
604 if (!mWillDrawSoon) {
605 scheduleTraversals();
606 }
607 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700608
609 void invalidate() {
610 mDirty.set(0, 0, mWidth, mHeight);
611 scheduleTraversals();
612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613
614 public ViewParent getParent() {
615 return null;
616 }
617
618 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
619 invalidateChild(null, dirty);
620 return null;
621 }
622
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700623 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 if (child != mView) {
625 throw new RuntimeException("child is not mine, honest!");
626 }
627 // Note: don't apply scroll offset, because we want to know its
628 // visibility in the virtual canvas being given to the view hierarchy.
629 return r.intersect(0, 0, mWidth, mHeight);
630 }
631
632 public void bringChildToFront(View child) {
633 }
634
635 public void scheduleTraversals() {
636 if (!mTraversalScheduled) {
637 mTraversalScheduled = true;
638 sendEmptyMessage(DO_TRAVERSAL);
639 }
640 }
641
642 public void unscheduleTraversals() {
643 if (mTraversalScheduled) {
644 mTraversalScheduled = false;
645 removeMessages(DO_TRAVERSAL);
646 }
647 }
648
649 int getHostVisibility() {
650 return mAppVisible ? mView.getVisibility() : View.GONE;
651 }
Romain Guy8506ab42009-06-11 17:35:47 -0700652
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800653 void disposeResizeBitmap() {
654 if (mResizeBitmap != null) {
655 mResizeBitmap.recycle();
656 mResizeBitmap = null;
657 }
658 }
659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 private void performTraversals() {
661 // cache mView since it is used so much below...
662 final View host = mView;
663
664 if (DBG) {
665 System.out.println("======================================");
666 System.out.println("performTraversals");
667 host.debug();
668 }
669
670 if (host == null || !mAdded)
671 return;
672
673 mTraversalScheduled = false;
674 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800675 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 boolean fullRedrawNeeded = mFullRedrawNeeded;
677 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700678 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 WindowManager.LayoutParams lp = mWindowAttributes;
680
681 int desiredWindowWidth;
682 int desiredWindowHeight;
683 int childWidthMeasureSpec;
684 int childHeightMeasureSpec;
685
686 final View.AttachInfo attachInfo = mAttachInfo;
687
688 final int viewVisibility = getHostVisibility();
689 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
690 || mNewSurfaceNeeded;
691
692 WindowManager.LayoutParams params = null;
693 if (mWindowAttributesChanged) {
694 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700695 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 params = lp;
697 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700698 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 if (mFirst) {
700 fullRedrawNeeded = true;
701 mLayoutRequested = true;
702
Romain Guy8506ab42009-06-11 17:35:47 -0700703 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700704 mView.getContext().getResources().getDisplayMetrics();
705 desiredWindowWidth = packageMetrics.widthPixels;
706 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707
708 // For the very first time, tell the view hierarchy that it
709 // is attached to the window. Note that at this point the surface
710 // object is not initialized to its backing store, but soon it
711 // will be (assuming the window is visible).
712 attachInfo.mSurface = mSurface;
Adam Powell26153a32010-11-08 15:22:27 -0800713 attachInfo.mUse32BitDrawingCache = PixelFormat.formatHasAlpha(lp.format) ||
714 lp.format == PixelFormat.RGBX_8888;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 attachInfo.mHasWindowFocus = false;
716 attachInfo.mWindowVisibility = viewVisibility;
717 attachInfo.mRecomputeGlobalAttributes = false;
718 attachInfo.mKeepScreenOn = false;
719 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700720 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700725 desiredWindowWidth = frame.width();
726 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700728 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700729 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 fullRedrawNeeded = true;
731 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800732 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734 }
735
736 if (viewVisibilityChanged) {
737 attachInfo.mWindowVisibility = viewVisibility;
738 host.dispatchWindowVisibilityChanged(viewVisibility);
739 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700740 if (mAttachInfo.mHardwareRenderer != null) {
741 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
744 if (viewVisibility == View.GONE) {
745 // After making a window gone, we will count it as being
746 // shown for the first time the next time it gets focus.
747 mHasHadWindowFocus = false;
748 }
749 }
750
751 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700754 // Execute enqueued actions on every layout in case a view that was detached
755 // enqueued an action after being detached
756 getRunQueue().executeActions(attachInfo.mHandler);
757
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800758 final Resources res = mView.getContext().getResources();
759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 if (mFirst) {
761 host.fitSystemWindows(mAttachInfo.mContentInsets);
762 // make sure touch mode code executes by setting cached value
763 // to opposite of the added touch mode.
764 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700765 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 } else {
767 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800768 if (mWidth > 0 && mHeight > 0 &&
769 mSurface != null && mSurface.isValid() &&
770 mAttachInfo.mHardwareRenderer != null &&
771 mAttachInfo.mHardwareRenderer.isEnabled() &&
772 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
773
774 disposeResizeBitmap();
775
776 boolean completed = false;
777 try {
778 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
779 Bitmap.Config.ARGB_8888);
780 mResizeBitmap.setHasAlpha(false);
781 Canvas canvas = new Canvas(mResizeBitmap);
782 int yoff;
783 final boolean scrolling = mScroller != null
784 && mScroller.computeScrollOffset();
785 if (scrolling) {
786 yoff = mScroller.getCurrY();
787 mScroller.abortAnimation();
788 } else {
789 yoff = mScrollY;
790 }
791 canvas.translate(0, -yoff);
792 if (mTranslator != null) {
793 mTranslator.translateCanvas(canvas);
794 }
795 canvas.setScreenDensity(mAttachInfo.mScalingRequired
796 ? DisplayMetrics.DENSITY_DEVICE : 0);
797 mView.draw(canvas);
798 mResizeBitmapStartTime = SystemClock.uptimeMillis();
799 mResizeBitmapDuration = mView.getResources().getInteger(
800 com.android.internal.R.integer.config_mediumAnimTime);
801 completed = true;
802 } catch (OutOfMemoryError e) {
803 Log.w(TAG, "Not enough memory for content change anim buffer", e);
804 } finally {
805 if (!completed) {
806 mResizeBitmap = null;
807 }
808 }
809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 mAttachInfo.mContentInsets.set(mPendingContentInsets);
811 host.fitSystemWindows(mAttachInfo.mContentInsets);
812 insetsChanged = true;
813 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
814 + mAttachInfo.mContentInsets);
815 }
816 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
817 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
818 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
819 + mAttachInfo.mVisibleInsets);
820 }
821 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
822 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800823 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800825 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700826 desiredWindowWidth = packageMetrics.widthPixels;
827 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829 }
830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700832 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 "Measuring " + host + " in display " + desiredWindowWidth
834 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800835
836 boolean goodMeasure = false;
837 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
838 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
839 // On large screens, we don't want to allow dialogs to just
840 // stretch to fill the entire width of the screen to display
841 // one line of text. First try doing the layout at a smaller
842 // size to see if it will fit.
843 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
844 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
845 int baseSize = 0;
846 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
847 baseSize = (int)mTmpValue.getDimension(packageMetrics);
848 }
849 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800850 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800851 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
852 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
853 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
854 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800855 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
856 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800857 goodMeasure = true;
858 } else {
859 // Didn't fit in that size... try expanding a bit.
860 baseSize = (baseSize+desiredWindowWidth)/2;
861 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
862 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800863 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800864 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
865 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800866 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
867 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800868 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
869 goodMeasure = true;
870 }
871 }
872 }
873 }
874
875 if (!goodMeasure) {
876 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
877 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
878 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800879 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
880 windowSizeMayChange = true;
881 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883
884 if (DBG) {
885 System.out.println("======================================");
886 System.out.println("performTraversals -- after measure");
887 host.debug();
888 }
889 }
890
891 if (attachInfo.mRecomputeGlobalAttributes) {
892 //Log.i(TAG, "Computing screen on!");
893 attachInfo.mRecomputeGlobalAttributes = false;
894 boolean oldVal = attachInfo.mKeepScreenOn;
895 attachInfo.mKeepScreenOn = false;
896 host.dispatchCollectViewAttributes(0);
897 if (attachInfo.mKeepScreenOn != oldVal) {
898 params = lp;
899 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
900 }
901 }
902
903 if (mFirst || attachInfo.mViewVisibilityChanged) {
904 attachInfo.mViewVisibilityChanged = false;
905 int resizeMode = mSoftInputMode &
906 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
907 // If we are in auto resize mode, then we need to determine
908 // what mode to use now.
909 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
910 final int N = attachInfo.mScrollContainers.size();
911 for (int i=0; i<N; i++) {
912 if (attachInfo.mScrollContainers.get(i).isShown()) {
913 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
914 }
915 }
916 if (resizeMode == 0) {
917 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
918 }
919 if ((lp.softInputMode &
920 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
921 lp.softInputMode = (lp.softInputMode &
922 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
923 resizeMode;
924 params = lp;
925 }
926 }
927 }
Romain Guy8506ab42009-06-11 17:35:47 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
930 if (!PixelFormat.formatHasAlpha(params.format)) {
931 params.format = PixelFormat.TRANSLUCENT;
932 }
933 }
934
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800935 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800936 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700937 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
938 frame.width() < desiredWindowWidth && frame.width() != mWidth)
939 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
940 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941
942 final boolean computesInternalInsets =
943 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 boolean insetsPending = false;
946 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700947
948 if (mFirst || windowShouldResize || insetsChanged ||
949 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950
951 if (viewVisibility == View.VISIBLE) {
952 // If this window is giving internal insets to the window
953 // manager, and it is being added or changing its visibility,
954 // then we want to first give the window manager "fake"
955 // insets to cause it to effectively ignore the content of
956 // the window during layout. This avoids it briefly causing
957 // other windows to resize/move based on the raw frame of the
958 // window, waiting until we can finish laying out this window
959 // and get back to the window manager with the ultimately
960 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700961 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
963
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700964 if (mSurfaceHolder != null) {
965 mSurfaceHolder.mSurfaceLock.lock();
966 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700967 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700968
Romain Guyc361da82010-10-25 15:29:10 -0700969 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700971 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700972 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 int fl = 0;
976 if (params != null) {
977 fl = params.flags;
978 if (attachInfo.mKeepScreenOn) {
979 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
980 }
981 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700982 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800983 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
984 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700985 }
Romain Guy2a83f002011-01-18 18:28:21 -0800986
987 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700988 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 if (params != null) {
991 params.flags = fl;
992 }
993
994 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
995 + " content=" + mPendingContentInsets.toShortString()
996 + " visible=" + mPendingVisibleInsets.toShortString()
997 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700998
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700999 if (mPendingConfiguration.seq != 0) {
1000 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1001 + mPendingConfiguration);
1002 updateConfiguration(mPendingConfiguration, !mFirst);
1003 mPendingConfiguration.seq = 0;
1004 }
1005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 contentInsetsChanged = !mPendingContentInsets.equals(
1007 mAttachInfo.mContentInsets);
1008 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1009 mAttachInfo.mVisibleInsets);
1010 if (contentInsetsChanged) {
1011 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1012 host.fitSystemWindows(mAttachInfo.mContentInsets);
1013 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1014 + mAttachInfo.mContentInsets);
1015 }
1016 if (visibleInsetsChanged) {
1017 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1018 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1019 + mAttachInfo.mVisibleInsets);
1020 }
1021
1022 if (!hadSurface) {
1023 if (mSurface.isValid()) {
1024 // If we are creating a new surface, then we need to
1025 // completely redraw it. Also, when we get to the
1026 // point of drawing it we will hold off and schedule
1027 // a new traversal instead. This is so we can tell the
1028 // window manager about all of the windows being displayed
1029 // before actually drawing them, so it can display then
1030 // all at once.
1031 newSurface = true;
1032 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001033 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001034
Romain Guyb051e892010-09-28 19:09:36 -07001035 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001036 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 }
1039 } else if (!mSurface.isValid()) {
1040 // If the surface has been removed, then reset the scroll
1041 // positions.
1042 mLastScrolledFocus = null;
1043 mScrollY = mCurScrollY = 0;
1044 if (mScroller != null) {
1045 mScroller.abortAnimation();
1046 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001047 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001048 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1049 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1050 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052 } catch (RemoteException e) {
1053 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001056 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057
1058 attachInfo.mWindowLeft = frame.left;
1059 attachInfo.mWindowTop = frame.top;
1060
1061 // !!FIXME!! This next section handles the case where we did not get the
1062 // window size we asked for. We should avoid this by getting a maximum size from
1063 // the window session beforehand.
1064 mWidth = frame.width();
1065 mHeight = frame.height();
1066
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001067 if (mSurfaceHolder != null) {
1068 // The app owns the surface; tell it about what is going on.
1069 if (mSurface.isValid()) {
1070 // XXX .copyFrom() doesn't work!
1071 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1072 mSurfaceHolder.mSurface = mSurface;
1073 }
1074 mSurfaceHolder.mSurfaceLock.unlock();
1075 if (mSurface.isValid()) {
1076 if (!hadSurface) {
1077 mSurfaceHolder.ungetCallbacks();
1078
1079 mIsCreating = true;
1080 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1081 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1082 if (callbacks != null) {
1083 for (SurfaceHolder.Callback c : callbacks) {
1084 c.surfaceCreated(mSurfaceHolder);
1085 }
1086 }
1087 surfaceChanged = true;
1088 }
1089 if (surfaceChanged) {
1090 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1091 lp.format, mWidth, mHeight);
1092 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1093 if (callbacks != null) {
1094 for (SurfaceHolder.Callback c : callbacks) {
1095 c.surfaceChanged(mSurfaceHolder, lp.format,
1096 mWidth, mHeight);
1097 }
1098 }
1099 }
1100 mIsCreating = false;
1101 } else if (hadSurface) {
1102 mSurfaceHolder.ungetCallbacks();
1103 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1104 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1105 if (callbacks != null) {
1106 for (SurfaceHolder.Callback c : callbacks) {
1107 c.surfaceDestroyed(mSurfaceHolder);
1108 }
1109 }
1110 mSurfaceHolder.mSurfaceLock.lock();
1111 // Make surface invalid.
1112 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1113 mSurfaceHolder.mSurface = new Surface();
1114 mSurfaceHolder.mSurfaceLock.unlock();
1115 }
1116 }
Romain Guy53389bd2010-09-07 17:16:32 -07001117
Romain Guy6b5108b2011-01-04 16:11:10 -08001118 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001119 mAttachInfo.mHardwareRenderer != null &&
1120 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001121 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
1123
1124 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001125 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001126 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1127 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1129 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1130
1131 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001132 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 + " mHeight=" + mHeight
Dianne Hackborn189ee182010-12-02 21:48:53 -08001134 + " measuredHeight" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 // Ask host how big it wants to be
1138 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1139
1140 // Implementation of weights from WindowManager.LayoutParams
1141 // We just grow the dimensions as needed and re-measure if
1142 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001143 int width = host.getMeasuredWidth();
1144 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 boolean measureAgain = false;
1146
1147 if (lp.horizontalWeight > 0.0f) {
1148 width += (int) ((mWidth - width) * lp.horizontalWeight);
1149 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1150 MeasureSpec.EXACTLY);
1151 measureAgain = true;
1152 }
1153 if (lp.verticalWeight > 0.0f) {
1154 height += (int) ((mHeight - height) * lp.verticalWeight);
1155 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1156 MeasureSpec.EXACTLY);
1157 measureAgain = true;
1158 }
1159
1160 if (measureAgain) {
1161 if (DEBUG_LAYOUT) Log.v(TAG,
1162 "And hey let's measure once more: width=" + width
1163 + " height=" + height);
1164 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1165 }
1166
1167 mLayoutRequested = true;
1168 }
1169 }
1170
1171 final boolean didLayout = mLayoutRequested;
1172 boolean triggerGlobalLayoutListener = didLayout
1173 || attachInfo.mRecomputeGlobalAttributes;
1174 if (didLayout) {
1175 mLayoutRequested = false;
1176 mScrollMayChange = true;
1177 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001178 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001179 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001180 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001181 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 startTime = SystemClock.elapsedRealtime();
1183 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001184 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185
Romain Guy13922e02009-05-12 17:56:14 -07001186 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1187 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1188 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1189 + "please refer to the logs with the tag "
1190 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1191 }
1192 }
1193
Romain Guy5429e1d2010-09-07 12:38:00 -07001194 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1196 }
1197
1198 // By this point all views have been sized and positionned
1199 // We can compute the transparent area
1200
1201 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1202 // start out transparent
1203 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1204 host.getLocationInWindow(mTmpLocation);
1205 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1206 mTmpLocation[0] + host.mRight - host.mLeft,
1207 mTmpLocation[1] + host.mBottom - host.mTop);
1208
1209 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001210 if (mTranslator != null) {
1211 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1212 }
1213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1215 mPreviousTransparentRegion.set(mTransparentRegion);
1216 // reconfigure window manager
1217 try {
1218 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1219 } catch (RemoteException e) {
1220 }
1221 }
1222 }
1223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 if (DBG) {
1225 System.out.println("======================================");
1226 System.out.println("performTraversals -- after setFrame");
1227 host.debug();
1228 }
1229 }
1230
1231 if (triggerGlobalLayoutListener) {
1232 attachInfo.mRecomputeGlobalAttributes = false;
1233 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1234 }
1235
1236 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001237 // Clear the original insets.
1238 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1239 insets.reset();
1240
1241 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001243
1244 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1246 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001247
1248 // Translate insets to screen coordinates if needed.
1249 final Rect contentInsets;
1250 final Rect visibleInsets;
1251 final Region touchableRegion;
1252 if (mTranslator != null) {
1253 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1254 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1255 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1256 } else {
1257 contentInsets = insets.contentInsets;
1258 visibleInsets = insets.visibleInsets;
1259 touchableRegion = insets.touchableRegion;
1260 }
1261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 try {
1263 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001264 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 } catch (RemoteException e) {
1266 }
1267 }
1268 }
Romain Guy8506ab42009-06-11 17:35:47 -07001269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 if (mFirst) {
1271 // handle first focus request
1272 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1273 + mView.hasFocus());
1274 if (mView != null) {
1275 if (!mView.hasFocus()) {
1276 mView.requestFocus(View.FOCUS_FORWARD);
1277 mFocusedView = mRealFocusedView = mView.findFocus();
1278 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1279 + mFocusedView);
1280 } else {
1281 mRealFocusedView = mView.findFocus();
1282 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1283 + mRealFocusedView);
1284 }
1285 }
1286 }
1287
1288 mFirst = false;
1289 mWillDrawSoon = false;
1290 mNewSurfaceNeeded = false;
1291 mViewVisibility = viewVisibility;
1292
1293 if (mAttachInfo.mHasWindowFocus) {
1294 final boolean imTarget = WindowManager.LayoutParams
1295 .mayUseInputMethod(mWindowAttributes.flags);
1296 if (imTarget != mLastWasImTarget) {
1297 mLastWasImTarget = imTarget;
1298 InputMethodManager imm = InputMethodManager.peekInstance();
1299 if (imm != null && imTarget) {
1300 imm.startGettingWindowFocus(mView);
1301 imm.onWindowFocus(mView, mView.findFocus(),
1302 mWindowAttributes.softInputMode,
1303 !mHasHadWindowFocus, mWindowAttributes.flags);
1304 }
1305 }
1306 }
Romain Guy8506ab42009-06-11 17:35:47 -07001307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1309
1310 if (!cancelDraw && !newSurface) {
1311 mFullRedrawNeeded = false;
1312 draw(fullRedrawNeeded);
1313
1314 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1315 || mReportNextDraw) {
1316 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001317 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
1319 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001320 if (mSurfaceHolder != null && mSurface.isValid()) {
1321 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1322 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1323 if (callbacks != null) {
1324 for (SurfaceHolder.Callback c : callbacks) {
1325 if (c instanceof SurfaceHolder.Callback2) {
1326 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1327 mSurfaceHolder);
1328 }
1329 }
1330 }
1331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 try {
1333 sWindowSession.finishDrawing(mWindow);
1334 } catch (RemoteException e) {
1335 }
1336 }
1337 } else {
1338 // We were supposed to report when we are done drawing. Since we canceled the
1339 // draw, remember it here.
1340 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1341 mReportNextDraw = true;
1342 }
1343 if (fullRedrawNeeded) {
1344 mFullRedrawNeeded = true;
1345 }
1346 // Try again
1347 scheduleTraversals();
1348 }
1349 }
1350
1351 public void requestTransparentRegion(View child) {
1352 // the test below should not fail unless someone is messing with us
1353 checkThread();
1354 if (mView == child) {
1355 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1356 // Need to make sure we re-evaluate the window attributes next
1357 // time around, to ensure the window has the correct format.
1358 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001359 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
1361 }
1362
1363 /**
1364 * Figures out the measure spec for the root view in a window based on it's
1365 * layout params.
1366 *
1367 * @param windowSize
1368 * The available width or height of the window
1369 *
1370 * @param rootDimension
1371 * The layout params for one dimension (width or height) of the
1372 * window.
1373 *
1374 * @return The measure spec to use to measure the root view.
1375 */
1376 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1377 int measureSpec;
1378 switch (rootDimension) {
1379
Romain Guy980a9382010-01-08 15:06:28 -08001380 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 // Window can't resize. Force root view to be windowSize.
1382 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1383 break;
1384 case ViewGroup.LayoutParams.WRAP_CONTENT:
1385 // Window can resize. Set max size for root view.
1386 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1387 break;
1388 default:
1389 // Window wants to be an exact size. Force root view to be that size.
1390 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1391 break;
1392 }
1393 return measureSpec;
1394 }
1395
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001396 int mHardwareYOffset;
1397 int mResizeAlpha;
1398 final Paint mResizePaint = new Paint();
1399
1400 public void onHardwarePreDraw(Canvas canvas) {
1401 canvas.translate(0, -mHardwareYOffset);
1402 }
1403
1404 public void onHardwarePostDraw(Canvas canvas) {
1405 if (mResizeBitmap != null) {
1406 canvas.translate(0, mHardwareYOffset);
1407 mResizePaint.setAlpha(mResizeAlpha);
1408 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1409 }
1410 }
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 private void draw(boolean fullRedrawNeeded) {
1413 Surface surface = mSurface;
1414 if (surface == null || !surface.isValid()) {
1415 return;
1416 }
1417
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001418 if (!sFirstDrawComplete) {
1419 synchronized (sFirstDrawHandlers) {
1420 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001421 final int count = sFirstDrawHandlers.size();
1422 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001423 post(sFirstDrawHandlers.get(i));
1424 }
1425 }
1426 }
1427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 scrollToRectOrFocus(null, false);
1429
1430 if (mAttachInfo.mViewScrollChanged) {
1431 mAttachInfo.mViewScrollChanged = false;
1432 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1433 }
Romain Guy8506ab42009-06-11 17:35:47 -07001434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001436 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1437 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 yoff = mScroller.getCurrY();
1439 } else {
1440 yoff = mScrollY;
1441 }
1442 if (mCurScrollY != yoff) {
1443 mCurScrollY = yoff;
1444 fullRedrawNeeded = true;
1445 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001446 float appScale = mAttachInfo.mApplicationScale;
1447 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001449 int resizeAlpha = 0;
1450 if (mResizeBitmap != null) {
1451 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1452 if (deltaTime < mResizeBitmapDuration) {
1453 float amt = deltaTime/(float)mResizeBitmapDuration;
1454 amt = mResizeInterpolator.getInterpolation(amt);
1455 animating = true;
1456 resizeAlpha = 255 - (int)(amt*255);
1457 } else {
1458 disposeResizeBitmap();
1459 }
1460 }
1461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001463 if (mSurfaceHolder != null) {
1464 // The app owns the surface, we won't draw.
1465 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001466 if (animating) {
1467 if (mScroller != null) {
1468 mScroller.abortAnimation();
1469 }
1470 disposeResizeBitmap();
1471 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001472 return;
1473 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001474
1475 if (fullRedrawNeeded) {
1476 mAttachInfo.mIgnoreDirtyState = true;
1477 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1478 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001479
Romain Guyb051e892010-09-28 19:09:36 -07001480 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001481 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001482 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001483 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001484 mHardwareYOffset = yoff;
1485 mResizeAlpha = resizeAlpha;
1486 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001488
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001489 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 mFullRedrawNeeded = true;
1491 scheduleTraversals();
1492 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 return;
1495 }
1496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001498 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 + mWindowAttributes.getTitle()
1500 + ": dirty={" + dirty.left + "," + dirty.top
1501 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001502 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1503 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001506 if (!dirty.isEmpty() || mIsAnimating) {
1507 Canvas canvas;
1508 try {
1509 int left = dirty.left;
1510 int top = dirty.top;
1511 int right = dirty.right;
1512 int bottom = dirty.bottom;
1513 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001514
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001515 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1516 bottom != dirty.bottom) {
1517 mAttachInfo.mIgnoreDirtyState = true;
1518 }
1519
1520 // TODO: Do this in native
1521 canvas.setDensity(mDensity);
1522 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001523 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001524 // TODO: we should ask the window manager to do something!
1525 // for now we just do nothing
1526 return;
1527 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001528 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001529 // TODO: we should ask the window manager to do something!
1530 // for now we just do nothing
1531 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001532 }
1533
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001534 try {
1535 if (!dirty.isEmpty() || mIsAnimating) {
1536 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001538 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001539 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001540 + canvas.getWidth() + ", h=" + canvas.getHeight());
1541 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543
Romain Guy5429e1d2010-09-07 12:38:00 -07001544 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001545 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001547
1548 // If this bitmap's format includes an alpha channel, we
1549 // need to clear it before drawing so that the child will
1550 // properly re-composite its drawing on a transparent
1551 // background. This automatically respects the clip/dirty region
1552 // or
1553 // If we are applying an offset, we need to clear the area
1554 // where the offset doesn't appear to avoid having garbage
1555 // left in the blank areas.
1556 if (!canvas.isOpaque() || yoff != 0) {
1557 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1558 }
1559
1560 dirty.setEmpty();
1561 mIsAnimating = false;
1562 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1563 mView.mPrivateFlags |= View.DRAWN;
1564
1565 if (DEBUG_DRAW) {
1566 Context cxt = mView.getContext();
1567 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1568 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1569 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1570 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001571 try {
1572 canvas.translate(0, -yoff);
1573 if (mTranslator != null) {
1574 mTranslator.translateCanvas(canvas);
1575 }
1576 canvas.setScreenDensity(scalingRequired
1577 ? DisplayMetrics.DENSITY_DEVICE : 0);
1578 mView.draw(canvas);
1579 } finally {
1580 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001581 }
1582
1583 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1584 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1585 }
1586
Romain Guy5429e1d2010-09-07 12:38:00 -07001587 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001588 int now = (int)SystemClock.elapsedRealtime();
1589 if (sDrawTime != 0) {
1590 nativeShowFPS(canvas, now - sDrawTime);
1591 }
1592 sDrawTime = now;
1593 }
1594
Romain Guy5429e1d2010-09-07 12:38:00 -07001595 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001596 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001600 } finally {
1601 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604
1605 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001606 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
Romain Guy8506ab42009-06-11 17:35:47 -07001608
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001609 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 mFullRedrawNeeded = true;
1611 scheduleTraversals();
1612 }
1613 }
1614
1615 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1616 final View.AttachInfo attachInfo = mAttachInfo;
1617 final Rect ci = attachInfo.mContentInsets;
1618 final Rect vi = attachInfo.mVisibleInsets;
1619 int scrollY = 0;
1620 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 if (vi.left > ci.left || vi.top > ci.top
1623 || vi.right > ci.right || vi.bottom > ci.bottom) {
1624 // We'll assume that we aren't going to change the scroll
1625 // offset, since we want to avoid that unless it is actually
1626 // going to make the focus visible... otherwise we scroll
1627 // all over the place.
1628 scrollY = mScrollY;
1629 // We can be called for two different situations: during a draw,
1630 // to update the scroll position if the focus has changed (in which
1631 // case 'rectangle' is null), or in response to a
1632 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1633 // is non-null and we just want to scroll to whatever that
1634 // rectangle is).
1635 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001636
1637 // When in touch mode, focus points to the previously focused view,
1638 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001639 // line checks whether the view is still in our hierarchy.
1640 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001641 mRealFocusedView = null;
1642 return false;
1643 }
1644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if (focus != mLastScrolledFocus) {
1646 // If the focus has changed, then ignore any requests to scroll
1647 // to a rectangle; first we want to make sure the entire focus
1648 // view is visible.
1649 rectangle = null;
1650 }
1651 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1652 + " rectangle=" + rectangle + " ci=" + ci
1653 + " vi=" + vi);
1654 if (focus == mLastScrolledFocus && !mScrollMayChange
1655 && rectangle == null) {
1656 // Optimization: if the focus hasn't changed since last
1657 // time, and no layout has happened, then just leave things
1658 // as they are.
1659 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1660 + mScrollY + " vi=" + vi.toShortString());
1661 } else if (focus != null) {
1662 // We need to determine if the currently focused view is
1663 // within the visible part of the window and, if not, apply
1664 // a pan so it can be seen.
1665 mLastScrolledFocus = focus;
1666 mScrollMayChange = false;
1667 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1668 // Try to find the rectangle from the focus view.
1669 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1670 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1671 + mView.getWidth() + " h=" + mView.getHeight()
1672 + " ci=" + ci.toShortString()
1673 + " vi=" + vi.toShortString());
1674 if (rectangle == null) {
1675 focus.getFocusedRect(mTempRect);
1676 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1677 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001678 if (mView instanceof ViewGroup) {
1679 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1680 focus, mTempRect);
1681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1683 "Focus in window: focusRect="
1684 + mTempRect.toShortString()
1685 + " visRect=" + mVisRect.toShortString());
1686 } else {
1687 mTempRect.set(rectangle);
1688 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1689 "Request scroll to rect: "
1690 + mTempRect.toShortString()
1691 + " visRect=" + mVisRect.toShortString());
1692 }
1693 if (mTempRect.intersect(mVisRect)) {
1694 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1695 "Focus window visible rect: "
1696 + mTempRect.toShortString());
1697 if (mTempRect.height() >
1698 (mView.getHeight()-vi.top-vi.bottom)) {
1699 // If the focus simply is not going to fit, then
1700 // best is probably just to leave things as-is.
1701 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1702 "Too tall; leaving scrollY=" + scrollY);
1703 } else if ((mTempRect.top-scrollY) < vi.top) {
1704 scrollY -= vi.top - (mTempRect.top-scrollY);
1705 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1706 "Top covered; scrollY=" + scrollY);
1707 } else if ((mTempRect.bottom-scrollY)
1708 > (mView.getHeight()-vi.bottom)) {
1709 scrollY += (mTempRect.bottom-scrollY)
1710 - (mView.getHeight()-vi.bottom);
1711 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1712 "Bottom covered; scrollY=" + scrollY);
1713 }
1714 handled = true;
1715 }
1716 }
1717 }
1718 }
Romain Guy8506ab42009-06-11 17:35:47 -07001719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 if (scrollY != mScrollY) {
1721 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1722 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001723 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 if (mScroller == null) {
1725 mScroller = new Scroller(mView.getContext());
1726 }
1727 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1728 } else if (mScroller != null) {
1729 mScroller.abortAnimation();
1730 }
1731 mScrollY = scrollY;
1732 }
Romain Guy8506ab42009-06-11 17:35:47 -07001733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 return handled;
1735 }
Romain Guy8506ab42009-06-11 17:35:47 -07001736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 public void requestChildFocus(View child, View focused) {
1738 checkThread();
1739 if (mFocusedView != focused) {
1740 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1741 scheduleTraversals();
1742 }
1743 mFocusedView = mRealFocusedView = focused;
1744 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1745 + mFocusedView);
1746 }
1747
1748 public void clearChildFocus(View child) {
1749 checkThread();
1750
1751 View oldFocus = mFocusedView;
1752
1753 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1754 mFocusedView = mRealFocusedView = null;
1755 if (mView != null && !mView.hasFocus()) {
1756 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1757 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1758 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1759 }
1760 } else if (oldFocus != null) {
1761 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1762 }
1763 }
1764
1765
1766 public void focusableViewAvailable(View v) {
1767 checkThread();
1768
1769 if (mView != null && !mView.hasFocus()) {
1770 v.requestFocus();
1771 } else {
1772 // the one case where will transfer focus away from the current one
1773 // is if the current view is a view group that prefers to give focus
1774 // to its children first AND the view is a descendant of it.
1775 mFocusedView = mView.findFocus();
1776 boolean descendantsHaveDibsOnFocus =
1777 (mFocusedView instanceof ViewGroup) &&
1778 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1779 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1780 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1781 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1782 v.requestFocus();
1783 }
1784 }
1785 }
1786
1787 public void recomputeViewAttributes(View child) {
1788 checkThread();
1789 if (mView == child) {
1790 mAttachInfo.mRecomputeGlobalAttributes = true;
1791 if (!mWillDrawSoon) {
1792 scheduleTraversals();
1793 }
1794 }
1795 }
1796
1797 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001798 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 mView.dispatchDetachedFromWindow();
1800 }
1801
1802 mView = null;
1803 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001804 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805
Romain Guy29d89972010-09-22 16:10:57 -07001806 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001807
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001808 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001810 if (mInputChannel != null) {
1811 if (mInputQueueCallback != null) {
1812 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1813 mInputQueueCallback = null;
1814 } else {
1815 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001816 }
1817 }
1818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 try {
1820 sWindowSession.remove(mWindow);
1821 } catch (RemoteException e) {
1822 }
Jeff Brown349703e2010-06-22 01:27:15 -07001823
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001824 // Dispose the input channel after removing the window so the Window Manager
1825 // doesn't interpret the input channel being closed as an abnormal termination.
1826 if (mInputChannel != null) {
1827 mInputChannel.dispose();
1828 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
Romain Guy8506ab42009-06-11 17:35:47 -07001831
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001832 void updateConfiguration(Configuration config, boolean force) {
1833 if (DEBUG_CONFIGURATION) Log.v(TAG,
1834 "Applying new config to window "
1835 + mWindowAttributes.getTitle()
1836 + ": " + config);
1837 synchronized (sConfigCallbacks) {
1838 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1839 sConfigCallbacks.get(i).onConfigurationChanged(config);
1840 }
1841 }
1842 if (mView != null) {
1843 // At this point the resources have been updated to
1844 // have the most recent config, whatever that is. Use
1845 // the on in them which may be newer.
1846 if (mView != null) {
1847 config = mView.getResources().getConfiguration();
1848 }
1849 if (force || mLastConfiguration.diff(config) != 0) {
1850 mLastConfiguration.setTo(config);
1851 mView.dispatchConfigurationChanged(config);
1852 }
1853 }
1854 }
1855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 /**
1857 * Return true if child is an ancestor of parent, (or equal to the parent).
1858 */
1859 private static boolean isViewDescendantOf(View child, View parent) {
1860 if (child == parent) {
1861 return true;
1862 }
1863
1864 final ViewParent theParent = child.getParent();
1865 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1866 }
1867
Romain Guycdb86672010-03-18 18:54:50 -07001868 private static void forceLayout(View view) {
1869 view.forceLayout();
1870 if (view instanceof ViewGroup) {
1871 ViewGroup group = (ViewGroup) view;
1872 final int count = group.getChildCount();
1873 for (int i = 0; i < count; i++) {
1874 forceLayout(group.getChildAt(i));
1875 }
1876 }
1877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878
1879 public final static int DO_TRAVERSAL = 1000;
1880 public final static int DIE = 1001;
1881 public final static int RESIZED = 1002;
1882 public final static int RESIZED_REPORT = 1003;
1883 public final static int WINDOW_FOCUS_CHANGED = 1004;
1884 public final static int DISPATCH_KEY = 1005;
1885 public final static int DISPATCH_POINTER = 1006;
1886 public final static int DISPATCH_TRACKBALL = 1007;
1887 public final static int DISPATCH_APP_VISIBILITY = 1008;
1888 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1889 public final static int FINISHED_EVENT = 1010;
1890 public final static int DISPATCH_KEY_FROM_IME = 1011;
1891 public final static int FINISH_INPUT_CONNECTION = 1012;
1892 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001893 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001894 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001895 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896
1897 @Override
1898 public void handleMessage(Message msg) {
1899 switch (msg.what) {
1900 case View.AttachInfo.INVALIDATE_MSG:
1901 ((View) msg.obj).invalidate();
1902 break;
1903 case View.AttachInfo.INVALIDATE_RECT_MSG:
1904 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1905 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1906 info.release();
1907 break;
1908 case DO_TRAVERSAL:
1909 if (mProfile) {
1910 Debug.startMethodTracing("ViewRoot");
1911 }
1912
1913 performTraversals();
1914
1915 if (mProfile) {
1916 Debug.stopMethodTracing();
1917 mProfile = false;
1918 }
1919 break;
1920 case FINISHED_EVENT:
1921 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1922 break;
1923 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001924 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001926 case DISPATCH_POINTER:
1927 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1928 break;
1929 case DISPATCH_TRACKBALL:
1930 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1931 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 case DISPATCH_APP_VISIBILITY:
1933 handleAppVisibility(msg.arg1 != 0);
1934 break;
1935 case DISPATCH_GET_NEW_SURFACE:
1936 handleGetNewSurface();
1937 break;
1938 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001939 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001942 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001943 && mPendingVisibleInsets.equals(ri.visibleInsets)
1944 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 break;
1946 }
1947 // fall through...
1948 case RESIZED_REPORT:
1949 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001950 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1951 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001952 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 mWinFrame.left = 0;
1955 mWinFrame.right = msg.arg1;
1956 mWinFrame.top = 0;
1957 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001958 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1959 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 if (msg.what == RESIZED_REPORT) {
1961 mReportNextDraw = true;
1962 }
Romain Guycdb86672010-03-18 18:54:50 -07001963
1964 if (mView != null) {
1965 forceLayout(mView);
1966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 requestLayout();
1968 }
1969 break;
1970 case WINDOW_FOCUS_CHANGED: {
1971 if (mAdded) {
1972 boolean hasWindowFocus = msg.arg1 != 0;
1973 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1974 if (hasWindowFocus) {
1975 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001976 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977
Romain Guyc361da82010-10-25 15:29:10 -07001978 if (mAttachInfo.mHardwareRenderer != null &&
1979 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001980 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1981 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
1983 }
Romain Guy8506ab42009-06-11 17:35:47 -07001984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 mLastWasImTarget = WindowManager.LayoutParams
1986 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 InputMethodManager imm = InputMethodManager.peekInstance();
1989 if (mView != null) {
1990 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1991 imm.startGettingWindowFocus(mView);
1992 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001993 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 mView.dispatchWindowFocusChanged(hasWindowFocus);
1995 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 // Note: must be done after the focus change callbacks,
1998 // so all of the view state is set up correctly.
1999 if (hasWindowFocus) {
2000 if (imm != null && mLastWasImTarget) {
2001 imm.onWindowFocus(mView, mView.findFocus(),
2002 mWindowAttributes.softInputMode,
2003 !mHasHadWindowFocus, mWindowAttributes.flags);
2004 }
2005 // Clear the forward bit. We can just do this directly, since
2006 // the window manager doesn't care about it.
2007 mWindowAttributes.softInputMode &=
2008 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2009 ((WindowManager.LayoutParams)mView.getLayoutParams())
2010 .softInputMode &=
2011 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2012 mHasHadWindowFocus = true;
2013 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002014
2015 if (hasWindowFocus && mView != null) {
2016 sendAccessibilityEvents();
2017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 }
2019 } break;
2020 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002021 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002023 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002025 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002027 KeyEvent event = (KeyEvent)msg.obj;
2028 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2029 // The IME is trying to say this event is from the
2030 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002031 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002032 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002033 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002034 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 case FINISH_INPUT_CONNECTION: {
2036 InputMethodManager imm = InputMethodManager.peekInstance();
2037 if (imm != null) {
2038 imm.reportFinishInputConnection((InputConnection)msg.obj);
2039 }
2040 } break;
2041 case CHECK_FOCUS: {
2042 InputMethodManager imm = InputMethodManager.peekInstance();
2043 if (imm != null) {
2044 imm.checkFocus();
2045 }
2046 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002047 case CLOSE_SYSTEM_DIALOGS: {
2048 if (mView != null) {
2049 mView.onCloseSystemDialogs((String)msg.obj);
2050 }
2051 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002052 case DISPATCH_DRAG_EVENT:
2053 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07002054 handleDragEvent((DragEvent)msg.obj);
2055 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002058
Jeff Brown3915bb82010-11-05 15:02:16 -07002059 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002060 if (mFinishedCallback != null) {
2061 Slog.w(TAG, "Received a new input event from the input queue but there is "
2062 + "already an unfinished input event in progress.");
2063 }
2064
2065 mFinishedCallback = finishedCallback;
2066 }
2067
Jeff Brown3915bb82010-11-05 15:02:16 -07002068 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002069 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002070
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002071 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002072 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002073 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002074 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002075 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2076 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002077 }
2078 }
2079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 /**
2081 * Something in the current window tells us we need to change the touch mode. For
2082 * example, we are not in touch mode, and the user touches the screen.
2083 *
2084 * If the touch mode has changed, tell the window manager, and handle it locally.
2085 *
2086 * @param inTouchMode Whether we want to be in touch mode.
2087 * @return True if the touch mode changed and focus changed was changed as a result
2088 */
2089 boolean ensureTouchMode(boolean inTouchMode) {
2090 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2091 + "touch mode is " + mAttachInfo.mInTouchMode);
2092 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2093
2094 // tell the window manager
2095 try {
2096 sWindowSession.setInTouchMode(inTouchMode);
2097 } catch (RemoteException e) {
2098 throw new RuntimeException(e);
2099 }
2100
2101 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002102 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 }
2104
2105 /**
2106 * Ensure that the touch mode for this window is set, and if it is changing,
2107 * take the appropriate action.
2108 * @param inTouchMode Whether we want to be in touch mode.
2109 * @return True if the touch mode changed and focus changed was changed as a result
2110 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002111 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2113 + "touch mode is " + mAttachInfo.mInTouchMode);
2114
2115 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2116
2117 mAttachInfo.mInTouchMode = inTouchMode;
2118 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2119
Romain Guy2d4cff62010-04-09 15:39:00 -07002120 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
2122
2123 private boolean enterTouchMode() {
2124 if (mView != null) {
2125 if (mView.hasFocus()) {
2126 // note: not relying on mFocusedView here because this could
2127 // be when the window is first being added, and mFocused isn't
2128 // set yet.
2129 final View focused = mView.findFocus();
2130 if (focused != null && !focused.isFocusableInTouchMode()) {
2131
2132 final ViewGroup ancestorToTakeFocus =
2133 findAncestorToTakeFocusInTouchMode(focused);
2134 if (ancestorToTakeFocus != null) {
2135 // there is an ancestor that wants focus after its descendants that
2136 // is focusable in touch mode.. give it focus
2137 return ancestorToTakeFocus.requestFocus();
2138 } else {
2139 // nothing appropriate to have focus in touch mode, clear it out
2140 mView.unFocus();
2141 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2142 mFocusedView = null;
2143 return true;
2144 }
2145 }
2146 }
2147 }
2148 return false;
2149 }
2150
2151
2152 /**
2153 * Find an ancestor of focused that wants focus after its descendants and is
2154 * focusable in touch mode.
2155 * @param focused The currently focused view.
2156 * @return An appropriate view, or null if no such view exists.
2157 */
2158 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2159 ViewParent parent = focused.getParent();
2160 while (parent instanceof ViewGroup) {
2161 final ViewGroup vgParent = (ViewGroup) parent;
2162 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2163 && vgParent.isFocusableInTouchMode()) {
2164 return vgParent;
2165 }
2166 if (vgParent.isRootNamespace()) {
2167 return null;
2168 } else {
2169 parent = vgParent.getParent();
2170 }
2171 }
2172 return null;
2173 }
2174
2175 private boolean leaveTouchMode() {
2176 if (mView != null) {
2177 if (mView.hasFocus()) {
2178 // i learned the hard way to not trust mFocusedView :)
2179 mFocusedView = mView.findFocus();
2180 if (!(mFocusedView instanceof ViewGroup)) {
2181 // some view has focus, let it keep it
2182 return false;
2183 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2184 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2185 // some view group has focus, and doesn't prefer its children
2186 // over itself for focus, so let them keep it.
2187 return false;
2188 }
2189 }
2190
2191 // find the best view to give focus to in this brave new non-touch-mode
2192 // world
2193 final View focused = focusSearch(null, View.FOCUS_DOWN);
2194 if (focused != null) {
2195 return focused.requestFocus(View.FOCUS_DOWN);
2196 }
2197 }
2198 return false;
2199 }
2200
Jeff Brown3915bb82010-11-05 15:02:16 -07002201 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2202 // If there is no view, then the event will not be handled.
2203 if (mView == null || !mAdded) {
2204 finishPointerEvent(event, sendDone, false);
2205 return;
2206 }
2207
2208 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002209 if (mTranslator != null) {
2210 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 }
2212
Jeff Brown3915bb82010-11-05 15:02:16 -07002213 // Enter touch mode on the down.
2214 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2215 if (isDown) {
2216 ensureTouchMode(true);
2217 }
2218 if(Config.LOGV) {
2219 captureMotionLog("captureDispatchPointer", event);
2220 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002221
Jeff Brown3915bb82010-11-05 15:02:16 -07002222 // Offset the scroll position.
2223 if (mCurScrollY != 0) {
2224 event.offsetLocation(0, mCurScrollY);
2225 }
2226 if (MEASURE_LATENCY) {
2227 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2228 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002229
Jeff Brown3915bb82010-11-05 15:02:16 -07002230 // Remember the touch position for possible drag-initiation.
2231 mLastTouchPoint.x = event.getRawX();
2232 mLastTouchPoint.y = event.getRawY();
2233
2234 // Dispatch touch to view hierarchy.
2235 boolean handled = mView.dispatchTouchEvent(event);
2236 if (MEASURE_LATENCY) {
2237 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2238 }
2239 if (handled) {
2240 finishPointerEvent(event, sendDone, true);
2241 return;
2242 }
2243
2244 // Apply edge slop and try again, if appropriate.
2245 final int edgeFlags = event.getEdgeFlags();
2246 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2247 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2248 int direction = View.FOCUS_UP;
2249 int x = (int)event.getX();
2250 int y = (int)event.getY();
2251 final int[] deltas = new int[2];
2252
2253 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2254 direction = View.FOCUS_DOWN;
2255 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2256 deltas[0] = edgeSlop;
2257 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002258 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002259 deltas[0] = -edgeSlop;
2260 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002261 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002262 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2263 direction = View.FOCUS_UP;
2264 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2265 deltas[0] = edgeSlop;
2266 x += edgeSlop;
2267 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2268 deltas[0] = -edgeSlop;
2269 x -= edgeSlop;
2270 }
2271 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2272 direction = View.FOCUS_RIGHT;
2273 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2274 direction = View.FOCUS_LEFT;
2275 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002276
Jeff Brown3915bb82010-11-05 15:02:16 -07002277 View nearest = FocusFinder.getInstance().findNearestTouchable(
2278 ((ViewGroup) mView), x, y, direction, deltas);
2279 if (nearest != null) {
2280 event.offsetLocation(deltas[0], deltas[1]);
2281 event.setEdgeFlags(0);
2282 if (mView.dispatchTouchEvent(event)) {
2283 finishPointerEvent(event, sendDone, true);
2284 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002285 }
2286 }
2287 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002288
2289 // Pointer event was unhandled.
2290 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002291 }
2292
Jeff Brown3915bb82010-11-05 15:02:16 -07002293 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2294 event.recycle();
2295 if (sendDone) {
2296 finishInputEvent(handled);
2297 }
2298 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2299 }
2300
2301 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2303
Jeff Brown3915bb82010-11-05 15:02:16 -07002304 // If there is no view, then the event will not be handled.
2305 if (mView == null || !mAdded) {
2306 finishTrackballEvent(event, sendDone, false);
2307 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
2309
Jeff Brown3915bb82010-11-05 15:02:16 -07002310 // Deliver the trackball event to the view.
2311 if (mView.dispatchTrackballEvent(event)) {
2312 // If we reach this, we delivered a trackball event to mView and
2313 // mView consumed it. Because we will not translate the trackball
2314 // event into a key event, touch mode will not exit, so we exit
2315 // touch mode here.
2316 ensureTouchMode(false);
2317
2318 finishTrackballEvent(event, sendDone, true);
2319 mLastTrackballTime = Integer.MIN_VALUE;
2320 return;
2321 }
2322
2323 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 final TrackballAxis x = mTrackballAxisX;
2325 final TrackballAxis y = mTrackballAxisY;
2326
2327 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002328 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 // It has been too long since the last movement,
2330 // so restart at the beginning.
2331 x.reset(0);
2332 y.reset(0);
2333 mLastTrackballTime = curTime;
2334 }
2335
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002336 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002337 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002338 switch (action) {
2339 case MotionEvent.ACTION_DOWN:
2340 x.reset(2);
2341 y.reset(2);
2342 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002343 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2344 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2345 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002346 break;
2347 case MotionEvent.ACTION_UP:
2348 x.reset(2);
2349 y.reset(2);
2350 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002351 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2352 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2353 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002354 break;
2355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002357 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2358 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2359 + " move=" + event.getX()
2360 + " / Y=" + y.position + " step="
2361 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2362 + " move=" + event.getY());
2363 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2364 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002366 // Generate DPAD events based on the trackball movement.
2367 // We pick the axis that has moved the most as the direction of
2368 // the DPAD. When we generate DPAD events for one axis, then the
2369 // other axis is reset -- we don't want to perform DPAD jumps due
2370 // to slight movements in the trackball when making major movements
2371 // along the other axis.
2372 int keycode = 0;
2373 int movement = 0;
2374 float accel = 1;
2375 if (xOff > yOff) {
2376 movement = x.generate((2/event.getXPrecision()));
2377 if (movement != 0) {
2378 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2379 : KeyEvent.KEYCODE_DPAD_LEFT;
2380 accel = x.acceleration;
2381 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002383 } else if (yOff > 0) {
2384 movement = y.generate((2/event.getYPrecision()));
2385 if (movement != 0) {
2386 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2387 : KeyEvent.KEYCODE_DPAD_UP;
2388 accel = y.acceleration;
2389 x.reset(2);
2390 }
2391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002393 if (keycode != 0) {
2394 if (movement < 0) movement = -movement;
2395 int accelMovement = (int)(movement * accel);
2396 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2397 + " accelMovement=" + accelMovement
2398 + " accel=" + accel);
2399 if (accelMovement > movement) {
2400 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2401 + keycode);
2402 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002403 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002404 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002405 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2406 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2407 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002409 while (movement > 0) {
2410 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2411 + keycode);
2412 movement--;
2413 curTime = SystemClock.uptimeMillis();
2414 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002415 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2416 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2417 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002418 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002419 KeyEvent.ACTION_UP, keycode, 0, metaState,
2420 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2421 InputDevice.SOURCE_KEYBOARD), false);
2422 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002423 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002425
2426 // Unfortunately we can't tell whether the application consumed the keys, so
2427 // we always consider the trackball event handled.
2428 finishTrackballEvent(event, sendDone, true);
2429 }
2430
2431 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2432 event.recycle();
2433 if (sendDone) {
2434 finishInputEvent(handled);
2435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 }
2437
2438 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002439 * Returns true if the key is used for keyboard navigation.
2440 * @param keyEvent The key event.
2441 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002443 private static boolean isNavigationKey(KeyEvent keyEvent) {
2444 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 case KeyEvent.KEYCODE_DPAD_LEFT:
2446 case KeyEvent.KEYCODE_DPAD_RIGHT:
2447 case KeyEvent.KEYCODE_DPAD_UP:
2448 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002449 case KeyEvent.KEYCODE_DPAD_CENTER:
2450 case KeyEvent.KEYCODE_PAGE_UP:
2451 case KeyEvent.KEYCODE_PAGE_DOWN:
2452 case KeyEvent.KEYCODE_MOVE_HOME:
2453 case KeyEvent.KEYCODE_MOVE_END:
2454 case KeyEvent.KEYCODE_TAB:
2455 case KeyEvent.KEYCODE_SPACE:
2456 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 return true;
2458 }
2459 return false;
2460 }
2461
2462 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002463 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002465 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002467 private static boolean isTypingKey(KeyEvent keyEvent) {
2468 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 }
2470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002472 * 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 -08002473 * @param event The key event.
2474 * @return Whether this key event should be consumed (meaning the act of
2475 * leaving touch mode alone is considered the event).
2476 */
2477 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002478 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 if (!mAttachInfo.mInTouchMode) {
2480 return false;
2481 }
2482
Jeff Brown4e6319b2010-12-13 10:36:51 -08002483 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2484 final int action = event.getAction();
2485 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 return false;
2487 }
2488
Jeff Brown4e6319b2010-12-13 10:36:51 -08002489 // Don't leave touch mode if the IME told us not to.
2490 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2491 return false;
2492 }
2493
2494 // If the key can be used for keyboard navigation then leave touch mode
2495 // and select a focused view if needed (in ensureTouchMode).
2496 // When a new focused view is selected, we consume the navigation key because
2497 // navigation doesn't make much sense unless a view already has focus so
2498 // the key's purpose is to set focus.
2499 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 return ensureTouchMode(false);
2501 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002502
2503 // If the key can be used for typing then leave touch mode
2504 // and select a focused view if needed (in ensureTouchMode).
2505 // Always allow the view to process the typing key.
2506 if (isTypingKey(event)) {
2507 ensureTouchMode(false);
2508 return false;
2509 }
2510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 return false;
2512 }
2513
2514 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002515 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 */
2517 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002518 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 if (ev == null ||
2520 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2521 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 }
Romain Guy8506ab42009-06-11 17:35:47 -07002523
2524 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 sb.append(ev.getDownTime()).append(',');
2526 sb.append(ev.getEventTime()).append(',');
2527 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002528 sb.append(ev.getX()).append(',');
2529 sb.append(ev.getY()).append(',');
2530 sb.append(ev.getPressure()).append(',');
2531 sb.append(ev.getSize()).append(',');
2532 sb.append(ev.getMetaState()).append(',');
2533 sb.append(ev.getXPrecision()).append(',');
2534 sb.append(ev.getYPrecision()).append(',');
2535 sb.append(ev.getDeviceId()).append(',');
2536 sb.append(ev.getEdgeFlags());
2537 Log.d(TAG, sb.toString());
2538 }
2539 /**
2540 * log motion events
2541 */
2542 private static void captureKeyLog(String subTag, KeyEvent ev) {
2543 //check dynamic switch
2544 if (ev == null ||
2545 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2546 return;
2547 }
2548 StringBuilder sb = new StringBuilder(subTag + ": ");
2549 sb.append(ev.getDownTime()).append(',');
2550 sb.append(ev.getEventTime()).append(',');
2551 sb.append(ev.getAction()).append(',');
2552 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 sb.append(ev.getRepeatCount()).append(',');
2554 sb.append(ev.getMetaState()).append(',');
2555 sb.append(ev.getDeviceId()).append(',');
2556 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002557 Log.d(TAG, sb.toString());
2558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559
2560 int enqueuePendingEvent(Object event, boolean sendDone) {
2561 int seq = mPendingEventSeq+1;
2562 if (seq < 0) seq = 0;
2563 mPendingEventSeq = seq;
2564 mPendingEvents.put(seq, event);
2565 return sendDone ? seq : -seq;
2566 }
2567
2568 Object retrievePendingEvent(int seq) {
2569 if (seq < 0) seq = -seq;
2570 Object event = mPendingEvents.get(seq);
2571 if (event != null) {
2572 mPendingEvents.remove(seq);
2573 }
2574 return event;
2575 }
Romain Guy8506ab42009-06-11 17:35:47 -07002576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002578 // If there is no view, then the event will not be handled.
2579 if (mView == null || !mAdded) {
2580 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 return;
2582 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002583
2584 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2585
2586 // Perform predispatching before the IME.
2587 if (mView.dispatchKeyEventPreIme(event)) {
2588 finishKeyEvent(event, sendDone, true);
2589 return;
2590 }
2591
2592 // Dispatch to the IME before propagating down the view hierarchy.
2593 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 if (mLastWasImTarget) {
2595 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002596 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 int seq = enqueuePendingEvent(event, sendDone);
2598 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2599 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002600 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 return;
2602 }
2603 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002604
2605 // Not dispatching to IME, continue with post IME actions.
2606 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
2608
Jeff Brown3915bb82010-11-05 15:02:16 -07002609 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2611 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2612 + " handled=" + handled + " event=" + event);
2613 if (event != null) {
2614 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002615 if (handled) {
2616 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002618 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 }
2620 }
2621 }
Romain Guy8506ab42009-06-11 17:35:47 -07002622
Jeff Brown3915bb82010-11-05 15:02:16 -07002623 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2624 // If the view went away, then the event will not be handled.
2625 if (mView == null || !mAdded) {
2626 finishKeyEvent(event, sendDone, false);
2627 return;
2628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629
Jeff Brown3915bb82010-11-05 15:02:16 -07002630 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2631 if (checkForLeavingTouchModeAndConsume(event)) {
2632 finishKeyEvent(event, sendDone, true);
2633 return;
2634 }
Romain Guy8506ab42009-06-11 17:35:47 -07002635
Jeff Brown3915bb82010-11-05 15:02:16 -07002636 if (Config.LOGV) {
2637 captureKeyLog("captureDispatchKeyEvent", event);
2638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639
Jeff Brown90655042010-12-02 13:50:46 -08002640 // Make sure the fallback event policy sees all keys that will be delivered to the
2641 // view hierarchy.
2642 mFallbackEventHandler.preDispatchKeyEvent(event);
2643
Jeff Brown3915bb82010-11-05 15:02:16 -07002644 // Deliver the key to the view hierarchy.
2645 if (mView.dispatchKeyEvent(event)) {
2646 finishKeyEvent(event, sendDone, true);
2647 return;
2648 }
Joe Onorato86f67862010-11-05 18:57:34 -07002649
Jeff Brownc1df9072010-12-21 16:38:50 -08002650 // If the Control modifier is held, try to interpret the key as a shortcut.
2651 if (event.getAction() == KeyEvent.ACTION_UP
2652 && event.isCtrlPressed()
2653 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2654 if (mView.dispatchKeyShortcutEvent(event)) {
2655 finishKeyEvent(event, sendDone, true);
2656 return;
2657 }
2658 }
2659
Jeff Brown3915bb82010-11-05 15:02:16 -07002660 // Apply the fallback event policy.
2661 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2662 finishKeyEvent(event, sendDone, true);
2663 return;
2664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665
Jeff Brown3915bb82010-11-05 15:02:16 -07002666 // Handle automatic focus changes.
2667 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2668 int direction = 0;
2669 switch (event.getKeyCode()) {
2670 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002671 if (event.hasNoModifiers()) {
2672 direction = View.FOCUS_LEFT;
2673 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002674 break;
2675 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002676 if (event.hasNoModifiers()) {
2677 direction = View.FOCUS_RIGHT;
2678 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002679 break;
2680 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002681 if (event.hasNoModifiers()) {
2682 direction = View.FOCUS_UP;
2683 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002684 break;
2685 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002686 if (event.hasNoModifiers()) {
2687 direction = View.FOCUS_DOWN;
2688 }
2689 break;
2690 case KeyEvent.KEYCODE_TAB:
2691 if (event.hasNoModifiers()) {
2692 direction = View.FOCUS_FORWARD;
2693 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2694 direction = View.FOCUS_BACKWARD;
2695 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002696 break;
2697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698
Jeff Brown3915bb82010-11-05 15:02:16 -07002699 if (direction != 0) {
2700 View focused = mView != null ? mView.findFocus() : null;
2701 if (focused != null) {
2702 View v = focused.focusSearch(direction);
2703 if (v != null && v != focused) {
2704 // do the math the get the interesting rect
2705 // of previous focused into the coord system of
2706 // newly focused view
2707 focused.getFocusedRect(mTempRect);
2708 if (mView instanceof ViewGroup) {
2709 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2710 focused, mTempRect);
2711 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2712 v, mTempRect);
2713 }
2714 if (v.requestFocus(direction, mTempRect)) {
2715 playSoundEffect(
2716 SoundEffectConstants.getContantForFocusDirection(direction));
2717 finishKeyEvent(event, sendDone, true);
2718 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 }
2720 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002721
2722 // Give the focused view a last chance to handle the dpad key.
2723 if (mView.dispatchUnhandledMove(focused, direction)) {
2724 finishKeyEvent(event, sendDone, true);
2725 return;
2726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 }
2728 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730
Jeff Brown3915bb82010-11-05 15:02:16 -07002731 // Key was unhandled.
2732 finishKeyEvent(event, sendDone, false);
2733 }
2734
2735 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2736 if (sendDone) {
2737 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 }
2739 }
2740
Christopher Tatea53146c2010-09-07 11:57:52 -07002741 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002742 void setLocalDragState(Object obj) {
2743 mLocalDragState = obj;
2744 }
2745
Christopher Tatea53146c2010-09-07 11:57:52 -07002746 private void handleDragEvent(DragEvent event) {
2747 // From the root, only drag start/end/location are dispatched. entered/exited
2748 // are determined and dispatched by the viewgroup hierarchy, who then report
2749 // that back here for ultimate reporting back to the framework.
2750 if (mView != null && mAdded) {
2751 final int what = event.mAction;
2752
2753 if (what == DragEvent.ACTION_DRAG_EXITED) {
2754 // A direct EXITED event means that the window manager knows we've just crossed
2755 // a window boundary, so the current drag target within this one must have
2756 // just been exited. Send it the usual notifications and then we're done
2757 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002758 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002759 } else {
2760 // Cache the drag description when the operation starts, then fill it in
2761 // on subsequent calls as a convenience
2762 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002763 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002764 mDragDescription = event.mClipDescription;
2765 } else {
2766 event.mClipDescription = mDragDescription;
2767 }
2768
2769 // For events with a [screen] location, translate into window coordinates
2770 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2771 mDragPoint.set(event.mX, event.mY);
2772 if (mTranslator != null) {
2773 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2774 }
2775
2776 if (mCurScrollY != 0) {
2777 mDragPoint.offset(0, mCurScrollY);
2778 }
2779
2780 event.mX = mDragPoint.x;
2781 event.mY = mDragPoint.y;
2782 }
2783
2784 // Remember who the current drag target is pre-dispatch
2785 final View prevDragView = mCurrentDragView;
2786
2787 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002788 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002789
2790 // If we changed apparent drag target, tell the OS about it
2791 if (prevDragView != mCurrentDragView) {
2792 try {
2793 if (prevDragView != null) {
2794 sWindowSession.dragRecipientExited(mWindow);
2795 }
2796 if (mCurrentDragView != null) {
2797 sWindowSession.dragRecipientEntered(mWindow);
2798 }
2799 } catch (RemoteException e) {
2800 Slog.e(TAG, "Unable to note drag target change");
2801 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002802 }
Chris Tated4533f12010-10-19 15:15:08 -07002803
Christopher Tate407b4e92010-11-30 17:14:08 -08002804 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002805 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002806 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002807 try {
2808 Log.i(TAG, "Reporting drop result: " + result);
2809 sWindowSession.reportDropResult(mWindow, result);
2810 } catch (RemoteException e) {
2811 Log.e(TAG, "Unable to report drop result");
2812 }
2813 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002814
2815 // When the drag operation ends, release any local state object
2816 // that may have been in use
2817 if (what == DragEvent.ACTION_DRAG_ENDED) {
2818 setLocalDragState(null);
2819 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002820 }
2821 }
2822 event.recycle();
2823 }
2824
Christopher Tate2c095f32010-10-04 14:13:40 -07002825 public void getLastTouchPoint(Point outLocation) {
2826 outLocation.x = (int) mLastTouchPoint.x;
2827 outLocation.y = (int) mLastTouchPoint.y;
2828 }
2829
Chris Tate9d1ab882010-11-02 15:55:39 -07002830 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002831 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002832 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002833 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002834 }
2835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 private AudioManager getAudioManager() {
2837 if (mView == null) {
2838 throw new IllegalStateException("getAudioManager called when there is no mView");
2839 }
2840 if (mAudioManager == null) {
2841 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2842 }
2843 return mAudioManager;
2844 }
2845
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002846 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2847 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002848
2849 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002850 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002851 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002852 restore = true;
2853 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002854 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002855 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002856 if (params != null) {
2857 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002858 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002859 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002860 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002861 int relayoutResult = sWindowSession.relayout(
2862 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002863 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2864 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002865 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002866 mPendingContentInsets, mPendingVisibleInsets,
2867 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002868 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002869 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002870 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002871 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002872
2873 if (mTranslator != null) {
2874 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2875 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2876 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002877 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002878 return relayoutResult;
2879 }
Romain Guy8506ab42009-06-11 17:35:47 -07002880
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002881 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 * {@inheritDoc}
2883 */
2884 public void playSoundEffect(int effectId) {
2885 checkThread();
2886
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002887 try {
2888 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002890 switch (effectId) {
2891 case SoundEffectConstants.CLICK:
2892 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2893 return;
2894 case SoundEffectConstants.NAVIGATION_DOWN:
2895 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2896 return;
2897 case SoundEffectConstants.NAVIGATION_LEFT:
2898 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2899 return;
2900 case SoundEffectConstants.NAVIGATION_RIGHT:
2901 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2902 return;
2903 case SoundEffectConstants.NAVIGATION_UP:
2904 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2905 return;
2906 default:
2907 throw new IllegalArgumentException("unknown effect id " + effectId +
2908 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2909 }
2910 } catch (IllegalStateException e) {
2911 // Exception thrown by getAudioManager() when mView is null
2912 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2913 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 }
2915 }
2916
2917 /**
2918 * {@inheritDoc}
2919 */
2920 public boolean performHapticFeedback(int effectId, boolean always) {
2921 try {
2922 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2923 } catch (RemoteException e) {
2924 return false;
2925 }
2926 }
2927
2928 /**
2929 * {@inheritDoc}
2930 */
2931 public View focusSearch(View focused, int direction) {
2932 checkThread();
2933 if (!(mView instanceof ViewGroup)) {
2934 return null;
2935 }
2936 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2937 }
2938
2939 public void debug() {
2940 mView.debug();
2941 }
2942
2943 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002944 if (immediate) {
2945 doDie();
2946 } else {
2947 sendEmptyMessage(DIE);
2948 }
2949 }
2950
2951 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002953 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 synchronized (this) {
2955 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002956 destroyHardwareRenderer();
2957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 int viewVisibility = mView.getVisibility();
2959 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2960 if (mWindowAttributesChanged || viewVisibilityChanged) {
2961 // If layout params have been changed, first give them
2962 // to the window manager to make sure it has the correct
2963 // animation info.
2964 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002965 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2966 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 sWindowSession.finishDrawing(mWindow);
2968 }
2969 } catch (RemoteException e) {
2970 }
2971 }
2972
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002973 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 if (mAdded) {
2976 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002977 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 }
2979 }
2980 }
2981
Romain Guy29d89972010-09-22 16:10:57 -07002982 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002983 if (mAttachInfo.mHardwareRenderer != null) {
2984 mAttachInfo.mHardwareRenderer.destroy(true);
2985 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002986 mAttachInfo.mHardwareAccelerated = false;
2987 }
2988 }
2989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 public void dispatchFinishedEvent(int seq, boolean handled) {
2991 Message msg = obtainMessage(FINISHED_EVENT);
2992 msg.arg1 = seq;
2993 msg.arg2 = handled ? 1 : 0;
2994 sendMessage(msg);
2995 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002998 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3000 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3001 + " visibleInsets=" + visibleInsets.toShortString()
3002 + " reportDraw=" + reportDraw);
3003 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003004 if (mTranslator != null) {
3005 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3006 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3007 w *= mTranslator.applicationInvertedScale;
3008 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003009 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003010 msg.arg1 = w;
3011 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003012 ResizedInfo ri = new ResizedInfo();
3013 ri.coveredInsets = new Rect(coveredInsets);
3014 ri.visibleInsets = new Rect(visibleInsets);
3015 ri.newConfig = newConfig;
3016 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 sendMessage(msg);
3018 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003019
Jeff Brown3915bb82010-11-05 15:02:16 -07003020 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003021
3022 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003023 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003024 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003025 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003026 }
3027
Jeff Brown3915bb82010-11-05 15:02:16 -07003028 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003029 startInputEvent(finishedCallback);
3030 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003031 }
3032 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033
3034 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003035 dispatchKey(event, false);
3036 }
3037
3038 private void dispatchKey(KeyEvent event, boolean sendDone) {
3039 //noinspection ConstantConditions
3040 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3041 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003042 if (DBG) Log.d("keydisp", "===================================================");
3043 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 debug();
3046
Romain Guy812ccbe2010-06-01 14:07:24 -07003047 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 }
3049 }
3050
3051 Message msg = obtainMessage(DISPATCH_KEY);
3052 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003053 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054
3055 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003056 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057
3058 sendMessageAtTime(msg, event.getEventTime());
3059 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003060
3061 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003062 dispatchMotion(event, false);
3063 }
3064
3065 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003066 int source = event.getSource();
3067 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003068 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003069 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003070 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003071 } else {
3072 // TODO
3073 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003074 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003075 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003076 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003077 }
3078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003080 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003081 dispatchPointer(event, false);
3082 }
3083
3084 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 Message msg = obtainMessage(DISPATCH_POINTER);
3086 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003087 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003088 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 }
3090
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003091 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003092 dispatchTrackball(event, false);
3093 }
3094
3095 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3097 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003098 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003099 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 public void dispatchAppVisibility(boolean visible) {
3103 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3104 msg.arg1 = visible ? 1 : 0;
3105 sendMessage(msg);
3106 }
3107
3108 public void dispatchGetNewSurface() {
3109 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3110 sendMessage(msg);
3111 }
3112
3113 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3114 Message msg = Message.obtain();
3115 msg.what = WINDOW_FOCUS_CHANGED;
3116 msg.arg1 = hasFocus ? 1 : 0;
3117 msg.arg2 = inTouchMode ? 1 : 0;
3118 sendMessage(msg);
3119 }
3120
Dianne Hackbornffa42482009-09-23 22:20:11 -07003121 public void dispatchCloseSystemDialogs(String reason) {
3122 Message msg = Message.obtain();
3123 msg.what = CLOSE_SYSTEM_DIALOGS;
3124 msg.obj = reason;
3125 sendMessage(msg);
3126 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003127
3128 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003129 final int what;
3130 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3131 what = DISPATCH_DRAG_LOCATION_EVENT;
3132 removeMessages(what);
3133 } else {
3134 what = DISPATCH_DRAG_EVENT;
3135 }
Christopher Tate407b4e92010-11-30 17:14:08 -08003136 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
Chris Tate91e9bb32010-10-12 12:58:43 -07003137 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003138 sendMessage(msg);
3139 }
3140
svetoslavganov75986cf2009-05-14 22:28:01 -07003141 /**
3142 * The window is getting focus so if there is anything focused/selected
3143 * send an {@link AccessibilityEvent} to announce that.
3144 */
3145 private void sendAccessibilityEvents() {
3146 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3147 return;
3148 }
3149 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3150 View focusedView = mView.findFocus();
3151 if (focusedView != null && focusedView != mView) {
3152 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3153 }
3154 }
3155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 public boolean showContextMenuForChild(View originalView) {
3157 return false;
3158 }
3159
Adam Powell6e346362010-07-23 10:18:23 -07003160 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3161 return null;
3162 }
3163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 public void createContextMenu(ContextMenu menu) {
3165 }
3166
3167 public void childDrawableStateChanged(View child) {
3168 }
3169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 void checkThread() {
3171 if (mThread != Thread.currentThread()) {
3172 throw new CalledFromWrongThreadException(
3173 "Only the original thread that created a view hierarchy can touch its views.");
3174 }
3175 }
3176
3177 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3178 // ViewRoot never intercepts touch event, so this can be a no-op
3179 }
3180
3181 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3182 boolean immediate) {
3183 return scrollToRectOrFocus(rectangle, immediate);
3184 }
Romain Guy8506ab42009-06-11 17:35:47 -07003185
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003186 class TakenSurfaceHolder extends BaseSurfaceHolder {
3187 @Override
3188 public boolean onAllowLockCanvas() {
3189 return mDrawingAllowed;
3190 }
3191
3192 @Override
3193 public void onRelayoutContainer() {
3194 // Not currently interesting -- from changing between fixed and layout size.
3195 }
3196
3197 public void setFormat(int format) {
3198 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3199 }
3200
3201 public void setType(int type) {
3202 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3203 }
3204
3205 @Override
3206 public void onUpdateSurface() {
3207 // We take care of format and type changes on our own.
3208 throw new IllegalStateException("Shouldn't be here");
3209 }
3210
3211 public boolean isCreating() {
3212 return mIsCreating;
3213 }
3214
3215 @Override
3216 public void setFixedSize(int width, int height) {
3217 throw new UnsupportedOperationException(
3218 "Currently only support sizing from layout");
3219 }
3220
3221 public void setKeepScreenOn(boolean screenOn) {
3222 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3223 }
3224 }
3225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 static class InputMethodCallback extends IInputMethodCallback.Stub {
3227 private WeakReference<ViewRoot> mViewRoot;
3228
3229 public InputMethodCallback(ViewRoot viewRoot) {
3230 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3231 }
Romain Guy8506ab42009-06-11 17:35:47 -07003232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 public void finishedEvent(int seq, boolean handled) {
3234 final ViewRoot viewRoot = mViewRoot.get();
3235 if (viewRoot != null) {
3236 viewRoot.dispatchFinishedEvent(seq, handled);
3237 }
3238 }
3239
3240 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3241 // Stub -- not for use in the client.
3242 }
3243 }
Romain Guy8506ab42009-06-11 17:35:47 -07003244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003246 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247
Romain Guyfb8b7632010-08-23 21:05:08 -07003248 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3250 }
3251
Romain Guyfb8b7632010-08-23 21:05:08 -07003252 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3253 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 final ViewRoot viewRoot = mViewRoot.get();
3255 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003256 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 }
3258 }
3259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 public void dispatchAppVisibility(boolean visible) {
3261 final ViewRoot viewRoot = mViewRoot.get();
3262 if (viewRoot != null) {
3263 viewRoot.dispatchAppVisibility(visible);
3264 }
3265 }
3266
3267 public void dispatchGetNewSurface() {
3268 final ViewRoot viewRoot = mViewRoot.get();
3269 if (viewRoot != null) {
3270 viewRoot.dispatchGetNewSurface();
3271 }
3272 }
3273
3274 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3275 final ViewRoot viewRoot = mViewRoot.get();
3276 if (viewRoot != null) {
3277 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3278 }
3279 }
3280
3281 private static int checkCallingPermission(String permission) {
3282 if (!Process.supportsProcesses()) {
3283 return PackageManager.PERMISSION_GRANTED;
3284 }
3285
3286 try {
3287 return ActivityManagerNative.getDefault().checkPermission(
3288 permission, Binder.getCallingPid(), Binder.getCallingUid());
3289 } catch (RemoteException e) {
3290 return PackageManager.PERMISSION_DENIED;
3291 }
3292 }
3293
3294 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3295 final ViewRoot viewRoot = mViewRoot.get();
3296 if (viewRoot != null) {
3297 final View view = viewRoot.mView;
3298 if (view != null) {
3299 if (checkCallingPermission(Manifest.permission.DUMP) !=
3300 PackageManager.PERMISSION_GRANTED) {
3301 throw new SecurityException("Insufficient permissions to invoke"
3302 + " executeCommand() from pid=" + Binder.getCallingPid()
3303 + ", uid=" + Binder.getCallingUid());
3304 }
3305
3306 OutputStream clientStream = null;
3307 try {
3308 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3309 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3310 } catch (IOException e) {
3311 e.printStackTrace();
3312 } finally {
3313 if (clientStream != null) {
3314 try {
3315 clientStream.close();
3316 } catch (IOException e) {
3317 e.printStackTrace();
3318 }
3319 }
3320 }
3321 }
3322 }
3323 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003324
Dianne Hackbornffa42482009-09-23 22:20:11 -07003325 public void closeSystemDialogs(String reason) {
3326 final ViewRoot viewRoot = mViewRoot.get();
3327 if (viewRoot != null) {
3328 viewRoot.dispatchCloseSystemDialogs(reason);
3329 }
3330 }
3331
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003332 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3333 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003334 if (sync) {
3335 try {
3336 sWindowSession.wallpaperOffsetsComplete(asBinder());
3337 } catch (RemoteException e) {
3338 }
3339 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003340 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003341
3342 public void dispatchWallpaperCommand(String action, int x, int y,
3343 int z, Bundle extras, boolean sync) {
3344 if (sync) {
3345 try {
3346 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3347 } catch (RemoteException e) {
3348 }
3349 }
3350 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003351
3352 /* Drag/drop */
3353 public void dispatchDragEvent(DragEvent event) {
3354 final ViewRoot viewRoot = mViewRoot.get();
3355 if (viewRoot != null) {
3356 viewRoot.dispatchDragEvent(event);
3357 }
3358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 }
3360
3361 /**
3362 * Maintains state information for a single trackball axis, generating
3363 * discrete (DPAD) movements based on raw trackball motion.
3364 */
3365 static final class TrackballAxis {
3366 /**
3367 * The maximum amount of acceleration we will apply.
3368 */
3369 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 /**
3372 * The maximum amount of time (in milliseconds) between events in order
3373 * for us to consider the user to be doing fast trackball movements,
3374 * and thus apply an acceleration.
3375 */
3376 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 /**
3379 * Scaling factor to the time (in milliseconds) between events to how
3380 * much to multiple/divide the current acceleration. When movement
3381 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3382 * FAST_MOVE_TIME it divides it.
3383 */
3384 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 float position;
3387 float absPosition;
3388 float acceleration = 1;
3389 long lastMoveTime = 0;
3390 int step;
3391 int dir;
3392 int nonAccelMovement;
3393
3394 void reset(int _step) {
3395 position = 0;
3396 acceleration = 1;
3397 lastMoveTime = 0;
3398 step = _step;
3399 dir = 0;
3400 }
3401
3402 /**
3403 * Add trackball movement into the state. If the direction of movement
3404 * has been reversed, the state is reset before adding the
3405 * movement (so that you don't have to compensate for any previously
3406 * collected movement before see the result of the movement in the
3407 * new direction).
3408 *
3409 * @return Returns the absolute value of the amount of movement
3410 * collected so far.
3411 */
3412 float collect(float off, long time, String axis) {
3413 long normTime;
3414 if (off > 0) {
3415 normTime = (long)(off * FAST_MOVE_TIME);
3416 if (dir < 0) {
3417 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3418 position = 0;
3419 step = 0;
3420 acceleration = 1;
3421 lastMoveTime = 0;
3422 }
3423 dir = 1;
3424 } else if (off < 0) {
3425 normTime = (long)((-off) * FAST_MOVE_TIME);
3426 if (dir > 0) {
3427 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3428 position = 0;
3429 step = 0;
3430 acceleration = 1;
3431 lastMoveTime = 0;
3432 }
3433 dir = -1;
3434 } else {
3435 normTime = 0;
3436 }
Romain Guy8506ab42009-06-11 17:35:47 -07003437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 // The number of milliseconds between each movement that is
3439 // considered "normal" and will not result in any acceleration
3440 // or deceleration, scaled by the offset we have here.
3441 if (normTime > 0) {
3442 long delta = time - lastMoveTime;
3443 lastMoveTime = time;
3444 float acc = acceleration;
3445 if (delta < normTime) {
3446 // The user is scrolling rapidly, so increase acceleration.
3447 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3448 if (scale > 1) acc *= scale;
3449 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3450 + off + " normTime=" + normTime + " delta=" + delta
3451 + " scale=" + scale + " acc=" + acc);
3452 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3453 } else {
3454 // The user is scrolling slowly, so decrease acceleration.
3455 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3456 if (scale > 1) acc /= scale;
3457 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3458 + off + " normTime=" + normTime + " delta=" + delta
3459 + " scale=" + scale + " acc=" + acc);
3460 acceleration = acc > 1 ? acc : 1;
3461 }
3462 }
3463 position += off;
3464 return (absPosition = Math.abs(position));
3465 }
3466
3467 /**
3468 * Generate the number of discrete movement events appropriate for
3469 * the currently collected trackball movement.
3470 *
3471 * @param precision The minimum movement required to generate the
3472 * first discrete movement.
3473 *
3474 * @return Returns the number of discrete movements, either positive
3475 * or negative, or 0 if there is not enough trackball movement yet
3476 * for a discrete movement.
3477 */
3478 int generate(float precision) {
3479 int movement = 0;
3480 nonAccelMovement = 0;
3481 do {
3482 final int dir = position >= 0 ? 1 : -1;
3483 switch (step) {
3484 // If we are going to execute the first step, then we want
3485 // to do this as soon as possible instead of waiting for
3486 // a full movement, in order to make things look responsive.
3487 case 0:
3488 if (absPosition < precision) {
3489 return movement;
3490 }
3491 movement += dir;
3492 nonAccelMovement += dir;
3493 step = 1;
3494 break;
3495 // If we have generated the first movement, then we need
3496 // to wait for the second complete trackball motion before
3497 // generating the second discrete movement.
3498 case 1:
3499 if (absPosition < 2) {
3500 return movement;
3501 }
3502 movement += dir;
3503 nonAccelMovement += dir;
3504 position += dir > 0 ? -2 : 2;
3505 absPosition = Math.abs(position);
3506 step = 2;
3507 break;
3508 // After the first two, we generate discrete movements
3509 // consistently with the trackball, applying an acceleration
3510 // if the trackball is moving quickly. This is a simple
3511 // acceleration on top of what we already compute based
3512 // on how quickly the wheel is being turned, to apply
3513 // a longer increasing acceleration to continuous movement
3514 // in one direction.
3515 default:
3516 if (absPosition < 1) {
3517 return movement;
3518 }
3519 movement += dir;
3520 position += dir >= 0 ? -1 : 1;
3521 absPosition = Math.abs(position);
3522 float acc = acceleration;
3523 acc *= 1.1f;
3524 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3525 break;
3526 }
3527 } while (true);
3528 }
3529 }
3530
3531 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3532 public CalledFromWrongThreadException(String msg) {
3533 super(msg);
3534 }
3535 }
3536
3537 private SurfaceHolder mHolder = new SurfaceHolder() {
3538 // we only need a SurfaceHolder for opengl. it would be nice
3539 // to implement everything else though, especially the callback
3540 // support (opengl doesn't make use of it right now, but eventually
3541 // will).
3542 public Surface getSurface() {
3543 return mSurface;
3544 }
3545
3546 public boolean isCreating() {
3547 return false;
3548 }
3549
3550 public void addCallback(Callback callback) {
3551 }
3552
3553 public void removeCallback(Callback callback) {
3554 }
3555
3556 public void setFixedSize(int width, int height) {
3557 }
3558
3559 public void setSizeFromLayout() {
3560 }
3561
3562 public void setFormat(int format) {
3563 }
3564
3565 public void setType(int type) {
3566 }
3567
3568 public void setKeepScreenOn(boolean screenOn) {
3569 }
3570
3571 public Canvas lockCanvas() {
3572 return null;
3573 }
3574
3575 public Canvas lockCanvas(Rect dirty) {
3576 return null;
3577 }
3578
3579 public void unlockCanvasAndPost(Canvas canvas) {
3580 }
3581 public Rect getSurfaceFrame() {
3582 return null;
3583 }
3584 };
3585
3586 static RunQueue getRunQueue() {
3587 RunQueue rq = sRunQueues.get();
3588 if (rq != null) {
3589 return rq;
3590 }
3591 rq = new RunQueue();
3592 sRunQueues.set(rq);
3593 return rq;
3594 }
Romain Guy8506ab42009-06-11 17:35:47 -07003595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 /**
3597 * @hide
3598 */
3599 static final class RunQueue {
3600 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3601
3602 void post(Runnable action) {
3603 postDelayed(action, 0);
3604 }
3605
3606 void postDelayed(Runnable action, long delayMillis) {
3607 HandlerAction handlerAction = new HandlerAction();
3608 handlerAction.action = action;
3609 handlerAction.delay = delayMillis;
3610
3611 synchronized (mActions) {
3612 mActions.add(handlerAction);
3613 }
3614 }
3615
3616 void removeCallbacks(Runnable action) {
3617 final HandlerAction handlerAction = new HandlerAction();
3618 handlerAction.action = action;
3619
3620 synchronized (mActions) {
3621 final ArrayList<HandlerAction> actions = mActions;
3622
3623 while (actions.remove(handlerAction)) {
3624 // Keep going
3625 }
3626 }
3627 }
3628
3629 void executeActions(Handler handler) {
3630 synchronized (mActions) {
3631 final ArrayList<HandlerAction> actions = mActions;
3632 final int count = actions.size();
3633
3634 for (int i = 0; i < count; i++) {
3635 final HandlerAction handlerAction = actions.get(i);
3636 handler.postDelayed(handlerAction.action, handlerAction.delay);
3637 }
3638
Romain Guy15df6702009-08-17 20:17:30 -07003639 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 }
3641 }
3642
3643 private static class HandlerAction {
3644 Runnable action;
3645 long delay;
3646
3647 @Override
3648 public boolean equals(Object o) {
3649 if (this == o) return true;
3650 if (o == null || getClass() != o.getClass()) return false;
3651
3652 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 return !(action != null ? !action.equals(that.action) : that.action != null);
3654
3655 }
3656
3657 @Override
3658 public int hashCode() {
3659 int result = action != null ? action.hashCode() : 0;
3660 result = 31 * result + (int) (delay ^ (delay >>> 32));
3661 return result;
3662 }
3663 }
3664 }
3665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667}