blob: 2c6ec71d5c7d5e64801c77fe56c3430d1778bafc [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 Tate7fb8b562011-01-20 13:46:41 -0800231 volatile 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) {
492 // Only enable hardware acceleration if we are not in the system process
493 // The window manager creates ViewRoots to display animated preview windows
494 // of launching apps and we don't want those to be hardware accelerated
495 if (!HardwareRenderer.sRendererDisabled) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800496 // Don't enable hardware acceleration when we're not on the main thread
497 if (Looper.getMainLooper() != Looper.myLooper()) {
498 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
499 + "acceleration outside of the main thread, aborting");
500 return;
501 }
502
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 Tate7fb8b562011-01-20 13:46:41 -08002054 DragEvent event = (DragEvent)msg.obj;
2055 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2056 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002057 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
2059 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002060
Jeff Brown3915bb82010-11-05 15:02:16 -07002061 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002062 if (mFinishedCallback != null) {
2063 Slog.w(TAG, "Received a new input event from the input queue but there is "
2064 + "already an unfinished input event in progress.");
2065 }
2066
2067 mFinishedCallback = finishedCallback;
2068 }
2069
Jeff Brown3915bb82010-11-05 15:02:16 -07002070 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002071 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002072
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002073 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002074 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002075 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002076 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002077 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2078 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002079 }
2080 }
2081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 /**
2083 * Something in the current window tells us we need to change the touch mode. For
2084 * example, we are not in touch mode, and the user touches the screen.
2085 *
2086 * If the touch mode has changed, tell the window manager, and handle it locally.
2087 *
2088 * @param inTouchMode Whether we want to be in touch mode.
2089 * @return True if the touch mode changed and focus changed was changed as a result
2090 */
2091 boolean ensureTouchMode(boolean inTouchMode) {
2092 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2093 + "touch mode is " + mAttachInfo.mInTouchMode);
2094 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2095
2096 // tell the window manager
2097 try {
2098 sWindowSession.setInTouchMode(inTouchMode);
2099 } catch (RemoteException e) {
2100 throw new RuntimeException(e);
2101 }
2102
2103 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002104 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
2106
2107 /**
2108 * Ensure that the touch mode for this window is set, and if it is changing,
2109 * take the appropriate action.
2110 * @param inTouchMode Whether we want to be in touch mode.
2111 * @return True if the touch mode changed and focus changed was changed as a result
2112 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002113 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2115 + "touch mode is " + mAttachInfo.mInTouchMode);
2116
2117 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2118
2119 mAttachInfo.mInTouchMode = inTouchMode;
2120 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2121
Romain Guy2d4cff62010-04-09 15:39:00 -07002122 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
2124
2125 private boolean enterTouchMode() {
2126 if (mView != null) {
2127 if (mView.hasFocus()) {
2128 // note: not relying on mFocusedView here because this could
2129 // be when the window is first being added, and mFocused isn't
2130 // set yet.
2131 final View focused = mView.findFocus();
2132 if (focused != null && !focused.isFocusableInTouchMode()) {
2133
2134 final ViewGroup ancestorToTakeFocus =
2135 findAncestorToTakeFocusInTouchMode(focused);
2136 if (ancestorToTakeFocus != null) {
2137 // there is an ancestor that wants focus after its descendants that
2138 // is focusable in touch mode.. give it focus
2139 return ancestorToTakeFocus.requestFocus();
2140 } else {
2141 // nothing appropriate to have focus in touch mode, clear it out
2142 mView.unFocus();
2143 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2144 mFocusedView = null;
2145 return true;
2146 }
2147 }
2148 }
2149 }
2150 return false;
2151 }
2152
2153
2154 /**
2155 * Find an ancestor of focused that wants focus after its descendants and is
2156 * focusable in touch mode.
2157 * @param focused The currently focused view.
2158 * @return An appropriate view, or null if no such view exists.
2159 */
2160 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2161 ViewParent parent = focused.getParent();
2162 while (parent instanceof ViewGroup) {
2163 final ViewGroup vgParent = (ViewGroup) parent;
2164 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2165 && vgParent.isFocusableInTouchMode()) {
2166 return vgParent;
2167 }
2168 if (vgParent.isRootNamespace()) {
2169 return null;
2170 } else {
2171 parent = vgParent.getParent();
2172 }
2173 }
2174 return null;
2175 }
2176
2177 private boolean leaveTouchMode() {
2178 if (mView != null) {
2179 if (mView.hasFocus()) {
2180 // i learned the hard way to not trust mFocusedView :)
2181 mFocusedView = mView.findFocus();
2182 if (!(mFocusedView instanceof ViewGroup)) {
2183 // some view has focus, let it keep it
2184 return false;
2185 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2186 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2187 // some view group has focus, and doesn't prefer its children
2188 // over itself for focus, so let them keep it.
2189 return false;
2190 }
2191 }
2192
2193 // find the best view to give focus to in this brave new non-touch-mode
2194 // world
2195 final View focused = focusSearch(null, View.FOCUS_DOWN);
2196 if (focused != null) {
2197 return focused.requestFocus(View.FOCUS_DOWN);
2198 }
2199 }
2200 return false;
2201 }
2202
Jeff Brown3915bb82010-11-05 15:02:16 -07002203 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2204 // If there is no view, then the event will not be handled.
2205 if (mView == null || !mAdded) {
2206 finishPointerEvent(event, sendDone, false);
2207 return;
2208 }
2209
2210 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002211 if (mTranslator != null) {
2212 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 }
2214
Jeff Brown3915bb82010-11-05 15:02:16 -07002215 // Enter touch mode on the down.
2216 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2217 if (isDown) {
2218 ensureTouchMode(true);
2219 }
2220 if(Config.LOGV) {
2221 captureMotionLog("captureDispatchPointer", event);
2222 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002223
Jeff Brown3915bb82010-11-05 15:02:16 -07002224 // Offset the scroll position.
2225 if (mCurScrollY != 0) {
2226 event.offsetLocation(0, mCurScrollY);
2227 }
2228 if (MEASURE_LATENCY) {
2229 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2230 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002231
Jeff Brown3915bb82010-11-05 15:02:16 -07002232 // Remember the touch position for possible drag-initiation.
2233 mLastTouchPoint.x = event.getRawX();
2234 mLastTouchPoint.y = event.getRawY();
2235
2236 // Dispatch touch to view hierarchy.
2237 boolean handled = mView.dispatchTouchEvent(event);
2238 if (MEASURE_LATENCY) {
2239 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2240 }
2241 if (handled) {
2242 finishPointerEvent(event, sendDone, true);
2243 return;
2244 }
2245
2246 // Apply edge slop and try again, if appropriate.
2247 final int edgeFlags = event.getEdgeFlags();
2248 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2249 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2250 int direction = View.FOCUS_UP;
2251 int x = (int)event.getX();
2252 int y = (int)event.getY();
2253 final int[] deltas = new int[2];
2254
2255 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2256 direction = View.FOCUS_DOWN;
2257 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2258 deltas[0] = edgeSlop;
2259 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002260 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002261 deltas[0] = -edgeSlop;
2262 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002263 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002264 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2265 direction = View.FOCUS_UP;
2266 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2267 deltas[0] = edgeSlop;
2268 x += edgeSlop;
2269 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2270 deltas[0] = -edgeSlop;
2271 x -= edgeSlop;
2272 }
2273 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2274 direction = View.FOCUS_RIGHT;
2275 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2276 direction = View.FOCUS_LEFT;
2277 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002278
Jeff Brown3915bb82010-11-05 15:02:16 -07002279 View nearest = FocusFinder.getInstance().findNearestTouchable(
2280 ((ViewGroup) mView), x, y, direction, deltas);
2281 if (nearest != null) {
2282 event.offsetLocation(deltas[0], deltas[1]);
2283 event.setEdgeFlags(0);
2284 if (mView.dispatchTouchEvent(event)) {
2285 finishPointerEvent(event, sendDone, true);
2286 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002287 }
2288 }
2289 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002290
2291 // Pointer event was unhandled.
2292 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002293 }
2294
Jeff Brown3915bb82010-11-05 15:02:16 -07002295 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2296 event.recycle();
2297 if (sendDone) {
2298 finishInputEvent(handled);
2299 }
2300 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2301 }
2302
2303 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2305
Jeff Brown3915bb82010-11-05 15:02:16 -07002306 // If there is no view, then the event will not be handled.
2307 if (mView == null || !mAdded) {
2308 finishTrackballEvent(event, sendDone, false);
2309 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311
Jeff Brown3915bb82010-11-05 15:02:16 -07002312 // Deliver the trackball event to the view.
2313 if (mView.dispatchTrackballEvent(event)) {
2314 // If we reach this, we delivered a trackball event to mView and
2315 // mView consumed it. Because we will not translate the trackball
2316 // event into a key event, touch mode will not exit, so we exit
2317 // touch mode here.
2318 ensureTouchMode(false);
2319
2320 finishTrackballEvent(event, sendDone, true);
2321 mLastTrackballTime = Integer.MIN_VALUE;
2322 return;
2323 }
2324
2325 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 final TrackballAxis x = mTrackballAxisX;
2327 final TrackballAxis y = mTrackballAxisY;
2328
2329 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002330 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 // It has been too long since the last movement,
2332 // so restart at the beginning.
2333 x.reset(0);
2334 y.reset(0);
2335 mLastTrackballTime = curTime;
2336 }
2337
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002338 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002339 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002340 switch (action) {
2341 case MotionEvent.ACTION_DOWN:
2342 x.reset(2);
2343 y.reset(2);
2344 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002345 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2346 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2347 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002348 break;
2349 case MotionEvent.ACTION_UP:
2350 x.reset(2);
2351 y.reset(2);
2352 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002353 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2354 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2355 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002356 break;
2357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002359 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2360 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2361 + " move=" + event.getX()
2362 + " / Y=" + y.position + " step="
2363 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2364 + " move=" + event.getY());
2365 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2366 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002368 // Generate DPAD events based on the trackball movement.
2369 // We pick the axis that has moved the most as the direction of
2370 // the DPAD. When we generate DPAD events for one axis, then the
2371 // other axis is reset -- we don't want to perform DPAD jumps due
2372 // to slight movements in the trackball when making major movements
2373 // along the other axis.
2374 int keycode = 0;
2375 int movement = 0;
2376 float accel = 1;
2377 if (xOff > yOff) {
2378 movement = x.generate((2/event.getXPrecision()));
2379 if (movement != 0) {
2380 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2381 : KeyEvent.KEYCODE_DPAD_LEFT;
2382 accel = x.acceleration;
2383 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002385 } else if (yOff > 0) {
2386 movement = y.generate((2/event.getYPrecision()));
2387 if (movement != 0) {
2388 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2389 : KeyEvent.KEYCODE_DPAD_UP;
2390 accel = y.acceleration;
2391 x.reset(2);
2392 }
2393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002395 if (keycode != 0) {
2396 if (movement < 0) movement = -movement;
2397 int accelMovement = (int)(movement * accel);
2398 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2399 + " accelMovement=" + accelMovement
2400 + " accel=" + accel);
2401 if (accelMovement > movement) {
2402 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2403 + keycode);
2404 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002405 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002406 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002407 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2408 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2409 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002411 while (movement > 0) {
2412 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2413 + keycode);
2414 movement--;
2415 curTime = SystemClock.uptimeMillis();
2416 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002417 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2418 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2419 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002420 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002421 KeyEvent.ACTION_UP, keycode, 0, metaState,
2422 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2423 InputDevice.SOURCE_KEYBOARD), false);
2424 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002425 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002427
2428 // Unfortunately we can't tell whether the application consumed the keys, so
2429 // we always consider the trackball event handled.
2430 finishTrackballEvent(event, sendDone, true);
2431 }
2432
2433 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2434 event.recycle();
2435 if (sendDone) {
2436 finishInputEvent(handled);
2437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 }
2439
2440 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002441 * Returns true if the key is used for keyboard navigation.
2442 * @param keyEvent The key event.
2443 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002445 private static boolean isNavigationKey(KeyEvent keyEvent) {
2446 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 case KeyEvent.KEYCODE_DPAD_LEFT:
2448 case KeyEvent.KEYCODE_DPAD_RIGHT:
2449 case KeyEvent.KEYCODE_DPAD_UP:
2450 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002451 case KeyEvent.KEYCODE_DPAD_CENTER:
2452 case KeyEvent.KEYCODE_PAGE_UP:
2453 case KeyEvent.KEYCODE_PAGE_DOWN:
2454 case KeyEvent.KEYCODE_MOVE_HOME:
2455 case KeyEvent.KEYCODE_MOVE_END:
2456 case KeyEvent.KEYCODE_TAB:
2457 case KeyEvent.KEYCODE_SPACE:
2458 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 return true;
2460 }
2461 return false;
2462 }
2463
2464 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002465 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002467 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002469 private static boolean isTypingKey(KeyEvent keyEvent) {
2470 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 }
2472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002474 * 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 -08002475 * @param event The key event.
2476 * @return Whether this key event should be consumed (meaning the act of
2477 * leaving touch mode alone is considered the event).
2478 */
2479 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002480 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 if (!mAttachInfo.mInTouchMode) {
2482 return false;
2483 }
2484
Jeff Brown4e6319b2010-12-13 10:36:51 -08002485 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2486 final int action = event.getAction();
2487 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 return false;
2489 }
2490
Jeff Brown4e6319b2010-12-13 10:36:51 -08002491 // Don't leave touch mode if the IME told us not to.
2492 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2493 return false;
2494 }
2495
2496 // If the key can be used for keyboard navigation then leave touch mode
2497 // and select a focused view if needed (in ensureTouchMode).
2498 // When a new focused view is selected, we consume the navigation key because
2499 // navigation doesn't make much sense unless a view already has focus so
2500 // the key's purpose is to set focus.
2501 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 return ensureTouchMode(false);
2503 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002504
2505 // If the key can be used for typing then leave touch mode
2506 // and select a focused view if needed (in ensureTouchMode).
2507 // Always allow the view to process the typing key.
2508 if (isTypingKey(event)) {
2509 ensureTouchMode(false);
2510 return false;
2511 }
2512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 return false;
2514 }
2515
2516 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002517 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 */
2519 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002520 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 if (ev == null ||
2522 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2523 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
Romain Guy8506ab42009-06-11 17:35:47 -07002525
2526 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 sb.append(ev.getDownTime()).append(',');
2528 sb.append(ev.getEventTime()).append(',');
2529 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002530 sb.append(ev.getX()).append(',');
2531 sb.append(ev.getY()).append(',');
2532 sb.append(ev.getPressure()).append(',');
2533 sb.append(ev.getSize()).append(',');
2534 sb.append(ev.getMetaState()).append(',');
2535 sb.append(ev.getXPrecision()).append(',');
2536 sb.append(ev.getYPrecision()).append(',');
2537 sb.append(ev.getDeviceId()).append(',');
2538 sb.append(ev.getEdgeFlags());
2539 Log.d(TAG, sb.toString());
2540 }
2541 /**
2542 * log motion events
2543 */
2544 private static void captureKeyLog(String subTag, KeyEvent ev) {
2545 //check dynamic switch
2546 if (ev == null ||
2547 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2548 return;
2549 }
2550 StringBuilder sb = new StringBuilder(subTag + ": ");
2551 sb.append(ev.getDownTime()).append(',');
2552 sb.append(ev.getEventTime()).append(',');
2553 sb.append(ev.getAction()).append(',');
2554 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 sb.append(ev.getRepeatCount()).append(',');
2556 sb.append(ev.getMetaState()).append(',');
2557 sb.append(ev.getDeviceId()).append(',');
2558 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002559 Log.d(TAG, sb.toString());
2560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561
2562 int enqueuePendingEvent(Object event, boolean sendDone) {
2563 int seq = mPendingEventSeq+1;
2564 if (seq < 0) seq = 0;
2565 mPendingEventSeq = seq;
2566 mPendingEvents.put(seq, event);
2567 return sendDone ? seq : -seq;
2568 }
2569
2570 Object retrievePendingEvent(int seq) {
2571 if (seq < 0) seq = -seq;
2572 Object event = mPendingEvents.get(seq);
2573 if (event != null) {
2574 mPendingEvents.remove(seq);
2575 }
2576 return event;
2577 }
Romain Guy8506ab42009-06-11 17:35:47 -07002578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002580 // If there is no view, then the event will not be handled.
2581 if (mView == null || !mAdded) {
2582 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 return;
2584 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002585
2586 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2587
2588 // Perform predispatching before the IME.
2589 if (mView.dispatchKeyEventPreIme(event)) {
2590 finishKeyEvent(event, sendDone, true);
2591 return;
2592 }
2593
2594 // Dispatch to the IME before propagating down the view hierarchy.
2595 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 if (mLastWasImTarget) {
2597 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002598 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 int seq = enqueuePendingEvent(event, sendDone);
2600 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2601 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002602 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 return;
2604 }
2605 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002606
2607 // Not dispatching to IME, continue with post IME actions.
2608 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
2610
Jeff Brown3915bb82010-11-05 15:02:16 -07002611 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2613 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2614 + " handled=" + handled + " event=" + event);
2615 if (event != null) {
2616 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002617 if (handled) {
2618 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002620 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
2622 }
2623 }
Romain Guy8506ab42009-06-11 17:35:47 -07002624
Jeff Brown3915bb82010-11-05 15:02:16 -07002625 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2626 // If the view went away, then the event will not be handled.
2627 if (mView == null || !mAdded) {
2628 finishKeyEvent(event, sendDone, false);
2629 return;
2630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631
Jeff Brown3915bb82010-11-05 15:02:16 -07002632 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2633 if (checkForLeavingTouchModeAndConsume(event)) {
2634 finishKeyEvent(event, sendDone, true);
2635 return;
2636 }
Romain Guy8506ab42009-06-11 17:35:47 -07002637
Jeff Brown3915bb82010-11-05 15:02:16 -07002638 if (Config.LOGV) {
2639 captureKeyLog("captureDispatchKeyEvent", event);
2640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641
Jeff Brown90655042010-12-02 13:50:46 -08002642 // Make sure the fallback event policy sees all keys that will be delivered to the
2643 // view hierarchy.
2644 mFallbackEventHandler.preDispatchKeyEvent(event);
2645
Jeff Brown3915bb82010-11-05 15:02:16 -07002646 // Deliver the key to the view hierarchy.
2647 if (mView.dispatchKeyEvent(event)) {
2648 finishKeyEvent(event, sendDone, true);
2649 return;
2650 }
Joe Onorato86f67862010-11-05 18:57:34 -07002651
Jeff Brownc1df9072010-12-21 16:38:50 -08002652 // If the Control modifier is held, try to interpret the key as a shortcut.
2653 if (event.getAction() == KeyEvent.ACTION_UP
2654 && event.isCtrlPressed()
2655 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2656 if (mView.dispatchKeyShortcutEvent(event)) {
2657 finishKeyEvent(event, sendDone, true);
2658 return;
2659 }
2660 }
2661
Jeff Brown3915bb82010-11-05 15:02:16 -07002662 // Apply the fallback event policy.
2663 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2664 finishKeyEvent(event, sendDone, true);
2665 return;
2666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667
Jeff Brown3915bb82010-11-05 15:02:16 -07002668 // Handle automatic focus changes.
2669 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2670 int direction = 0;
2671 switch (event.getKeyCode()) {
2672 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002673 if (event.hasNoModifiers()) {
2674 direction = View.FOCUS_LEFT;
2675 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002676 break;
2677 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002678 if (event.hasNoModifiers()) {
2679 direction = View.FOCUS_RIGHT;
2680 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002681 break;
2682 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002683 if (event.hasNoModifiers()) {
2684 direction = View.FOCUS_UP;
2685 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002686 break;
2687 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002688 if (event.hasNoModifiers()) {
2689 direction = View.FOCUS_DOWN;
2690 }
2691 break;
2692 case KeyEvent.KEYCODE_TAB:
2693 if (event.hasNoModifiers()) {
2694 direction = View.FOCUS_FORWARD;
2695 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2696 direction = View.FOCUS_BACKWARD;
2697 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002698 break;
2699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700
Jeff Brown3915bb82010-11-05 15:02:16 -07002701 if (direction != 0) {
2702 View focused = mView != null ? mView.findFocus() : null;
2703 if (focused != null) {
2704 View v = focused.focusSearch(direction);
2705 if (v != null && v != focused) {
2706 // do the math the get the interesting rect
2707 // of previous focused into the coord system of
2708 // newly focused view
2709 focused.getFocusedRect(mTempRect);
2710 if (mView instanceof ViewGroup) {
2711 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2712 focused, mTempRect);
2713 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2714 v, mTempRect);
2715 }
2716 if (v.requestFocus(direction, mTempRect)) {
2717 playSoundEffect(
2718 SoundEffectConstants.getContantForFocusDirection(direction));
2719 finishKeyEvent(event, sendDone, true);
2720 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002723
2724 // Give the focused view a last chance to handle the dpad key.
2725 if (mView.dispatchUnhandledMove(focused, direction)) {
2726 finishKeyEvent(event, sendDone, true);
2727 return;
2728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
2730 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732
Jeff Brown3915bb82010-11-05 15:02:16 -07002733 // Key was unhandled.
2734 finishKeyEvent(event, sendDone, false);
2735 }
2736
2737 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2738 if (sendDone) {
2739 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 }
2741 }
2742
Christopher Tatea53146c2010-09-07 11:57:52 -07002743 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002744 void setLocalDragState(Object obj) {
2745 mLocalDragState = obj;
2746 }
2747
Christopher Tatea53146c2010-09-07 11:57:52 -07002748 private void handleDragEvent(DragEvent event) {
2749 // From the root, only drag start/end/location are dispatched. entered/exited
2750 // are determined and dispatched by the viewgroup hierarchy, who then report
2751 // that back here for ultimate reporting back to the framework.
2752 if (mView != null && mAdded) {
2753 final int what = event.mAction;
2754
2755 if (what == DragEvent.ACTION_DRAG_EXITED) {
2756 // A direct EXITED event means that the window manager knows we've just crossed
2757 // a window boundary, so the current drag target within this one must have
2758 // just been exited. Send it the usual notifications and then we're done
2759 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002760 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002761 } else {
2762 // Cache the drag description when the operation starts, then fill it in
2763 // on subsequent calls as a convenience
2764 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002765 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002766 mDragDescription = event.mClipDescription;
2767 } else {
2768 event.mClipDescription = mDragDescription;
2769 }
2770
2771 // For events with a [screen] location, translate into window coordinates
2772 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2773 mDragPoint.set(event.mX, event.mY);
2774 if (mTranslator != null) {
2775 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2776 }
2777
2778 if (mCurScrollY != 0) {
2779 mDragPoint.offset(0, mCurScrollY);
2780 }
2781
2782 event.mX = mDragPoint.x;
2783 event.mY = mDragPoint.y;
2784 }
2785
2786 // Remember who the current drag target is pre-dispatch
2787 final View prevDragView = mCurrentDragView;
2788
2789 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002790 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002791
2792 // If we changed apparent drag target, tell the OS about it
2793 if (prevDragView != mCurrentDragView) {
2794 try {
2795 if (prevDragView != null) {
2796 sWindowSession.dragRecipientExited(mWindow);
2797 }
2798 if (mCurrentDragView != null) {
2799 sWindowSession.dragRecipientEntered(mWindow);
2800 }
2801 } catch (RemoteException e) {
2802 Slog.e(TAG, "Unable to note drag target change");
2803 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002804 }
Chris Tated4533f12010-10-19 15:15:08 -07002805
Christopher Tate407b4e92010-11-30 17:14:08 -08002806 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002807 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002808 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002809 try {
2810 Log.i(TAG, "Reporting drop result: " + result);
2811 sWindowSession.reportDropResult(mWindow, result);
2812 } catch (RemoteException e) {
2813 Log.e(TAG, "Unable to report drop result");
2814 }
2815 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002816
2817 // When the drag operation ends, release any local state object
2818 // that may have been in use
2819 if (what == DragEvent.ACTION_DRAG_ENDED) {
2820 setLocalDragState(null);
2821 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002822 }
2823 }
2824 event.recycle();
2825 }
2826
Christopher Tate2c095f32010-10-04 14:13:40 -07002827 public void getLastTouchPoint(Point outLocation) {
2828 outLocation.x = (int) mLastTouchPoint.x;
2829 outLocation.y = (int) mLastTouchPoint.y;
2830 }
2831
Chris Tate9d1ab882010-11-02 15:55:39 -07002832 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002833 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002834 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002835 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002836 }
2837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 private AudioManager getAudioManager() {
2839 if (mView == null) {
2840 throw new IllegalStateException("getAudioManager called when there is no mView");
2841 }
2842 if (mAudioManager == null) {
2843 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2844 }
2845 return mAudioManager;
2846 }
2847
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002848 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2849 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002850
2851 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002852 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002853 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002854 restore = true;
2855 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002856 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002857 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002858 if (params != null) {
2859 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002860 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002861 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002862 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002863 int relayoutResult = sWindowSession.relayout(
2864 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002865 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2866 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002867 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002868 mPendingContentInsets, mPendingVisibleInsets,
2869 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002870 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002871 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002872 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002873 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002874
2875 if (mTranslator != null) {
2876 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2877 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2878 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002879 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002880 return relayoutResult;
2881 }
Romain Guy8506ab42009-06-11 17:35:47 -07002882
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002883 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 * {@inheritDoc}
2885 */
2886 public void playSoundEffect(int effectId) {
2887 checkThread();
2888
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002889 try {
2890 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002892 switch (effectId) {
2893 case SoundEffectConstants.CLICK:
2894 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2895 return;
2896 case SoundEffectConstants.NAVIGATION_DOWN:
2897 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2898 return;
2899 case SoundEffectConstants.NAVIGATION_LEFT:
2900 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2901 return;
2902 case SoundEffectConstants.NAVIGATION_RIGHT:
2903 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2904 return;
2905 case SoundEffectConstants.NAVIGATION_UP:
2906 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2907 return;
2908 default:
2909 throw new IllegalArgumentException("unknown effect id " + effectId +
2910 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2911 }
2912 } catch (IllegalStateException e) {
2913 // Exception thrown by getAudioManager() when mView is null
2914 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2915 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
2917 }
2918
2919 /**
2920 * {@inheritDoc}
2921 */
2922 public boolean performHapticFeedback(int effectId, boolean always) {
2923 try {
2924 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2925 } catch (RemoteException e) {
2926 return false;
2927 }
2928 }
2929
2930 /**
2931 * {@inheritDoc}
2932 */
2933 public View focusSearch(View focused, int direction) {
2934 checkThread();
2935 if (!(mView instanceof ViewGroup)) {
2936 return null;
2937 }
2938 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2939 }
2940
2941 public void debug() {
2942 mView.debug();
2943 }
2944
2945 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002946 if (immediate) {
2947 doDie();
2948 } else {
2949 sendEmptyMessage(DIE);
2950 }
2951 }
2952
2953 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002955 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 synchronized (this) {
2957 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002958 destroyHardwareRenderer();
2959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 int viewVisibility = mView.getVisibility();
2961 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2962 if (mWindowAttributesChanged || viewVisibilityChanged) {
2963 // If layout params have been changed, first give them
2964 // to the window manager to make sure it has the correct
2965 // animation info.
2966 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002967 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2968 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 sWindowSession.finishDrawing(mWindow);
2970 }
2971 } catch (RemoteException e) {
2972 }
2973 }
2974
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002975 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 }
2977 if (mAdded) {
2978 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002979 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 }
2981 }
2982 }
2983
Romain Guy29d89972010-09-22 16:10:57 -07002984 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002985 if (mAttachInfo.mHardwareRenderer != null) {
2986 mAttachInfo.mHardwareRenderer.destroy(true);
2987 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002988 mAttachInfo.mHardwareAccelerated = false;
2989 }
2990 }
2991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 public void dispatchFinishedEvent(int seq, boolean handled) {
2993 Message msg = obtainMessage(FINISHED_EVENT);
2994 msg.arg1 = seq;
2995 msg.arg2 = handled ? 1 : 0;
2996 sendMessage(msg);
2997 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003000 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3002 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3003 + " visibleInsets=" + visibleInsets.toShortString()
3004 + " reportDraw=" + reportDraw);
3005 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003006 if (mTranslator != null) {
3007 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3008 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3009 w *= mTranslator.applicationInvertedScale;
3010 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003011 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003012 msg.arg1 = w;
3013 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003014 ResizedInfo ri = new ResizedInfo();
3015 ri.coveredInsets = new Rect(coveredInsets);
3016 ri.visibleInsets = new Rect(visibleInsets);
3017 ri.newConfig = newConfig;
3018 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 sendMessage(msg);
3020 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003021
Jeff Brown3915bb82010-11-05 15:02:16 -07003022 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003023
3024 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003025 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003026 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003027 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003028 }
3029
Jeff Brown3915bb82010-11-05 15:02:16 -07003030 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003031 startInputEvent(finishedCallback);
3032 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003033 }
3034 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035
3036 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003037 dispatchKey(event, false);
3038 }
3039
3040 private void dispatchKey(KeyEvent event, boolean sendDone) {
3041 //noinspection ConstantConditions
3042 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3043 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003044 if (DBG) Log.d("keydisp", "===================================================");
3045 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 debug();
3048
Romain Guy812ccbe2010-06-01 14:07:24 -07003049 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 }
3051 }
3052
3053 Message msg = obtainMessage(DISPATCH_KEY);
3054 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003055 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056
3057 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003058 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059
3060 sendMessageAtTime(msg, event.getEventTime());
3061 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003062
3063 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003064 dispatchMotion(event, false);
3065 }
3066
3067 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003068 int source = event.getSource();
3069 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003070 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003071 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003072 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003073 } else {
3074 // TODO
3075 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003076 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003077 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003078 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003079 }
3080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003082 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003083 dispatchPointer(event, false);
3084 }
3085
3086 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 Message msg = obtainMessage(DISPATCH_POINTER);
3088 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003089 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003090 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 }
3092
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003093 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003094 dispatchTrackball(event, false);
3095 }
3096
3097 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3099 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003100 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003101 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 public void dispatchAppVisibility(boolean visible) {
3105 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3106 msg.arg1 = visible ? 1 : 0;
3107 sendMessage(msg);
3108 }
3109
3110 public void dispatchGetNewSurface() {
3111 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3112 sendMessage(msg);
3113 }
3114
3115 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3116 Message msg = Message.obtain();
3117 msg.what = WINDOW_FOCUS_CHANGED;
3118 msg.arg1 = hasFocus ? 1 : 0;
3119 msg.arg2 = inTouchMode ? 1 : 0;
3120 sendMessage(msg);
3121 }
3122
Dianne Hackbornffa42482009-09-23 22:20:11 -07003123 public void dispatchCloseSystemDialogs(String reason) {
3124 Message msg = Message.obtain();
3125 msg.what = CLOSE_SYSTEM_DIALOGS;
3126 msg.obj = reason;
3127 sendMessage(msg);
3128 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003129
3130 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003131 final int what;
3132 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3133 what = DISPATCH_DRAG_LOCATION_EVENT;
3134 removeMessages(what);
3135 } else {
3136 what = DISPATCH_DRAG_EVENT;
3137 }
3138 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003139 sendMessage(msg);
3140 }
3141
svetoslavganov75986cf2009-05-14 22:28:01 -07003142 /**
3143 * The window is getting focus so if there is anything focused/selected
3144 * send an {@link AccessibilityEvent} to announce that.
3145 */
3146 private void sendAccessibilityEvents() {
3147 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3148 return;
3149 }
3150 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3151 View focusedView = mView.findFocus();
3152 if (focusedView != null && focusedView != mView) {
3153 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3154 }
3155 }
3156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 public boolean showContextMenuForChild(View originalView) {
3158 return false;
3159 }
3160
Adam Powell6e346362010-07-23 10:18:23 -07003161 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3162 return null;
3163 }
3164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 public void createContextMenu(ContextMenu menu) {
3166 }
3167
3168 public void childDrawableStateChanged(View child) {
3169 }
3170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 void checkThread() {
3172 if (mThread != Thread.currentThread()) {
3173 throw new CalledFromWrongThreadException(
3174 "Only the original thread that created a view hierarchy can touch its views.");
3175 }
3176 }
3177
3178 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3179 // ViewRoot never intercepts touch event, so this can be a no-op
3180 }
3181
3182 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3183 boolean immediate) {
3184 return scrollToRectOrFocus(rectangle, immediate);
3185 }
Romain Guy8506ab42009-06-11 17:35:47 -07003186
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003187 class TakenSurfaceHolder extends BaseSurfaceHolder {
3188 @Override
3189 public boolean onAllowLockCanvas() {
3190 return mDrawingAllowed;
3191 }
3192
3193 @Override
3194 public void onRelayoutContainer() {
3195 // Not currently interesting -- from changing between fixed and layout size.
3196 }
3197
3198 public void setFormat(int format) {
3199 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3200 }
3201
3202 public void setType(int type) {
3203 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3204 }
3205
3206 @Override
3207 public void onUpdateSurface() {
3208 // We take care of format and type changes on our own.
3209 throw new IllegalStateException("Shouldn't be here");
3210 }
3211
3212 public boolean isCreating() {
3213 return mIsCreating;
3214 }
3215
3216 @Override
3217 public void setFixedSize(int width, int height) {
3218 throw new UnsupportedOperationException(
3219 "Currently only support sizing from layout");
3220 }
3221
3222 public void setKeepScreenOn(boolean screenOn) {
3223 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3224 }
3225 }
3226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 static class InputMethodCallback extends IInputMethodCallback.Stub {
3228 private WeakReference<ViewRoot> mViewRoot;
3229
3230 public InputMethodCallback(ViewRoot viewRoot) {
3231 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3232 }
Romain Guy8506ab42009-06-11 17:35:47 -07003233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 public void finishedEvent(int seq, boolean handled) {
3235 final ViewRoot viewRoot = mViewRoot.get();
3236 if (viewRoot != null) {
3237 viewRoot.dispatchFinishedEvent(seq, handled);
3238 }
3239 }
3240
3241 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3242 // Stub -- not for use in the client.
3243 }
3244 }
Romain Guy8506ab42009-06-11 17:35:47 -07003245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003247 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248
Romain Guyfb8b7632010-08-23 21:05:08 -07003249 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3251 }
3252
Romain Guyfb8b7632010-08-23 21:05:08 -07003253 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3254 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 final ViewRoot viewRoot = mViewRoot.get();
3256 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003257 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
3259 }
3260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 public void dispatchAppVisibility(boolean visible) {
3262 final ViewRoot viewRoot = mViewRoot.get();
3263 if (viewRoot != null) {
3264 viewRoot.dispatchAppVisibility(visible);
3265 }
3266 }
3267
3268 public void dispatchGetNewSurface() {
3269 final ViewRoot viewRoot = mViewRoot.get();
3270 if (viewRoot != null) {
3271 viewRoot.dispatchGetNewSurface();
3272 }
3273 }
3274
3275 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3276 final ViewRoot viewRoot = mViewRoot.get();
3277 if (viewRoot != null) {
3278 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3279 }
3280 }
3281
3282 private static int checkCallingPermission(String permission) {
3283 if (!Process.supportsProcesses()) {
3284 return PackageManager.PERMISSION_GRANTED;
3285 }
3286
3287 try {
3288 return ActivityManagerNative.getDefault().checkPermission(
3289 permission, Binder.getCallingPid(), Binder.getCallingUid());
3290 } catch (RemoteException e) {
3291 return PackageManager.PERMISSION_DENIED;
3292 }
3293 }
3294
3295 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3296 final ViewRoot viewRoot = mViewRoot.get();
3297 if (viewRoot != null) {
3298 final View view = viewRoot.mView;
3299 if (view != null) {
3300 if (checkCallingPermission(Manifest.permission.DUMP) !=
3301 PackageManager.PERMISSION_GRANTED) {
3302 throw new SecurityException("Insufficient permissions to invoke"
3303 + " executeCommand() from pid=" + Binder.getCallingPid()
3304 + ", uid=" + Binder.getCallingUid());
3305 }
3306
3307 OutputStream clientStream = null;
3308 try {
3309 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3310 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3311 } catch (IOException e) {
3312 e.printStackTrace();
3313 } finally {
3314 if (clientStream != null) {
3315 try {
3316 clientStream.close();
3317 } catch (IOException e) {
3318 e.printStackTrace();
3319 }
3320 }
3321 }
3322 }
3323 }
3324 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003325
Dianne Hackbornffa42482009-09-23 22:20:11 -07003326 public void closeSystemDialogs(String reason) {
3327 final ViewRoot viewRoot = mViewRoot.get();
3328 if (viewRoot != null) {
3329 viewRoot.dispatchCloseSystemDialogs(reason);
3330 }
3331 }
3332
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003333 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3334 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003335 if (sync) {
3336 try {
3337 sWindowSession.wallpaperOffsetsComplete(asBinder());
3338 } catch (RemoteException e) {
3339 }
3340 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003341 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003342
3343 public void dispatchWallpaperCommand(String action, int x, int y,
3344 int z, Bundle extras, boolean sync) {
3345 if (sync) {
3346 try {
3347 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3348 } catch (RemoteException e) {
3349 }
3350 }
3351 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003352
3353 /* Drag/drop */
3354 public void dispatchDragEvent(DragEvent event) {
3355 final ViewRoot viewRoot = mViewRoot.get();
3356 if (viewRoot != null) {
3357 viewRoot.dispatchDragEvent(event);
3358 }
3359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 }
3361
3362 /**
3363 * Maintains state information for a single trackball axis, generating
3364 * discrete (DPAD) movements based on raw trackball motion.
3365 */
3366 static final class TrackballAxis {
3367 /**
3368 * The maximum amount of acceleration we will apply.
3369 */
3370 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 /**
3373 * The maximum amount of time (in milliseconds) between events in order
3374 * for us to consider the user to be doing fast trackball movements,
3375 * and thus apply an acceleration.
3376 */
3377 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 /**
3380 * Scaling factor to the time (in milliseconds) between events to how
3381 * much to multiple/divide the current acceleration. When movement
3382 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3383 * FAST_MOVE_TIME it divides it.
3384 */
3385 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 float position;
3388 float absPosition;
3389 float acceleration = 1;
3390 long lastMoveTime = 0;
3391 int step;
3392 int dir;
3393 int nonAccelMovement;
3394
3395 void reset(int _step) {
3396 position = 0;
3397 acceleration = 1;
3398 lastMoveTime = 0;
3399 step = _step;
3400 dir = 0;
3401 }
3402
3403 /**
3404 * Add trackball movement into the state. If the direction of movement
3405 * has been reversed, the state is reset before adding the
3406 * movement (so that you don't have to compensate for any previously
3407 * collected movement before see the result of the movement in the
3408 * new direction).
3409 *
3410 * @return Returns the absolute value of the amount of movement
3411 * collected so far.
3412 */
3413 float collect(float off, long time, String axis) {
3414 long normTime;
3415 if (off > 0) {
3416 normTime = (long)(off * FAST_MOVE_TIME);
3417 if (dir < 0) {
3418 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3419 position = 0;
3420 step = 0;
3421 acceleration = 1;
3422 lastMoveTime = 0;
3423 }
3424 dir = 1;
3425 } else if (off < 0) {
3426 normTime = (long)((-off) * FAST_MOVE_TIME);
3427 if (dir > 0) {
3428 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3429 position = 0;
3430 step = 0;
3431 acceleration = 1;
3432 lastMoveTime = 0;
3433 }
3434 dir = -1;
3435 } else {
3436 normTime = 0;
3437 }
Romain Guy8506ab42009-06-11 17:35:47 -07003438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 // The number of milliseconds between each movement that is
3440 // considered "normal" and will not result in any acceleration
3441 // or deceleration, scaled by the offset we have here.
3442 if (normTime > 0) {
3443 long delta = time - lastMoveTime;
3444 lastMoveTime = time;
3445 float acc = acceleration;
3446 if (delta < normTime) {
3447 // The user is scrolling rapidly, so increase acceleration.
3448 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3449 if (scale > 1) acc *= scale;
3450 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3451 + off + " normTime=" + normTime + " delta=" + delta
3452 + " scale=" + scale + " acc=" + acc);
3453 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3454 } else {
3455 // The user is scrolling slowly, so decrease acceleration.
3456 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3457 if (scale > 1) acc /= scale;
3458 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3459 + off + " normTime=" + normTime + " delta=" + delta
3460 + " scale=" + scale + " acc=" + acc);
3461 acceleration = acc > 1 ? acc : 1;
3462 }
3463 }
3464 position += off;
3465 return (absPosition = Math.abs(position));
3466 }
3467
3468 /**
3469 * Generate the number of discrete movement events appropriate for
3470 * the currently collected trackball movement.
3471 *
3472 * @param precision The minimum movement required to generate the
3473 * first discrete movement.
3474 *
3475 * @return Returns the number of discrete movements, either positive
3476 * or negative, or 0 if there is not enough trackball movement yet
3477 * for a discrete movement.
3478 */
3479 int generate(float precision) {
3480 int movement = 0;
3481 nonAccelMovement = 0;
3482 do {
3483 final int dir = position >= 0 ? 1 : -1;
3484 switch (step) {
3485 // If we are going to execute the first step, then we want
3486 // to do this as soon as possible instead of waiting for
3487 // a full movement, in order to make things look responsive.
3488 case 0:
3489 if (absPosition < precision) {
3490 return movement;
3491 }
3492 movement += dir;
3493 nonAccelMovement += dir;
3494 step = 1;
3495 break;
3496 // If we have generated the first movement, then we need
3497 // to wait for the second complete trackball motion before
3498 // generating the second discrete movement.
3499 case 1:
3500 if (absPosition < 2) {
3501 return movement;
3502 }
3503 movement += dir;
3504 nonAccelMovement += dir;
3505 position += dir > 0 ? -2 : 2;
3506 absPosition = Math.abs(position);
3507 step = 2;
3508 break;
3509 // After the first two, we generate discrete movements
3510 // consistently with the trackball, applying an acceleration
3511 // if the trackball is moving quickly. This is a simple
3512 // acceleration on top of what we already compute based
3513 // on how quickly the wheel is being turned, to apply
3514 // a longer increasing acceleration to continuous movement
3515 // in one direction.
3516 default:
3517 if (absPosition < 1) {
3518 return movement;
3519 }
3520 movement += dir;
3521 position += dir >= 0 ? -1 : 1;
3522 absPosition = Math.abs(position);
3523 float acc = acceleration;
3524 acc *= 1.1f;
3525 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3526 break;
3527 }
3528 } while (true);
3529 }
3530 }
3531
3532 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3533 public CalledFromWrongThreadException(String msg) {
3534 super(msg);
3535 }
3536 }
3537
3538 private SurfaceHolder mHolder = new SurfaceHolder() {
3539 // we only need a SurfaceHolder for opengl. it would be nice
3540 // to implement everything else though, especially the callback
3541 // support (opengl doesn't make use of it right now, but eventually
3542 // will).
3543 public Surface getSurface() {
3544 return mSurface;
3545 }
3546
3547 public boolean isCreating() {
3548 return false;
3549 }
3550
3551 public void addCallback(Callback callback) {
3552 }
3553
3554 public void removeCallback(Callback callback) {
3555 }
3556
3557 public void setFixedSize(int width, int height) {
3558 }
3559
3560 public void setSizeFromLayout() {
3561 }
3562
3563 public void setFormat(int format) {
3564 }
3565
3566 public void setType(int type) {
3567 }
3568
3569 public void setKeepScreenOn(boolean screenOn) {
3570 }
3571
3572 public Canvas lockCanvas() {
3573 return null;
3574 }
3575
3576 public Canvas lockCanvas(Rect dirty) {
3577 return null;
3578 }
3579
3580 public void unlockCanvasAndPost(Canvas canvas) {
3581 }
3582 public Rect getSurfaceFrame() {
3583 return null;
3584 }
3585 };
3586
3587 static RunQueue getRunQueue() {
3588 RunQueue rq = sRunQueues.get();
3589 if (rq != null) {
3590 return rq;
3591 }
3592 rq = new RunQueue();
3593 sRunQueues.set(rq);
3594 return rq;
3595 }
Romain Guy8506ab42009-06-11 17:35:47 -07003596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 /**
3598 * @hide
3599 */
3600 static final class RunQueue {
3601 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3602
3603 void post(Runnable action) {
3604 postDelayed(action, 0);
3605 }
3606
3607 void postDelayed(Runnable action, long delayMillis) {
3608 HandlerAction handlerAction = new HandlerAction();
3609 handlerAction.action = action;
3610 handlerAction.delay = delayMillis;
3611
3612 synchronized (mActions) {
3613 mActions.add(handlerAction);
3614 }
3615 }
3616
3617 void removeCallbacks(Runnable action) {
3618 final HandlerAction handlerAction = new HandlerAction();
3619 handlerAction.action = action;
3620
3621 synchronized (mActions) {
3622 final ArrayList<HandlerAction> actions = mActions;
3623
3624 while (actions.remove(handlerAction)) {
3625 // Keep going
3626 }
3627 }
3628 }
3629
3630 void executeActions(Handler handler) {
3631 synchronized (mActions) {
3632 final ArrayList<HandlerAction> actions = mActions;
3633 final int count = actions.size();
3634
3635 for (int i = 0; i < count; i++) {
3636 final HandlerAction handlerAction = actions.get(i);
3637 handler.postDelayed(handlerAction.action, handlerAction.delay);
3638 }
3639
Romain Guy15df6702009-08-17 20:17:30 -07003640 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642 }
3643
3644 private static class HandlerAction {
3645 Runnable action;
3646 long delay;
3647
3648 @Override
3649 public boolean equals(Object o) {
3650 if (this == o) return true;
3651 if (o == null || getClass() != o.getClass()) return false;
3652
3653 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 return !(action != null ? !action.equals(that.action) : that.action != null);
3655
3656 }
3657
3658 @Override
3659 public int hashCode() {
3660 int result = action != null ? action.hashCode() : 0;
3661 result = 31 * result + (int) (delay ^ (delay >>> 32));
3662 return result;
3663 }
3664 }
3665 }
3666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668}